2 * Copyright 2016 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 { return data.end() - upper; }
70 uint8_t numLowerBits = 0;
72 // WARNING: EliasFanoCompressedList has no ownership of data. The 7
73 // bytes following the last byte should be readable.
74 folly::Range<Pointer> data;
76 Pointer skipPointers = nullptr;
77 Pointer forwardPointers = nullptr;
78 Pointer lower = nullptr;
79 Pointer upper = nullptr;
82 typedef EliasFanoCompressedListBase<const uint8_t*> EliasFanoCompressedList;
83 typedef EliasFanoCompressedListBase<uint8_t*> MutableEliasFanoCompressedList;
85 template <class Value,
86 class SkipValue = size_t,
87 size_t kSkipQuantum = 0, // 0 = disabled
88 size_t kForwardQuantum = 0> // 0 = disabled
89 struct EliasFanoEncoderV2 {
90 static_assert(std::is_integral<Value>::value &&
91 std::is_unsigned<Value>::value,
92 "Value should be unsigned integral");
94 typedef EliasFanoCompressedList CompressedList;
95 typedef MutableEliasFanoCompressedList MutableCompressedList;
97 typedef Value ValueType;
98 typedef SkipValue SkipValueType;
101 static constexpr size_t skipQuantum = kSkipQuantum;
102 static constexpr size_t forwardQuantum = kForwardQuantum;
104 static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
105 if (size == 0 || upperBound < size) {
108 // floor(log(upperBound / size));
109 return folly::findLastSet(upperBound / size) - 1;
112 // Requires: input range (begin, end) is sorted (encoding
113 // crashes if it's not).
114 // WARNING: encode() mallocates EliasFanoCompressedList::data. As
115 // EliasFanoCompressedList has no ownership of it, you need to call
116 // free() explicitly.
117 template <class RandomAccessIterator>
118 static MutableCompressedList encode(RandomAccessIterator begin,
119 RandomAccessIterator end) {
121 return MutableCompressedList();
123 EliasFanoEncoderV2 encoder(end - begin, *(end - 1));
124 for (; begin != end; ++begin) {
127 return encoder.finish();
130 explicit EliasFanoEncoderV2(const MutableCompressedList& result)
131 : lower_(result.lower),
132 upper_(result.upper),
133 skipPointers_(reinterpret_cast<SkipValueType*>(
134 result.skipPointers)),
135 forwardPointers_(reinterpret_cast<SkipValueType*>(
136 result.forwardPointers)),
138 std::fill(result.data.begin(), result.data.end(), 0);
141 EliasFanoEncoderV2(size_t size, ValueType upperBound)
142 : EliasFanoEncoderV2(
143 Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
145 void add(ValueType value) {
146 CHECK_LT(value, std::numeric_limits<ValueType>::max());
147 CHECK_GE(value, lastValue_);
149 const auto numLowerBits = result_.numLowerBits;
150 const ValueType upperBits = value >> numLowerBits;
152 // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
153 const size_t pos = upperBits + size_;
154 upper_[pos / 8] |= 1U << (pos % 8);
155 // Append numLowerBits bits to lower sequence.
156 if (numLowerBits != 0) {
157 const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
158 writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
161 /* static */ if (skipQuantum != 0) {
162 while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
163 // Store the number of preceding 1-bits.
164 skipPointers_[skipPointersSize_++] = size_;
168 /* static */ if (forwardQuantum != 0) {
169 if ((size_ + 1) % forwardQuantum == 0) {
170 const auto pos = size_ / forwardQuantum;
171 // Store the number of preceding 0-bits.
172 forwardPointers_[pos] = upperBits;
180 const MutableCompressedList& finish() const {
181 CHECK_EQ(size_, result_.size);
186 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
187 static void writeBits56(unsigned char* data, size_t pos,
188 uint8_t len, uint64_t value) {
189 DCHECK_LE(uint32_t(len), 56);
190 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
191 unsigned char* const ptr = data + (pos / 8);
192 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
193 ptrv |= value << (pos % 8);
194 folly::storeUnaligned<uint64_t>(ptr, ptrv);
197 unsigned char* lower_ = nullptr;
198 unsigned char* upper_ = nullptr;
199 SkipValueType* skipPointers_ = nullptr;
200 SkipValueType* forwardPointers_ = nullptr;
202 ValueType lastValue_ = 0;
204 size_t skipPointersSize_ = 0;
206 MutableCompressedList result_;
209 template <class Value,
212 size_t kForwardQuantum>
213 struct EliasFanoEncoderV2<Value,
216 kForwardQuantum>::Layout {
217 static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
218 // numLowerBits can be at most 56 because of detail::writeBits56.
219 const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
223 // Upper bits are stored using unary delta encoding.
224 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
225 const size_t upperSizeBits =
226 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
228 const size_t upper = (upperSizeBits + 7) / 8;
230 // *** Validity checks.
231 // Shift by numLowerBits must be valid.
232 CHECK_LT(numLowerBits, 8 * sizeof(Value));
233 CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
234 CHECK_LT(upperBound >> numLowerBits,
235 std::numeric_limits<SkipValueType>::max());
237 return fromInternalSizes(numLowerBits, upper, size);
240 static Layout fromInternalSizes(uint8_t numLowerBits,
245 layout.numLowerBits = numLowerBits;
247 layout.lower = (numLowerBits * size + 7) / 8;
248 layout.upper = upper;
250 // *** Skip pointers.
251 // Store (1-indexed) position of every skipQuantum-th
252 // 0-bit in upper bits sequence.
253 /* static */ if (skipQuantum != 0) {
254 // 8 * upper is used here instead of upperSizeBits, as that is
255 // more serialization-friendly way (upperSizeBits doesn't need
256 // to be known by this function, unlike upper).
258 // '?: 1' is a workaround for false 'division by zero'
259 // compile-time error.
260 size_t numSkipPointers = (8 * upper - size) / (skipQuantum ?: 1);
261 layout.skipPointers = numSkipPointers * sizeof(SkipValueType);
264 // *** Forward pointers.
265 // Store (1-indexed) position of every forwardQuantum-th
266 // 1-bit in upper bits sequence.
267 /* static */ if (forwardQuantum != 0) {
268 size_t numForwardPointers = size / (forwardQuantum ?: 1);
269 layout.forwardPointers = numForwardPointers * sizeof(SkipValueType);
275 size_t bytes() const {
276 return lower + upper + skipPointers + forwardPointers;
279 template <class Range>
280 EliasFanoCompressedListBase<typename Range::iterator>
281 openList(Range& buf) const {
282 EliasFanoCompressedListBase<typename Range::iterator> result;
284 result.numLowerBits = numLowerBits;
285 result.data = buf.subpiece(0, bytes());
287 auto advance = [&] (size_t n) {
288 auto begin = buf.data();
293 result.skipPointers = advance(skipPointers);
294 result.forwardPointers = advance(forwardPointers);
295 result.lower = advance(lower);
296 result.upper = advance(upper);
301 MutableCompressedList allocList() const {
302 uint8_t* buf = nullptr;
303 // WARNING: Current read/write logic assumes that the 7 bytes
304 // following the last byte of lower and upper sequences are
305 // readable (stored value doesn't matter and won't be changed), so
306 // we allocate additional 7 bytes, but do not include them in size
307 // of returned value.
309 buf = static_cast<uint8_t*>(malloc(bytes() + 7));
311 folly::MutableByteRange bufRange(buf, bytes());
312 return openList(bufRange);
316 uint8_t numLowerBits = 0;
321 size_t skipPointers = 0;
322 size_t forwardPointers = 0;
327 template <class Encoder, class Instructions>
328 class UpperBitsReader {
329 typedef typename Encoder::SkipValueType SkipValueType;
331 typedef typename Encoder::ValueType ValueType;
333 explicit UpperBitsReader(const typename Encoder::CompressedList& list)
334 : forwardPointers_(list.forwardPointers),
335 skipPointers_(list.skipPointers),
341 block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
348 size_t position() const { return position_; }
349 ValueType value() const { return value_; }
352 // Skip to the first non-zero block.
353 while (block_ == 0) {
354 outer_ += sizeof(block_t);
355 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
359 inner_ = Instructions::ctz(block_);
360 block_ = Instructions::blsr(block_);
365 ValueType skip(size_t n) {
368 position_ += n; // n 1-bits will be read.
370 // Use forward pointer.
371 if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
372 // Workaround to avoid 'division by zero' compile-time error.
373 constexpr size_t q = Encoder::forwardQuantum ?: 1;
375 const size_t steps = position_ / q;
377 folly::loadUnaligned<SkipValueType>(
378 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
380 reposition(dest + steps * q);
381 n = position_ + 1 - steps * q; // n is > 0.
382 // Correct inner_ will be set at the end.
386 // Find necessary block.
387 while ((cnt = Instructions::popcount(block_)) < n) {
389 outer_ += sizeof(block_t);
390 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
393 // Skip to the n-th one in the block.
395 inner_ = select64<Instructions>(block_, n - 1);
396 block_ &= (block_t(-1) << inner_) << 1;
401 // Skip to the first element that is >= v and located *after* the current
402 // one (so even if current value equals v, position will be increased by 1).
403 ValueType skipToNext(ValueType v) {
404 DCHECK_GE(v, value_);
407 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
408 // Workaround to avoid 'division by zero' compile-time error.
409 constexpr size_t q = Encoder::skipQuantum ?: 1;
411 const size_t steps = v / q;
413 folly::loadUnaligned<SkipValueType>(
414 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
416 reposition(dest + q * 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_ = -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)) {
476 DCHECK_GE(outer, sizeof(block_t));
477 outer -= sizeof(block_t);
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 = 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 size_t upperValue = (value >> numLowerBits_);
590 size_t 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_;