2 * Copyright 2014 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).
24 #ifndef FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
25 #define FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
28 #error EliasFanoCoding.h requires GCC
32 #error EliasFanoCoding.h requires x86_64
37 #include <type_traits>
38 #include <boost/noncopyable.hpp>
39 #include <glog/logging.h>
41 #include <folly/Bits.h>
42 #include <folly/CpuId.h>
43 #include <folly/Likely.h>
44 #include <folly/Range.h>
46 #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
47 #error EliasFanoCoding.h requires little endianness
50 namespace folly { namespace compression {
52 struct EliasFanoCompressedList {
53 EliasFanoCompressedList() { }
56 ::free(const_cast<unsigned char*>(lower.data()));
57 ::free(const_cast<unsigned char*>(upper.data()));
58 ::free(const_cast<unsigned char*>(skipPointers.data()));
59 ::free(const_cast<unsigned char*>(forwardPointers.data()));
63 uint8_t numLowerBits = 0;
65 // WARNING: EliasFanoCompressedList has no ownership of
66 // lower, upper, skipPointers and forwardPointers.
67 // The 7 bytes following the last byte of lower and upper
68 // sequences should be readable.
69 folly::ByteRange lower;
70 folly::ByteRange upper;
72 folly::ByteRange skipPointers;
73 folly::ByteRange forwardPointers;
77 // In version 1 skip / forward pointers encoding has been changed,
78 // so SkipValue = uint32_t is able to address up to ~4B elements,
79 // instead of only ~2B.
80 template <class Value,
81 class SkipValue = size_t,
82 size_t kSkipQuantum = 0, // 0 = disabled
83 size_t kForwardQuantum = 0, // 0 = disabled
85 struct EliasFanoEncoder {
86 static_assert(std::is_integral<Value>::value &&
87 std::is_unsigned<Value>::value,
88 "Value should be unsigned integral");
90 typedef EliasFanoCompressedList CompressedList;
92 typedef Value ValueType;
93 typedef SkipValue SkipValueType;
95 static constexpr size_t skipQuantum = kSkipQuantum;
96 static constexpr size_t forwardQuantum = kForwardQuantum;
97 static constexpr size_t version = kVersion;
99 static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
100 if (size == 0 || upperBound < size) {
103 // floor(log(upperBound / size));
104 return folly::findLastSet(upperBound / size) - 1;
107 // Requires: input range (begin, end) is sorted (encoding
108 // crashes if it's not).
109 // WARNING: encode() mallocates lower, upper, skipPointers
110 // and forwardPointers. As EliasFanoCompressedList has
111 // no ownership of them, you need to call free() explicitly.
112 template <class RandomAccessIterator>
113 static EliasFanoCompressedList encode(RandomAccessIterator begin,
114 RandomAccessIterator end) {
116 return EliasFanoCompressedList();
118 EliasFanoEncoder encoder(end - begin, *(end - 1));
119 for (; begin != end; ++begin) {
122 return encoder.finish();
125 EliasFanoEncoder(size_t size, ValueType upperBound) {
130 uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
132 // This is detail::writeBits56 limitation.
133 numLowerBits = std::min<uint8_t>(numLowerBits, 56);
134 CHECK_LT(numLowerBits, 8 * sizeof(Value)); // As we shift by numLowerBits.
136 // WARNING: Current read/write logic assumes that the 7 bytes
137 // following the last byte of lower and upper sequences are
138 // readable (stored value doesn't matter and won't be changed),
139 // so we allocate additional 7B, but do not include them in size
140 // of returned value.
143 const size_t lowerSize = (numLowerBits * size + 7) / 8;
144 if (lowerSize > 0) { // numLowerBits != 0
145 lower_ = static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
149 // Upper bits are stored using unary delta encoding.
150 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
151 const size_t upperSizeBits =
152 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
154 const size_t upperSize = (upperSizeBits + 7) / 8;
155 upper_ = static_cast<unsigned char*>(calloc(upperSize + 7, 1));
157 // *** Skip pointers.
158 // Store (1-indexed) position of every skipQuantum-th
159 // 0-bit in upper bits sequence.
160 size_t numSkipPointers = 0;
161 /* static */ if (skipQuantum != 0) {
162 /* static */ if (kVersion > 0) {
163 CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
165 CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
167 // 8 * upperSize is used here instead of upperSizeBits, as that is
168 // more serialization-friendly way (upperSizeBits isn't known outside of
169 // this function, unlike upperSize; thus numSkipPointers could easily be
170 // deduced from upperSize).
171 numSkipPointers = (8 * upperSize - size) / (skipQuantum ?: 1);
172 skipPointers_ = static_cast<SkipValueType*>(
175 : calloc(numSkipPointers, sizeof(SkipValueType)));
178 // *** Forward pointers.
179 // Store (1-indexed) position of every forwardQuantum-th
180 // 1-bit in upper bits sequence.
181 size_t numForwardPointers = 0;
182 /* static */ if (forwardQuantum != 0) {
183 /* static */ if (kVersion > 0) {
184 CHECK_LT(upperBound >> numLowerBits,
185 std::numeric_limits<SkipValueType>::max());
187 CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
190 // '?: 1' is a workaround for false 'division by zero' compile-time error.
191 numForwardPointers = size / (forwardQuantum ?: 1);
192 forwardPointers_ = static_cast<SkipValueType*>(
193 numForwardPointers == 0
195 : malloc(numForwardPointers * sizeof(SkipValueType)));
200 result_.numLowerBits = numLowerBits;
201 result_.lower.reset(lower_, lowerSize);
202 result_.upper.reset(upper_, upperSize);
203 result_.skipPointers.reset(
204 reinterpret_cast<unsigned char*>(skipPointers_),
205 numSkipPointers * sizeof(SkipValueType));
206 result_.forwardPointers.reset(
207 reinterpret_cast<unsigned char*>(forwardPointers_),
208 numForwardPointers * sizeof(SkipValueType));
211 void add(ValueType value) {
212 CHECK_GE(value, lastValue_);
214 const auto numLowerBits = result_.numLowerBits;
215 const ValueType upperBits = value >> numLowerBits;
217 // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
218 const size_t pos = upperBits + size_;
219 upper_[pos / 8] |= 1U << (pos % 8);
220 // Append numLowerBits bits to lower sequence.
221 if (numLowerBits != 0) {
222 const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
223 writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
226 /* static */ if (skipQuantum != 0) {
227 while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
228 /* static */ if (kVersion > 0) {
229 // Since version 1, just the number of preceding 1-bits is stored.
230 skipPointers_[skipPointersSize_] = size_;
232 skipPointers_[skipPointersSize_] =
233 size_ + (skipPointersSize_ + 1) * skipQuantum;
239 /* static */ if (forwardQuantum != 0) {
240 if ((size_ + 1) % forwardQuantum == 0) {
241 const auto pos = size_ / forwardQuantum;
242 /* static */ if (kVersion > 0) {
243 // Since version 1, just the number of preceding 0-bits is stored.
244 forwardPointers_[pos] = upperBits;
246 forwardPointers_[pos] = upperBits + size_ + 1;
255 const EliasFanoCompressedList& finish() const {
256 CHECK_EQ(size_, result_.size);
261 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
262 static void writeBits56(unsigned char* data, size_t pos,
263 uint8_t len, uint64_t value) {
264 DCHECK_LE(uint32_t(len), 56);
265 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
266 unsigned char* const ptr = data + (pos / 8);
267 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
268 ptrv |= value << (pos % 8);
269 folly::storeUnaligned<uint64_t>(ptr, ptrv);
272 unsigned char* lower_ = nullptr;
273 unsigned char* upper_ = nullptr;
274 SkipValueType* skipPointers_ = nullptr;
275 SkipValueType* forwardPointers_ = nullptr;
277 ValueType lastValue_ = 0;
279 size_t skipPointersSize_ = 0;
281 EliasFanoCompressedList result_;
284 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
285 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
286 // it for __builtin_popcountll intrinsic.
287 // But we provide an alternative way for the client code: it can switch to
288 // the appropriate version of EliasFanoReader<> in realtime (client should
289 // implement this switching logic itself) by specifying instruction set to
291 namespace instructions {
294 static bool supported() {
297 static inline uint64_t popcount(uint64_t value) {
298 return __builtin_popcountll(value);
300 static inline int ctz(uint64_t value) {
302 return __builtin_ctzll(value);
306 struct Fast : public Default {
307 static bool supported() {
309 return cpuId.popcnt();
311 static inline uint64_t popcount(uint64_t value) {
313 asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
318 } // namespace instructions
322 template <class Encoder, class Instructions>
323 class UpperBitsReader {
324 typedef typename Encoder::SkipValueType SkipValueType;
326 typedef typename Encoder::ValueType ValueType;
328 explicit UpperBitsReader(const EliasFanoCompressedList& list)
329 : forwardPointers_(list.forwardPointers.data()),
330 skipPointers_(list.skipPointers.data()),
331 start_(list.upper.data()) {
336 block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
343 size_t position() const { return position_; }
344 ValueType value() const { return value_; }
347 // Skip to the first non-zero block.
348 while (block_ == 0) {
349 outer_ += sizeof(block_t);
350 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
354 inner_ = Instructions::ctz(block_);
355 block_ &= block_ - 1;
360 ValueType skip(size_t n) {
363 position_ += n; // n 1-bits will be read.
365 // Use forward pointer.
366 if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
367 // Workaround to avoid 'division by zero' compile-time error.
368 constexpr size_t q = Encoder::forwardQuantum ?: 1;
370 const size_t steps = position_ / q;
372 folly::loadUnaligned<SkipValueType>(
373 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
375 /* static */ if (Encoder::version > 0) {
376 reposition(dest + steps * q);
380 n = position_ + 1 - steps * q; // n is > 0.
381 // correct inner_ will be set at the end.
385 // Find necessary block.
386 while ((cnt = Instructions::popcount(block_)) < n) {
388 outer_ += sizeof(block_t);
389 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
392 // NOTE: Trying to skip half-block here didn't show any
393 // performance improvements.
397 // Kill n - 1 least significant 1-bits.
398 for (size_t i = 0; i < n - 1; ++i) {
399 block_ &= block_ - 1;
402 inner_ = Instructions::ctz(block_);
403 block_ &= block_ - 1;
408 // Skip to the first element that is >= v and located *after* the current
409 // one (so even if current value equals v, position will be increased by 1).
410 ValueType skipToNext(ValueType v) {
411 DCHECK_GE(v, value_);
414 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
415 // Workaround to avoid 'division by zero' compile-time error.
416 constexpr size_t q = Encoder::skipQuantum ?: 1;
418 const size_t steps = v / q;
420 folly::loadUnaligned<SkipValueType>(
421 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
423 /* static */ if (Encoder::version > 0) {
424 reposition(dest + q * steps);
425 position_ = dest - 1;
428 position_ = dest - q * steps - 1;
430 // Correct inner_ and value_ will be set during the next()
433 // NOTE: Corresponding block of lower bits sequence may be
434 // prefetched here (via __builtin_prefetch), but experiments
435 // didn't show any significant improvements.
440 size_t skip = v - (8 * outer_ - position_ - 1);
442 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
443 while ((cnt = Instructions::popcount(~block_)) < skip) {
445 position_ += kBitsPerBlock - cnt;
446 outer_ += sizeof(block_t);
447 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
450 // Try to skip half-block.
451 constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
452 constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
453 if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
454 position_ += kBitsPerHalfBlock - cnt;
455 block_ &= ~halfBlockMask;
458 // Just skip until we see expected value.
459 while (next() < v) { }
463 ValueType jump(size_t n) {
464 if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
467 position_ = -1; // Avoid reading the head, skip() will reposition.
472 ValueType jumpToNext(ValueType v) {
473 if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
476 value_ = 0; // Avoid reading the head, skipToNext() will reposition.
478 return skipToNext(v);
482 ValueType setValue() {
483 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
487 void reposition(size_t dest) {
489 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
490 block_ &= ~((block_t(1) << (dest % 8)) - 1);
493 typedef unsigned long long block_t;
494 const unsigned char* const forwardPointers_;
495 const unsigned char* const skipPointers_;
496 const unsigned char* const start_;
498 size_t outer_; // Outer offset: number of consumed bytes in upper.
499 size_t inner_; // Inner offset: (bit) position in current block.
500 size_t position_; // Index of current value (= #reads - 1).
504 } // namespace detail
506 template <class Encoder,
507 class Instructions = instructions::Default>
508 class EliasFanoReader : private boost::noncopyable {
510 typedef Encoder EncoderType;
511 typedef typename Encoder::ValueType ValueType;
513 explicit EliasFanoReader(const EliasFanoCompressedList& list)
515 lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
517 DCHECK(Instructions::supported());
518 // To avoid extra branching during skipTo() while reading
519 // upper sequence we need to know the last element.
520 if (UNLIKELY(list_.size == 0)) {
524 ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
525 auto it = list_.upper.end() - 1;
527 lastUpperValue -= 8 - folly::findLastSet(*it);
528 lastValue_ = readLowerPart(list_.size - 1) |
529 (lastUpperValue << list_.numLowerBits);
539 if (UNLIKELY(progress_ == list_.size)) {
540 value_ = std::numeric_limits<ValueType>::max();
543 value_ = readLowerPart(progress_) |
544 (upper_.next() << list_.numLowerBits);
549 bool skip(size_t n) {
553 if (LIKELY(progress_ <= list_.size)) {
554 value_ = readLowerPart(progress_ - 1) |
555 (upper_.skip(n) << list_.numLowerBits);
559 progress_ = list_.size;
560 value_ = std::numeric_limits<ValueType>::max();
564 bool skipTo(ValueType value) {
565 DCHECK_GE(value, value_);
566 if (value <= value_) {
568 } else if (value > lastValue_) {
569 progress_ = list_.size;
570 value_ = std::numeric_limits<ValueType>::max();
574 upper_.skipToNext(value >> list_.numLowerBits);
579 bool jump(size_t n) {
580 if (LIKELY(n - 1 < list_.size)) { // n > 0 && n <= list_.size
582 value_ = readLowerPart(n - 1) | (upper_.jump(n) << list_.numLowerBits);
588 progress_ = list_.size;
589 value_ = std::numeric_limits<ValueType>::max();
593 ValueType jumpTo(ValueType value) {
597 } else if (value > lastValue_) {
598 progress_ = list_.size;
599 value_ = std::numeric_limits<ValueType>::max();
603 upper_.jumpToNext(value >> list_.numLowerBits);
608 size_t size() const { return list_.size; }
610 size_t position() const { return progress_ - 1; }
611 ValueType value() const { return value_; }
614 ValueType readLowerPart(size_t i) const {
615 DCHECK_LT(i, list_.size);
616 const size_t pos = i * list_.numLowerBits;
617 const unsigned char* ptr = list_.lower.data() + (pos / 8);
618 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
619 return lowerMask_ & (ptrv >> (pos % 8));
622 void iterateTo(ValueType value) {
623 progress_ = upper_.position();
624 value_ = readLowerPart(progress_) | (upper_.value() << list_.numLowerBits);
626 while (value_ < value) {
627 value_ = readLowerPart(progress_) | (upper_.next() << list_.numLowerBits);
632 const EliasFanoCompressedList list_;
633 const ValueType lowerMask_;
634 detail::UpperBitsReader<Encoder, Instructions> upper_;
635 size_t progress_ = 0;
636 ValueType value_ = 0;
637 ValueType lastValue_;
642 #endif // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H