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(const folly::CpuId& cpuId = {}) {
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);
304 static inline uint64_t blsr(uint64_t value) {
305 return value & (value - 1);
309 struct Nehalem : public Default {
310 static bool supported(const folly::CpuId& cpuId = {}) {
311 return cpuId.popcnt();
313 static inline uint64_t popcount(uint64_t value) {
314 // POPCNT is supported starting with Intel Nehalem, AMD K10.
316 asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
321 struct Haswell : public Nehalem {
322 static bool supported(const folly::CpuId& cpuId = {}) {
323 return Nehalem::supported(cpuId) && cpuId.bmi1();
325 static inline uint64_t blsr(uint64_t value) {
326 // BMI1 is supported starting with Intel Haswell, AMD Piledriver.
327 // BLSR combines two instuctions into one and reduces register pressure.
329 asm ("blsrq %1, %0" : "=r" (result) : "r" (value));
334 } // namespace instructions
338 template <class Encoder, class Instructions>
339 class UpperBitsReader {
340 typedef typename Encoder::SkipValueType SkipValueType;
342 typedef typename Encoder::ValueType ValueType;
344 explicit UpperBitsReader(const EliasFanoCompressedList& list)
345 : forwardPointers_(list.forwardPointers.data()),
346 skipPointers_(list.skipPointers.data()),
347 start_(list.upper.data()) {
352 block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
359 size_t position() const { return position_; }
360 ValueType value() const { return value_; }
363 // Skip to the first non-zero block.
364 while (block_ == 0) {
365 outer_ += sizeof(block_t);
366 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
370 inner_ = Instructions::ctz(block_);
371 block_ = Instructions::blsr(block_);
376 ValueType skip(size_t n) {
379 position_ += n; // n 1-bits will be read.
381 // Use forward pointer.
382 if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
383 // Workaround to avoid 'division by zero' compile-time error.
384 constexpr size_t q = Encoder::forwardQuantum ?: 1;
386 const size_t steps = position_ / q;
388 folly::loadUnaligned<SkipValueType>(
389 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
391 /* static */ if (Encoder::version > 0) {
392 reposition(dest + steps * q);
396 n = position_ + 1 - steps * q; // n is > 0.
397 // correct inner_ will be set at the end.
401 // Find necessary block.
402 while ((cnt = Instructions::popcount(block_)) < n) {
404 outer_ += sizeof(block_t);
405 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
408 // NOTE: Trying to skip half-block here didn't show any
409 // performance improvements.
413 // Kill n - 1 least significant 1-bits.
414 for (size_t i = 0; i < n - 1; ++i) {
415 block_ = Instructions::blsr(block_);
418 inner_ = Instructions::ctz(block_);
419 block_ = Instructions::blsr(block_);
424 // Skip to the first element that is >= v and located *after* the current
425 // one (so even if current value equals v, position will be increased by 1).
426 ValueType skipToNext(ValueType v) {
427 DCHECK_GE(v, value_);
430 if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
431 // Workaround to avoid 'division by zero' compile-time error.
432 constexpr size_t q = Encoder::skipQuantum ?: 1;
434 const size_t steps = v / q;
436 folly::loadUnaligned<SkipValueType>(
437 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
439 /* static */ if (Encoder::version > 0) {
440 reposition(dest + q * steps);
441 position_ = dest - 1;
444 position_ = dest - q * steps - 1;
446 // Correct inner_ and value_ will be set during the next()
449 // NOTE: Corresponding block of lower bits sequence may be
450 // prefetched here (via __builtin_prefetch), but experiments
451 // didn't show any significant improvements.
456 size_t skip = v - (8 * outer_ - position_ - 1);
458 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
459 while ((cnt = Instructions::popcount(~block_)) < skip) {
461 position_ += kBitsPerBlock - cnt;
462 outer_ += sizeof(block_t);
463 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
466 // Try to skip half-block.
467 constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
468 constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
469 if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
470 position_ += kBitsPerHalfBlock - cnt;
471 block_ &= ~halfBlockMask;
474 // Just skip until we see expected value.
475 while (next() < v) { }
479 ValueType jump(size_t n) {
480 if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
483 position_ = -1; // Avoid reading the head, skip() will reposition.
488 ValueType jumpToNext(ValueType v) {
489 if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
492 value_ = 0; // Avoid reading the head, skipToNext() will reposition.
494 return skipToNext(v);
498 ValueType setValue() {
499 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
503 void reposition(size_t dest) {
505 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
506 block_ &= ~((block_t(1) << (dest % 8)) - 1);
509 typedef unsigned long long block_t;
510 const unsigned char* const forwardPointers_;
511 const unsigned char* const skipPointers_;
512 const unsigned char* const start_;
514 size_t outer_; // Outer offset: number of consumed bytes in upper.
515 size_t inner_; // Inner offset: (bit) position in current block.
516 size_t position_; // Index of current value (= #reads - 1).
520 } // namespace detail
522 template <class Encoder,
523 class Instructions = instructions::Default>
524 class EliasFanoReader : private boost::noncopyable {
526 typedef Encoder EncoderType;
527 typedef typename Encoder::ValueType ValueType;
529 explicit EliasFanoReader(const EliasFanoCompressedList& list)
531 lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
533 DCHECK(Instructions::supported());
534 // To avoid extra branching during skipTo() while reading
535 // upper sequence we need to know the last element.
536 if (UNLIKELY(list_.size == 0)) {
540 ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
541 auto it = list_.upper.end() - 1;
543 lastUpperValue -= 8 - folly::findLastSet(*it);
544 lastValue_ = readLowerPart(list_.size - 1) |
545 (lastUpperValue << list_.numLowerBits);
555 if (UNLIKELY(progress_ == list_.size)) {
556 value_ = std::numeric_limits<ValueType>::max();
559 value_ = readLowerPart(progress_) |
560 (upper_.next() << list_.numLowerBits);
565 bool skip(size_t n) {
569 if (LIKELY(progress_ <= list_.size)) {
570 value_ = readLowerPart(progress_ - 1) |
571 (upper_.skip(n) << list_.numLowerBits);
575 progress_ = list_.size;
576 value_ = std::numeric_limits<ValueType>::max();
580 bool skipTo(ValueType value) {
581 DCHECK_GE(value, value_);
582 if (value <= value_) {
584 } else if (value > lastValue_) {
585 progress_ = list_.size;
586 value_ = std::numeric_limits<ValueType>::max();
590 upper_.skipToNext(value >> list_.numLowerBits);
595 bool jump(size_t n) {
596 if (LIKELY(n - 1 < list_.size)) { // n > 0 && n <= list_.size
598 value_ = readLowerPart(n - 1) | (upper_.jump(n) << list_.numLowerBits);
604 progress_ = list_.size;
605 value_ = std::numeric_limits<ValueType>::max();
609 ValueType jumpTo(ValueType value) {
613 } else if (value > lastValue_) {
614 progress_ = list_.size;
615 value_ = std::numeric_limits<ValueType>::max();
619 upper_.jumpToNext(value >> list_.numLowerBits);
624 size_t size() const { return list_.size; }
626 size_t position() const { return progress_ - 1; }
627 ValueType value() const { return value_; }
630 ValueType readLowerPart(size_t i) const {
631 DCHECK_LT(i, list_.size);
632 const size_t pos = i * list_.numLowerBits;
633 const unsigned char* ptr = list_.lower.data() + (pos / 8);
634 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
635 return lowerMask_ & (ptrv >> (pos % 8));
638 void iterateTo(ValueType value) {
639 progress_ = upper_.position();
640 value_ = readLowerPart(progress_) | (upper_.value() << list_.numLowerBits);
642 while (value_ < value) {
643 value_ = readLowerPart(progress_) | (upper_.next() << list_.numLowerBits);
648 const EliasFanoCompressedList list_;
649 const ValueType lowerMask_;
650 detail::UpperBitsReader<Encoder, Instructions> upper_;
651 size_t progress_ = 0;
652 ValueType value_ = 0;
653 ValueType lastValue_;
658 #endif // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H