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 (size == 0 || upperBound < size) {
110 // floor(log(upperBound / size));
111 return uint8_t(folly::findLastSet(upperBound / size) - 1);
114 // Requires: input range (begin, end) is sorted (encoding
115 // crashes if it's not).
116 // WARNING: encode() mallocates EliasFanoCompressedList::data. As
117 // EliasFanoCompressedList has no ownership of it, you need to call
118 // free() explicitly.
119 template <class RandomAccessIterator>
120 static MutableCompressedList encode(RandomAccessIterator begin,
121 RandomAccessIterator end) {
123 return MutableCompressedList();
125 EliasFanoEncoderV2 encoder(size_t(end - begin), *(end - 1));
126 for (; begin != end; ++begin) {
129 return encoder.finish();
132 explicit EliasFanoEncoderV2(const MutableCompressedList& result)
133 : lower_(result.lower),
134 upper_(result.upper),
135 skipPointers_(reinterpret_cast<SkipValueType*>(
136 result.skipPointers)),
137 forwardPointers_(reinterpret_cast<SkipValueType*>(
138 result.forwardPointers)),
140 std::fill(result.data.begin(), result.data.end(), 0);
143 EliasFanoEncoderV2(size_t size, ValueType upperBound)
144 : EliasFanoEncoderV2(
145 Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
147 void add(ValueType value) {
148 CHECK_LT(value, std::numeric_limits<ValueType>::max());
149 CHECK_GE(value, lastValue_);
151 const auto numLowerBits = result_.numLowerBits;
152 const ValueType upperBits = value >> numLowerBits;
154 // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
155 const size_t pos = upperBits + size_;
156 upper_[pos / 8] |= 1U << (pos % 8);
157 // Append numLowerBits bits to lower sequence.
158 if (numLowerBits != 0) {
159 const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
160 writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
163 /* static */ if (skipQuantum != 0) {
164 while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
165 // Store the number of preceding 1-bits.
166 skipPointers_[skipPointersSize_++] = SkipValue(size_);
170 /* static */ if (forwardQuantum != 0) {
171 if ((size_ + 1) % forwardQuantum == 0) {
172 const auto k = size_ / forwardQuantum;
173 // Store the number of preceding 0-bits.
174 forwardPointers_[k] = upperBits;
182 const MutableCompressedList& finish() const {
183 CHECK_EQ(size_, result_.size);
188 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
189 static void writeBits56(unsigned char* data, size_t pos,
190 uint8_t len, uint64_t value) {
191 DCHECK_LE(uint32_t(len), 56);
192 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
193 unsigned char* const ptr = data + (pos / 8);
194 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
195 ptrv |= value << (pos % 8);
196 folly::storeUnaligned<uint64_t>(ptr, ptrv);
199 unsigned char* lower_ = nullptr;
200 unsigned char* upper_ = nullptr;
201 SkipValueType* skipPointers_ = nullptr;
202 SkipValueType* forwardPointers_ = nullptr;
204 ValueType lastValue_ = 0;
206 size_t skipPointersSize_ = 0;
208 MutableCompressedList result_;
211 template <class Value,
214 size_t kForwardQuantum>
215 struct EliasFanoEncoderV2<Value,
218 kForwardQuantum>::Layout {
219 static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
220 // numLowerBits can be at most 56 because of detail::writeBits56.
221 const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
225 // Upper bits are stored using unary delta encoding.
226 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
227 const size_t upperSizeBits =
228 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
230 const size_t upper = (upperSizeBits + 7) / 8;
232 // *** Validity checks.
233 // Shift by numLowerBits must be valid.
234 CHECK_LT(numLowerBits, 8 * sizeof(Value));
235 CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
236 CHECK_LT(upperBound >> numLowerBits,
237 std::numeric_limits<SkipValueType>::max());
239 return fromInternalSizes(numLowerBits, upper, size);
242 static Layout fromInternalSizes(uint8_t numLowerBits,
247 layout.numLowerBits = numLowerBits;
249 layout.lower = (numLowerBits * size + 7) / 8;
250 layout.upper = upper;
252 // *** Skip pointers.
253 // Store (1-indexed) position of every skipQuantum-th
254 // 0-bit in upper bits sequence.
255 /* static */ if (skipQuantum != 0) {
256 // 8 * upper is used here instead of upperSizeBits, as that is
257 // more serialization-friendly way (upperSizeBits doesn't need
258 // to be known by this function, unlike upper).
260 size_t numSkipPointers = (8 * upper - size) / skipQuantum;
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;
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;
343 inner_ = std::numeric_limits<size_t>::max();
344 position_ = std::numeric_limits<size_t>::max();
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_ = size_t(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 const size_t steps = position_ / Encoder::forwardQuantum;
374 folly::loadUnaligned<SkipValueType>(
375 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
377 reposition(dest + steps * Encoder::forwardQuantum);
378 n = position_ + 1 - steps * Encoder::forwardQuantum; // n is > 0.
379 // Correct inner_ will be set at the end.
383 // Find necessary block.
384 while ((cnt = Instructions::popcount(block_)) < n) {
386 outer_ += sizeof(block_t);
387 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
390 // Skip to the n-th one in the block.
392 inner_ = select64<Instructions>(block_, n - 1);
393 block_ &= (block_t(-1) << inner_) << 1;
398 // Skip to the first element that is >= v and located *after* the current
399 // one (so even if current value equals v, position will be increased by 1).
400 ValueType skipToNext(ValueType v) {
401 DCHECK_GE(v, value_);
404 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
405 const size_t steps = v / Encoder::skipQuantum;
407 folly::loadUnaligned<SkipValueType>(
408 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
410 reposition(dest + Encoder::skipQuantum * steps);
411 position_ = dest - 1;
413 // Correct inner_ and value_ will be set during the next()
416 // NOTE: Corresponding block of lower bits sequence may be
417 // prefetched here (via __builtin_prefetch), but experiments
418 // didn't show any significant improvements.
423 size_t skip = v - (8 * outer_ - position_ - 1);
425 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
426 while ((cnt = Instructions::popcount(~block_)) < skip) {
428 position_ += kBitsPerBlock - cnt;
429 outer_ += sizeof(block_t);
430 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
434 auto inner = select64<Instructions>(~block_, skip - 1);
435 position_ += inner - skip + 1;
436 block_ &= block_t(-1) << inner;
443 ValueType jump(size_t n) {
444 if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
447 position_ = size_t(-1); // Avoid reading the head, skip() will reposition.
452 ValueType jumpToNext(ValueType v) {
453 if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
456 value_ = 0; // Avoid reading the head, skipToNext() will reposition.
458 return skipToNext(v);
461 ValueType previousValue() const {
462 DCHECK_NE(position(), -1);
463 DCHECK_GT(position(), 0);
465 size_t outer = outer_;
466 block_t block = folly::loadUnaligned<block_t>(start_ + outer);
467 block &= (block_t(1) << inner_) - 1;
469 while (UNLIKELY(block == 0)) {
470 DCHECK_GE(outer, sizeof(block_t));
471 outer -= sizeof(block_t);
472 block = folly::loadUnaligned<block_t>(start_ + outer);
475 auto inner = 8 * sizeof(block_t) - 1 - Instructions::clz(block);
476 return static_cast<ValueType>(8 * outer + inner - (position_ - 1));
479 void setDone(size_t endPos) {
484 ValueType setValue() {
485 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
489 void reposition(size_t dest) {
491 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
492 block_ &= ~((block_t(1) << (dest % 8)) - 1);
495 typedef uint64_t block_t;
496 const unsigned char* const forwardPointers_;
497 const unsigned char* const skipPointers_;
498 const unsigned char* const start_;
500 size_t outer_; // Outer offset: number of consumed bytes in upper.
501 size_t inner_; // Inner offset: (bit) position in current block.
502 size_t position_; // Index of current value (= #reads - 1).
506 } // namespace detail
508 // If kUnchecked = true the caller must guarantee that all the
509 // operations return valid elements, i.e., they would never return
511 template <class Encoder,
512 class Instructions = instructions::Default,
513 bool kUnchecked = false>
514 class EliasFanoReader {
516 typedef Encoder EncoderType;
517 typedef typename Encoder::ValueType ValueType;
519 explicit EliasFanoReader(const typename Encoder::CompressedList& list)
523 lowerMask_((ValueType(1) << list.numLowerBits) - 1),
524 numLowerBits_(list.numLowerBits) {
525 DCHECK(Instructions::supported());
526 // To avoid extra branching during skipTo() while reading
527 // upper sequence we need to know the last element.
528 // If kUnchecked == true, we do not check that skipTo() is called
529 // within the bounds, so we can avoid initializing lastValue_.
530 if (kUnchecked || UNLIKELY(list.size == 0)) {
534 ValueType lastUpperValue = ValueType(8 * list.upperSize() - size_);
535 auto it = list.upper + list.upperSize() - 1;
537 lastUpperValue -= 8 - folly::findLastSet(*it);
538 lastValue_ = readLowerPart(size_ - 1) | (lastUpperValue << numLowerBits_);
543 value_ = kInvalidValue;
547 if (!kUnchecked && UNLIKELY(position() + 1 >= size_)) {
551 value_ = readLowerPart(upper_.position()) |
552 (upper_.value() << numLowerBits_);
556 bool skip(size_t n) {
559 if (kUnchecked || LIKELY(position() + n < size_)) {
560 if (LIKELY(n < kLinearScanThreshold)) {
561 for (size_t i = 0; i < n; ++i) upper_.next();
565 value_ = readLowerPart(upper_.position()) |
566 (upper_.value() << numLowerBits_);
573 bool skipTo(ValueType value) {
574 // Also works when value_ == kInvalidValue.
575 if (value != kInvalidValue) { DCHECK_GE(value + 1, value_ + 1); }
577 if (!kUnchecked && value > lastValue_) {
579 } else if (value == value_) {
583 size_t upperValue = (value >> numLowerBits_);
584 size_t upperSkip = upperValue - upper_.value();
585 // The average density of ones in upper bits is 1/2.
586 // LIKELY here seems to make things worse, even for small skips.
587 if (upperSkip < 2 * kLinearScanThreshold) {
590 } while (UNLIKELY(upper_.value() < upperValue));
592 upper_.skipToNext(upperValue);
599 bool jump(size_t n) {
600 if (LIKELY(n < size_)) { // Also checks that n != -1.
601 value_ = readLowerPart(n) | (upper_.jump(n + 1) << numLowerBits_);
607 bool jumpTo(ValueType value) {
608 if (!kUnchecked && value > lastValue_) {
612 upper_.jumpToNext(value >> numLowerBits_);
617 ValueType previousValue() const {
618 DCHECK_GT(position(), 0);
619 DCHECK_LT(position(), size());
620 return readLowerPart(upper_.position() - 1) |
621 (upper_.previousValue() << numLowerBits_);
624 size_t size() const { return size_; }
627 return position() < size(); // Also checks that position() != -1.
630 size_t position() const { return upper_.position(); }
631 ValueType value() const {
637 constexpr static ValueType kInvalidValue =
638 std::numeric_limits<ValueType>::max(); // Must hold kInvalidValue + 1 == 0.
641 value_ = kInvalidValue;
642 upper_.setDone(size_);
646 ValueType readLowerPart(size_t i) const {
648 const size_t pos = i * numLowerBits_;
649 const unsigned char* ptr = lower_ + (pos / 8);
650 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
651 return lowerMask_ & (ptrv >> (pos % 8));
654 void iterateTo(ValueType value) {
656 value_ = readLowerPart(upper_.position()) |
657 (upper_.value() << numLowerBits_);
658 if (LIKELY(value_ >= value)) break;
663 constexpr static size_t kLinearScanThreshold = 8;
666 const uint8_t* lower_;
667 detail::UpperBitsReader<Encoder, Instructions> upper_;
668 const ValueType lowerMask_;
669 ValueType value_ = kInvalidValue;
670 ValueType lastValue_;
671 uint8_t numLowerBits_;