2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * @author Philip Pronin (philipp@fb.com)
20 * Based on the paper by Sebastiano Vigna,
21 * "Quasi-succinct indices" (arxiv:1206.4300).
29 #include <type_traits>
31 #include <folly/Bits.h>
32 #include <folly/Likely.h>
33 #include <folly/Portability.h>
34 #include <folly/Range.h>
35 #include <folly/experimental/Instructions.h>
36 #include <folly/experimental/Select64.h>
37 #include <glog/logging.h>
40 #error EliasFanoCoding.h requires x86_64
43 namespace folly { namespace compression {
45 static_assert(kIsLittleEndian, "EliasFanoCoding.h requires little endianness");
47 template <class Pointer>
48 struct EliasFanoCompressedListBase {
49 EliasFanoCompressedListBase() = default;
51 template <class OtherPointer>
52 EliasFanoCompressedListBase(
53 const EliasFanoCompressedListBase<OtherPointer>& other)
55 numLowerBits(other.numLowerBits),
57 skipPointers(reinterpret_cast<Pointer>(other.skipPointers)),
58 forwardPointers(reinterpret_cast<Pointer>(other.forwardPointers)),
59 lower(reinterpret_cast<Pointer>(other.lower)),
60 upper(reinterpret_cast<Pointer>(other.upper)) { }
62 template <class T = Pointer>
63 auto free() -> decltype(::free(T(nullptr))) {
64 return ::free(data.data());
67 size_t upperSize() const {
68 return size_t(data.end() - upper);
72 uint8_t numLowerBits = 0;
74 // WARNING: EliasFanoCompressedList has no ownership of data. The 7
75 // bytes following the last byte should be readable.
76 folly::Range<Pointer> data;
78 Pointer skipPointers = nullptr;
79 Pointer forwardPointers = nullptr;
80 Pointer lower = nullptr;
81 Pointer upper = nullptr;
84 typedef EliasFanoCompressedListBase<const uint8_t*> EliasFanoCompressedList;
85 typedef EliasFanoCompressedListBase<uint8_t*> MutableEliasFanoCompressedList;
87 template <class Value,
88 class SkipValue = size_t,
89 size_t kSkipQuantum = 0, // 0 = disabled
90 size_t kForwardQuantum = 0> // 0 = disabled
91 struct EliasFanoEncoderV2 {
92 static_assert(std::is_integral<Value>::value &&
93 std::is_unsigned<Value>::value,
94 "Value should be unsigned integral");
96 typedef EliasFanoCompressedList CompressedList;
97 typedef MutableEliasFanoCompressedList MutableCompressedList;
99 typedef Value ValueType;
100 typedef SkipValue SkipValueType;
103 static constexpr size_t skipQuantum = kSkipQuantum;
104 static constexpr size_t forwardQuantum = kForwardQuantum;
106 static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
107 if (UNLIKELY(size == 0 || upperBound < size)) {
110 // Result that should be returned is "floor(log(upperBound / size))".
111 // In order to avoid expensive division, we rely on
112 // "floor(a) - floor(b) - 1 <= floor(a - b) <= floor(a) - floor(b)".
113 // Assuming "candidate = floor(log(upperBound)) - floor(log(upperBound))",
114 // then result is either "candidate - 1" or "candidate".
115 auto candidate = folly::findLastSet(upperBound) - folly::findLastSet(size);
116 // NOTE: As size != 0, "candidate" is always < 64.
117 return (size > (upperBound >> candidate)) ? candidate - 1 : candidate;
120 // Requires: input range (begin, end) is sorted (encoding
121 // crashes if it's not).
122 // WARNING: encode() mallocates EliasFanoCompressedList::data. As
123 // EliasFanoCompressedList has no ownership of it, you need to call
124 // free() explicitly.
125 template <class RandomAccessIterator>
126 static MutableCompressedList encode(RandomAccessIterator begin,
127 RandomAccessIterator end) {
129 return MutableCompressedList();
131 EliasFanoEncoderV2 encoder(size_t(end - begin), *(end - 1));
132 for (; begin != end; ++begin) {
135 return encoder.finish();
138 explicit EliasFanoEncoderV2(const MutableCompressedList& result)
139 : lower_(result.lower),
140 upper_(result.upper),
141 skipPointers_(reinterpret_cast<SkipValueType*>(
142 result.skipPointers)),
143 forwardPointers_(reinterpret_cast<SkipValueType*>(
144 result.forwardPointers)),
146 std::fill(result.data.begin(), result.data.end(), 0);
149 EliasFanoEncoderV2(size_t size, ValueType upperBound)
150 : EliasFanoEncoderV2(
151 Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
153 void add(ValueType value) {
154 CHECK_LT(value, std::numeric_limits<ValueType>::max());
155 CHECK_GE(value, lastValue_);
157 const auto numLowerBits = result_.numLowerBits;
158 const ValueType upperBits = value >> numLowerBits;
160 // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
161 const size_t pos = upperBits + size_;
162 upper_[pos / 8] |= 1U << (pos % 8);
163 // Append numLowerBits bits to lower sequence.
164 if (numLowerBits != 0) {
165 const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
166 writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
169 /* static */ if (skipQuantum != 0) {
170 while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
171 // Store the number of preceding 1-bits.
172 skipPointers_[skipPointersSize_++] = SkipValue(size_);
176 /* static */ if (forwardQuantum != 0) {
177 if ((size_ + 1) % forwardQuantum == 0) {
178 const auto k = size_ / forwardQuantum;
179 // Store the number of preceding 0-bits.
180 forwardPointers_[k] = upperBits;
188 const MutableCompressedList& finish() const {
189 CHECK_EQ(size_, result_.size);
194 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
195 static void writeBits56(unsigned char* data, size_t pos,
196 uint8_t len, uint64_t value) {
197 DCHECK_LE(uint32_t(len), 56);
198 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
199 unsigned char* const ptr = data + (pos / 8);
200 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
201 ptrv |= value << (pos % 8);
202 folly::storeUnaligned<uint64_t>(ptr, ptrv);
205 unsigned char* lower_ = nullptr;
206 unsigned char* upper_ = nullptr;
207 SkipValueType* skipPointers_ = nullptr;
208 SkipValueType* forwardPointers_ = nullptr;
210 ValueType lastValue_ = 0;
212 size_t skipPointersSize_ = 0;
214 MutableCompressedList result_;
217 template <class Value,
220 size_t kForwardQuantum>
221 struct EliasFanoEncoderV2<Value,
224 kForwardQuantum>::Layout {
225 static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
226 // numLowerBits can be at most 56 because of detail::writeBits56.
227 const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
231 // Upper bits are stored using unary delta encoding.
232 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
233 const size_t upperSizeBits =
234 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
236 const size_t upper = (upperSizeBits + 7) / 8;
238 // *** Validity checks.
239 // Shift by numLowerBits must be valid.
240 CHECK_LT(numLowerBits, 8 * sizeof(Value));
241 CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
242 CHECK_LT(upperBound >> numLowerBits,
243 std::numeric_limits<SkipValueType>::max());
245 return fromInternalSizes(numLowerBits, upper, size);
248 static Layout fromInternalSizes(uint8_t numLowerBits,
253 layout.numLowerBits = numLowerBits;
255 layout.lower = (numLowerBits * size + 7) / 8;
256 layout.upper = upper;
258 // *** Skip pointers.
259 // Store (1-indexed) position of every skipQuantum-th
260 // 0-bit in upper bits sequence.
261 /* static */ if (skipQuantum != 0) {
262 // 8 * upper is used here instead of upperSizeBits, as that is
263 // more serialization-friendly way (upperSizeBits doesn't need
264 // to be known by this function, unlike upper).
266 size_t numSkipPointers = (8 * upper - size) / skipQuantum;
267 layout.skipPointers = numSkipPointers * sizeof(SkipValueType);
270 // *** Forward pointers.
271 // Store (1-indexed) position of every forwardQuantum-th
272 // 1-bit in upper bits sequence.
273 /* static */ if (forwardQuantum != 0) {
274 size_t numForwardPointers = size / forwardQuantum;
275 layout.forwardPointers = numForwardPointers * sizeof(SkipValueType);
281 size_t bytes() const {
282 return lower + upper + skipPointers + forwardPointers;
285 template <class Range>
286 EliasFanoCompressedListBase<typename Range::iterator>
287 openList(Range& buf) const {
288 EliasFanoCompressedListBase<typename Range::iterator> result;
290 result.numLowerBits = numLowerBits;
291 result.data = buf.subpiece(0, bytes());
293 auto advance = [&] (size_t n) {
294 auto begin = buf.data();
299 result.skipPointers = advance(skipPointers);
300 result.forwardPointers = advance(forwardPointers);
301 result.lower = advance(lower);
302 result.upper = advance(upper);
307 MutableCompressedList allocList() const {
308 uint8_t* buf = nullptr;
309 // WARNING: Current read/write logic assumes that the 7 bytes
310 // following the last byte of lower and upper sequences are
311 // readable (stored value doesn't matter and won't be changed), so
312 // we allocate additional 7 bytes, but do not include them in size
313 // of returned value.
315 buf = static_cast<uint8_t*>(malloc(bytes() + 7));
317 folly::MutableByteRange bufRange(buf, bytes());
318 return openList(bufRange);
322 uint8_t numLowerBits = 0;
327 size_t skipPointers = 0;
328 size_t forwardPointers = 0;
333 template <class Encoder, class Instructions>
334 class UpperBitsReader {
335 typedef typename Encoder::SkipValueType SkipValueType;
337 typedef typename Encoder::ValueType ValueType;
339 explicit UpperBitsReader(const typename Encoder::CompressedList& list)
340 : forwardPointers_(list.forwardPointers),
341 skipPointers_(list.skipPointers),
347 block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
349 inner_ = std::numeric_limits<size_t>::max();
350 position_ = std::numeric_limits<size_t>::max();
354 size_t position() const { return position_; }
355 ValueType value() const { return value_; }
358 // Skip to the first non-zero block.
359 while (block_ == 0) {
360 outer_ += sizeof(block_t);
361 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
365 inner_ = size_t(Instructions::ctz(block_));
366 block_ = Instructions::blsr(block_);
371 ValueType skip(size_t n) {
374 position_ += n; // n 1-bits will be read.
376 // Use forward pointer.
377 if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
378 const size_t steps = position_ / Encoder::forwardQuantum;
380 folly::loadUnaligned<SkipValueType>(
381 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
383 reposition(dest + steps * Encoder::forwardQuantum);
384 n = position_ + 1 - steps * Encoder::forwardQuantum; // n is > 0.
385 // Correct inner_ will be set at the end.
389 // Find necessary block.
390 while ((cnt = Instructions::popcount(block_)) < n) {
392 outer_ += sizeof(block_t);
393 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
396 // Skip to the n-th one in the block.
398 inner_ = select64<Instructions>(block_, n - 1);
399 block_ &= (block_t(-1) << inner_) << 1;
404 // Skip to the first element that is >= v and located *after* the current
405 // one (so even if current value equals v, position will be increased by 1).
406 ValueType skipToNext(ValueType v) {
407 DCHECK_GE(v, value_);
410 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
411 const size_t steps = v / Encoder::skipQuantum;
413 folly::loadUnaligned<SkipValueType>(
414 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
416 reposition(dest + Encoder::skipQuantum * steps);
417 position_ = dest - 1;
419 // Correct inner_ and value_ will be set during the next()
422 // NOTE: Corresponding block of lower bits sequence may be
423 // prefetched here (via __builtin_prefetch), but experiments
424 // didn't show any significant improvements.
429 size_t skip = v - (8 * outer_ - position_ - 1);
431 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
432 while ((cnt = Instructions::popcount(~block_)) < skip) {
434 position_ += kBitsPerBlock - cnt;
435 outer_ += sizeof(block_t);
436 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
440 auto inner = select64<Instructions>(~block_, skip - 1);
441 position_ += inner - skip + 1;
442 block_ &= block_t(-1) << inner;
449 ValueType jump(size_t n) {
450 if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
453 position_ = size_t(-1); // Avoid reading the head, skip() will reposition.
458 ValueType jumpToNext(ValueType v) {
459 if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
462 value_ = 0; // Avoid reading the head, skipToNext() will reposition.
464 return skipToNext(v);
467 ValueType previousValue() const {
468 DCHECK_NE(position(), -1);
469 DCHECK_GT(position(), 0);
471 size_t outer = outer_;
472 block_t block = folly::loadUnaligned<block_t>(start_ + outer);
473 block &= (block_t(1) << inner_) - 1;
475 while (UNLIKELY(block == 0)) {
477 outer -= std::min(sizeof(block_t), outer);
478 block = folly::loadUnaligned<block_t>(start_ + outer);
481 auto inner = 8 * sizeof(block_t) - 1 - Instructions::clz(block);
482 return static_cast<ValueType>(8 * outer + inner - (position_ - 1));
485 void setDone(size_t endPos) {
490 ValueType setValue() {
491 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
495 void reposition(size_t dest) {
497 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
498 block_ &= ~((block_t(1) << (dest % 8)) - 1);
501 typedef uint64_t block_t;
502 const unsigned char* const forwardPointers_;
503 const unsigned char* const skipPointers_;
504 const unsigned char* const start_;
506 size_t outer_; // Outer offset: number of consumed bytes in upper.
507 size_t inner_; // Inner offset: (bit) position in current block.
508 size_t position_; // Index of current value (= #reads - 1).
512 } // namespace detail
514 // If kUnchecked = true the caller must guarantee that all the
515 // operations return valid elements, i.e., they would never return
517 template <class Encoder,
518 class Instructions = instructions::Default,
519 bool kUnchecked = false>
520 class EliasFanoReader {
522 typedef Encoder EncoderType;
523 typedef typename Encoder::ValueType ValueType;
525 explicit EliasFanoReader(const typename Encoder::CompressedList& list)
529 lowerMask_((ValueType(1) << list.numLowerBits) - 1),
530 numLowerBits_(list.numLowerBits) {
531 DCHECK(Instructions::supported());
532 // To avoid extra branching during skipTo() while reading
533 // upper sequence we need to know the last element.
534 // If kUnchecked == true, we do not check that skipTo() is called
535 // within the bounds, so we can avoid initializing lastValue_.
536 if (kUnchecked || UNLIKELY(list.size == 0)) {
540 ValueType lastUpperValue = ValueType(8 * list.upperSize() - size_);
541 auto it = list.upper + list.upperSize() - 1;
543 lastUpperValue -= 8 - folly::findLastSet(*it);
544 lastValue_ = readLowerPart(size_ - 1) | (lastUpperValue << numLowerBits_);
549 value_ = kInvalidValue;
553 if (!kUnchecked && UNLIKELY(position() + 1 >= size_)) {
557 value_ = readLowerPart(upper_.position()) |
558 (upper_.value() << numLowerBits_);
562 bool skip(size_t n) {
565 if (kUnchecked || LIKELY(position() + n < size_)) {
566 if (LIKELY(n < kLinearScanThreshold)) {
567 for (size_t i = 0; i < n; ++i) upper_.next();
571 value_ = readLowerPart(upper_.position()) |
572 (upper_.value() << numLowerBits_);
579 bool skipTo(ValueType value) {
580 // Also works when value_ == kInvalidValue.
581 if (value != kInvalidValue) { DCHECK_GE(value + 1, value_ + 1); }
583 if (!kUnchecked && value > lastValue_) {
585 } else if (value == value_) {
589 ValueType upperValue = (value >> numLowerBits_);
590 ValueType upperSkip = upperValue - upper_.value();
591 // The average density of ones in upper bits is 1/2.
592 // LIKELY here seems to make things worse, even for small skips.
593 if (upperSkip < 2 * kLinearScanThreshold) {
596 } while (UNLIKELY(upper_.value() < upperValue));
598 upper_.skipToNext(upperValue);
605 bool jump(size_t n) {
606 if (LIKELY(n < size_)) { // Also checks that n != -1.
607 value_ = readLowerPart(n) | (upper_.jump(n + 1) << numLowerBits_);
613 bool jumpTo(ValueType value) {
614 if (!kUnchecked && value > lastValue_) {
618 upper_.jumpToNext(value >> numLowerBits_);
623 ValueType previousValue() const {
624 DCHECK_GT(position(), 0);
625 DCHECK_LT(position(), size());
626 return readLowerPart(upper_.position() - 1) |
627 (upper_.previousValue() << numLowerBits_);
630 size_t size() const { return size_; }
633 return position() < size(); // Also checks that position() != -1.
636 size_t position() const { return upper_.position(); }
637 ValueType value() const {
643 constexpr static ValueType kInvalidValue =
644 std::numeric_limits<ValueType>::max(); // Must hold kInvalidValue + 1 == 0.
647 value_ = kInvalidValue;
648 upper_.setDone(size_);
652 ValueType readLowerPart(size_t i) const {
654 const size_t pos = i * numLowerBits_;
655 const unsigned char* ptr = lower_ + (pos / 8);
656 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
657 return lowerMask_ & (ptrv >> (pos % 8));
660 void iterateTo(ValueType value) {
662 value_ = readLowerPart(upper_.position()) |
663 (upper_.value() << numLowerBits_);
664 if (LIKELY(value_ >= value)) break;
669 constexpr static size_t kLinearScanThreshold = 8;
672 const uint8_t* lower_;
673 detail::UpperBitsReader<Encoder, Instructions> upper_;
674 const ValueType lowerMask_;
675 ValueType value_ = kInvalidValue;
676 ValueType lastValue_;
677 uint8_t numLowerBits_;