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).
28 #include <type_traits>
30 #include <folly/Bits.h>
31 #include <folly/Likely.h>
32 #include <folly/Portability.h>
33 #include <folly/Range.h>
34 #include <folly/experimental/Instructions.h>
35 #include <folly/experimental/Select64.h>
36 #include <glog/logging.h>
39 #error EliasFanoCoding.h requires GCC
43 #error EliasFanoCoding.h requires x86_64
46 #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
47 #error EliasFanoCoding.h requires little endianness
50 namespace folly { namespace compression {
52 template <class Pointer>
53 struct EliasFanoCompressedListBase {
54 EliasFanoCompressedListBase() = default;
56 template <class OtherPointer>
57 EliasFanoCompressedListBase(
58 const EliasFanoCompressedListBase<OtherPointer>& other)
60 numLowerBits(other.numLowerBits),
62 skipPointers(reinterpret_cast<Pointer>(other.skipPointers)),
63 forwardPointers(reinterpret_cast<Pointer>(other.forwardPointers)),
64 lower(reinterpret_cast<Pointer>(other.lower)),
65 upper(reinterpret_cast<Pointer>(other.upper)) { }
67 template <class T = Pointer>
68 auto free() -> decltype(::free(T(nullptr))) {
69 return ::free(data.data());
72 size_t upperSize() const { return data.end() - upper; }
75 uint8_t numLowerBits = 0;
77 // WARNING: EliasFanoCompressedList has no ownership of data. The 7
78 // bytes following the last byte should be readable.
79 folly::Range<Pointer> data;
81 Pointer skipPointers = nullptr;
82 Pointer forwardPointers = nullptr;
83 Pointer lower = nullptr;
84 Pointer upper = nullptr;
87 typedef EliasFanoCompressedListBase<const uint8_t*> EliasFanoCompressedList;
88 typedef EliasFanoCompressedListBase<uint8_t*> MutableEliasFanoCompressedList;
90 template <class Value,
91 class SkipValue = size_t,
92 size_t kSkipQuantum = 0, // 0 = disabled
93 size_t kForwardQuantum = 0> // 0 = disabled
94 struct EliasFanoEncoderV2 {
95 static_assert(std::is_integral<Value>::value &&
96 std::is_unsigned<Value>::value,
97 "Value should be unsigned integral");
99 typedef EliasFanoCompressedList CompressedList;
100 typedef MutableEliasFanoCompressedList MutableCompressedList;
102 typedef Value ValueType;
103 typedef SkipValue SkipValueType;
106 static constexpr size_t skipQuantum = kSkipQuantum;
107 static constexpr size_t forwardQuantum = kForwardQuantum;
109 static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
110 if (size == 0 || upperBound < size) {
113 // floor(log(upperBound / size));
114 return folly::findLastSet(upperBound / size) - 1;
117 // Requires: input range (begin, end) is sorted (encoding
118 // crashes if it's not).
119 // WARNING: encode() mallocates EliasFanoCompressedList::data. As
120 // EliasFanoCompressedList has no ownership of it, you need to call
121 // free() explicitly.
122 template <class RandomAccessIterator>
123 static MutableCompressedList encode(RandomAccessIterator begin,
124 RandomAccessIterator end) {
126 return MutableCompressedList();
128 EliasFanoEncoderV2 encoder(end - begin, *(end - 1));
129 for (; begin != end; ++begin) {
132 return encoder.finish();
135 explicit EliasFanoEncoderV2(const MutableCompressedList& result)
136 : lower_(result.lower),
137 upper_(result.upper),
138 skipPointers_(reinterpret_cast<SkipValueType*>(
139 result.skipPointers)),
140 forwardPointers_(reinterpret_cast<SkipValueType*>(
141 result.forwardPointers)),
143 memset(result.data.data(), 0, result.data.size());
146 EliasFanoEncoderV2(size_t size, ValueType upperBound)
147 : EliasFanoEncoderV2(
148 Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
150 void add(ValueType value) {
151 CHECK_LT(value, std::numeric_limits<ValueType>::max());
152 CHECK_GE(value, lastValue_);
154 const auto numLowerBits = result_.numLowerBits;
155 const ValueType upperBits = value >> numLowerBits;
157 // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
158 const size_t pos = upperBits + size_;
159 upper_[pos / 8] |= 1U << (pos % 8);
160 // Append numLowerBits bits to lower sequence.
161 if (numLowerBits != 0) {
162 const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
163 writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
166 /* static */ if (skipQuantum != 0) {
167 while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
168 // Store the number of preceding 1-bits.
169 skipPointers_[skipPointersSize_++] = size_;
173 /* static */ if (forwardQuantum != 0) {
174 if ((size_ + 1) % forwardQuantum == 0) {
175 const auto pos = size_ / forwardQuantum;
176 // Store the number of preceding 0-bits.
177 forwardPointers_[pos] = upperBits;
185 const MutableCompressedList& finish() const {
186 CHECK_EQ(size_, result_.size);
191 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
192 static void writeBits56(unsigned char* data, size_t pos,
193 uint8_t len, uint64_t value) {
194 DCHECK_LE(uint32_t(len), 56);
195 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
196 unsigned char* const ptr = data + (pos / 8);
197 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
198 ptrv |= value << (pos % 8);
199 folly::storeUnaligned<uint64_t>(ptr, ptrv);
202 unsigned char* lower_ = nullptr;
203 unsigned char* upper_ = nullptr;
204 SkipValueType* skipPointers_ = nullptr;
205 SkipValueType* forwardPointers_ = nullptr;
207 ValueType lastValue_ = 0;
209 size_t skipPointersSize_ = 0;
211 MutableCompressedList result_;
214 template <class Value,
217 size_t kForwardQuantum>
218 struct EliasFanoEncoderV2<Value,
221 kForwardQuantum>::Layout {
222 static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
223 // numLowerBits can be at most 56 because of detail::writeBits56.
224 const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
228 // Upper bits are stored using unary delta encoding.
229 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
230 const size_t upperSizeBits =
231 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
233 const size_t upper = (upperSizeBits + 7) / 8;
235 // *** Validity checks.
236 // Shift by numLowerBits must be valid.
237 CHECK_LT(numLowerBits, 8 * sizeof(Value));
238 CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
239 CHECK_LT(upperBound >> numLowerBits,
240 std::numeric_limits<SkipValueType>::max());
242 return fromInternalSizes(numLowerBits, upper, size);
245 static Layout fromInternalSizes(uint8_t numLowerBits,
250 layout.numLowerBits = numLowerBits;
252 layout.lower = (numLowerBits * size + 7) / 8;
253 layout.upper = upper;
255 // *** Skip pointers.
256 // Store (1-indexed) position of every skipQuantum-th
257 // 0-bit in upper bits sequence.
258 /* static */ if (skipQuantum != 0) {
259 // 8 * upper is used here instead of upperSizeBits, as that is
260 // more serialization-friendly way (upperSizeBits doesn't need
261 // to be known by this function, unlike upper).
263 // '?: 1' is a workaround for false 'division by zero'
264 // compile-time error.
265 size_t numSkipPointers = (8 * upper - size) / (skipQuantum ?: 1);
266 layout.skipPointers = numSkipPointers * sizeof(SkipValueType);
269 // *** Forward pointers.
270 // Store (1-indexed) position of every forwardQuantum-th
271 // 1-bit in upper bits sequence.
272 /* static */ if (forwardQuantum != 0) {
273 size_t numForwardPointers = size / (forwardQuantum ?: 1);
274 layout.forwardPointers = numForwardPointers * sizeof(SkipValueType);
280 size_t bytes() const {
281 return lower + upper + skipPointers + forwardPointers;
284 template <class Range>
285 EliasFanoCompressedListBase<typename Range::iterator>
286 openList(Range& buf) const {
287 EliasFanoCompressedListBase<typename Range::iterator> result;
289 result.numLowerBits = numLowerBits;
290 result.data = buf.subpiece(0, bytes());
292 auto advance = [&] (size_t n) {
293 auto begin = buf.data();
298 result.skipPointers = advance(skipPointers);
299 result.forwardPointers = advance(forwardPointers);
300 result.lower = advance(lower);
301 result.upper = advance(upper);
306 MutableCompressedList allocList() const {
307 uint8_t* buf = nullptr;
308 // WARNING: Current read/write logic assumes that the 7 bytes
309 // following the last byte of lower and upper sequences are
310 // readable (stored value doesn't matter and won't be changed), so
311 // we allocate additional 7 bytes, but do not include them in size
312 // of returned value.
314 buf = static_cast<uint8_t*>(malloc(bytes() + 7));
316 folly::MutableByteRange bufRange(buf, bytes());
317 return openList(bufRange);
321 uint8_t numLowerBits = 0;
326 size_t skipPointers = 0;
327 size_t forwardPointers = 0;
332 template <class Encoder, class Instructions>
333 class UpperBitsReader {
334 typedef typename Encoder::SkipValueType SkipValueType;
336 typedef typename Encoder::ValueType ValueType;
338 explicit UpperBitsReader(const typename Encoder::CompressedList& list)
339 : forwardPointers_(list.forwardPointers),
340 skipPointers_(list.skipPointers),
346 block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
353 size_t position() const { return position_; }
354 ValueType value() const { return value_; }
357 // Skip to the first non-zero block.
358 while (block_ == 0) {
359 outer_ += sizeof(block_t);
360 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
364 inner_ = Instructions::ctz(block_);
365 block_ = Instructions::blsr(block_);
370 ValueType skip(size_t n) {
373 position_ += n; // n 1-bits will be read.
375 // Use forward pointer.
376 if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
377 // Workaround to avoid 'division by zero' compile-time error.
378 constexpr size_t q = Encoder::forwardQuantum ?: 1;
380 const size_t steps = position_ / q;
382 folly::loadUnaligned<SkipValueType>(
383 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
385 reposition(dest + steps * q);
386 n = position_ + 1 - steps * q; // n is > 0.
387 // Correct inner_ will be set at the end.
391 // Find necessary block.
392 while ((cnt = Instructions::popcount(block_)) < n) {
394 outer_ += sizeof(block_t);
395 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
398 // Skip to the n-th one in the block.
400 inner_ = select64<Instructions>(block_, n - 1);
401 block_ &= (block_t(-1) << inner_) << 1;
406 // Skip to the first element that is >= v and located *after* the current
407 // one (so even if current value equals v, position will be increased by 1).
408 ValueType skipToNext(ValueType v) {
409 DCHECK_GE(v, value_);
412 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
413 // Workaround to avoid 'division by zero' compile-time error.
414 constexpr size_t q = Encoder::skipQuantum ?: 1;
416 const size_t steps = v / q;
418 folly::loadUnaligned<SkipValueType>(
419 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
421 reposition(dest + q * steps);
422 position_ = dest - 1;
424 // Correct inner_ and value_ will be set during the next()
427 // NOTE: Corresponding block of lower bits sequence may be
428 // prefetched here (via __builtin_prefetch), but experiments
429 // didn't show any significant improvements.
434 size_t skip = v - (8 * outer_ - position_ - 1);
436 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
437 while ((cnt = Instructions::popcount(~block_)) < skip) {
439 position_ += kBitsPerBlock - cnt;
440 outer_ += sizeof(block_t);
441 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
445 auto inner = select64<Instructions>(~block_, skip - 1);
446 position_ += inner - skip + 1;
447 block_ &= block_t(-1) << inner;
454 ValueType jump(size_t n) {
455 if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
458 position_ = -1; // Avoid reading the head, skip() will reposition.
463 ValueType jumpToNext(ValueType v) {
464 if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
467 value_ = 0; // Avoid reading the head, skipToNext() will reposition.
469 return skipToNext(v);
472 ValueType previousValue() const {
473 DCHECK_NE(position(), -1);
474 DCHECK_GT(position(), 0);
476 size_t outer = outer_;
477 block_t block = folly::loadUnaligned<block_t>(start_ + outer);
478 block &= (block_t(1) << inner_) - 1;
480 while (UNLIKELY(block == 0)) {
481 DCHECK_GE(outer, sizeof(block_t));
482 outer -= sizeof(block_t);
483 block = folly::loadUnaligned<block_t>(start_ + outer);
486 auto inner = 8 * sizeof(block_t) - 1 - Instructions::clz(block);
487 return static_cast<ValueType>(8 * outer + inner - (position_ - 1));
490 void setDone(size_t endPos) {
495 ValueType setValue() {
496 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
500 void reposition(size_t dest) {
502 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
503 block_ &= ~((block_t(1) << (dest % 8)) - 1);
506 typedef uint64_t block_t;
507 const unsigned char* const forwardPointers_;
508 const unsigned char* const skipPointers_;
509 const unsigned char* const start_;
511 size_t outer_; // Outer offset: number of consumed bytes in upper.
512 size_t inner_; // Inner offset: (bit) position in current block.
513 size_t position_; // Index of current value (= #reads - 1).
517 } // namespace detail
519 // If kUnchecked = true the caller must guarantee that all the
520 // operations return valid elements, i.e., they would never return
522 template <class Encoder,
523 class Instructions = instructions::Default,
524 bool kUnchecked = false>
525 class EliasFanoReader {
527 typedef Encoder EncoderType;
528 typedef typename Encoder::ValueType ValueType;
530 explicit EliasFanoReader(const typename Encoder::CompressedList& list)
534 lowerMask_((ValueType(1) << list.numLowerBits) - 1),
535 numLowerBits_(list.numLowerBits) {
536 DCHECK(Instructions::supported());
537 // To avoid extra branching during skipTo() while reading
538 // upper sequence we need to know the last element.
539 // If kUnchecked == true, we do not check that skipTo() is called
540 // within the bounds, so we can avoid initializing lastValue_.
541 if (kUnchecked || UNLIKELY(list.size == 0)) {
545 ValueType lastUpperValue = 8 * list.upperSize() - size_;
546 auto it = list.upper + list.upperSize() - 1;
548 lastUpperValue -= 8 - folly::findLastSet(*it);
549 lastValue_ = readLowerPart(size_ - 1) | (lastUpperValue << numLowerBits_);
554 value_ = kInvalidValue;
558 if (!kUnchecked && UNLIKELY(position() + 1 >= size_)) {
562 value_ = readLowerPart(upper_.position()) |
563 (upper_.value() << numLowerBits_);
567 bool skip(size_t n) {
570 if (kUnchecked || LIKELY(position() + n < size_)) {
571 if (LIKELY(n < kLinearScanThreshold)) {
572 for (size_t i = 0; i < n; ++i) upper_.next();
576 value_ = readLowerPart(upper_.position()) |
577 (upper_.value() << numLowerBits_);
584 bool skipTo(ValueType value) {
585 // Also works when value_ == kInvalidValue.
586 if (value != kInvalidValue) { DCHECK_GE(value + 1, value_ + 1); }
588 if (!kUnchecked && value > lastValue_) {
590 } else if (value == value_) {
594 size_t upperValue = (value >> numLowerBits_);
595 size_t upperSkip = upperValue - upper_.value();
596 // The average density of ones in upper bits is 1/2.
597 // LIKELY here seems to make things worse, even for small skips.
598 if (upperSkip < 2 * kLinearScanThreshold) {
601 } while (UNLIKELY(upper_.value() < upperValue));
603 upper_.skipToNext(upperValue);
610 bool jump(size_t n) {
611 if (LIKELY(n < size_)) { // Also checks that n != -1.
612 value_ = readLowerPart(n) | (upper_.jump(n + 1) << numLowerBits_);
618 bool jumpTo(ValueType value) {
619 if (!kUnchecked && value > lastValue_) {
623 upper_.jumpToNext(value >> numLowerBits_);
628 ValueType previousValue() const {
629 DCHECK_GT(position(), 0);
630 DCHECK_LT(position(), size());
631 return readLowerPart(upper_.position() - 1) |
632 (upper_.previousValue() << numLowerBits_);
635 size_t size() const { return size_; }
638 return position() < size(); // Also checks that position() != -1.
641 size_t position() const { return upper_.position(); }
642 ValueType value() const {
648 constexpr static ValueType kInvalidValue =
649 std::numeric_limits<ValueType>::max(); // Must hold kInvalidValue + 1 == 0.
652 value_ = kInvalidValue;
653 upper_.setDone(size_);
657 ValueType readLowerPart(size_t i) const {
659 const size_t pos = i * numLowerBits_;
660 const unsigned char* ptr = lower_ + (pos / 8);
661 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
662 return lowerMask_ & (ptrv >> (pos % 8));
665 void iterateTo(ValueType value) {
667 value_ = readLowerPart(upper_.position()) |
668 (upper_.value() << numLowerBits_);
669 if (LIKELY(value_ >= value)) break;
674 constexpr static size_t kLinearScanThreshold = 8;
677 const uint8_t* lower_;
678 detail::UpperBitsReader<Encoder, Instructions> upper_;
679 const ValueType lowerMask_;
680 ValueType value_ = kInvalidValue;
681 ValueType lastValue_;
682 uint8_t numLowerBits_;