2 * Copyright 2013 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
31 #if !defined(__x86_64__)
32 #error EliasFanoCoding.h requires x86_64
38 #include <type_traits>
39 #include <boost/noncopyable.hpp>
40 #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 template <class Value,
53 class SkipValue = size_t,
54 size_t kSkipQuantum = 0, // 0 = disabled
55 size_t kForwardQuantum = 0> // 0 = disabled
56 struct EliasFanoCompressedList {
57 static_assert(std::is_integral<Value>::value &&
58 std::is_unsigned<Value>::value,
59 "Value should be unsigned integral");
61 typedef Value ValueType;
62 typedef SkipValue SkipValueType;
64 EliasFanoCompressedList()
65 : size(0), numLowerBits(0) { }
67 static constexpr size_t skipQuantum = kSkipQuantum;
68 static constexpr size_t forwardQuantum = kForwardQuantum;
73 // WARNING: EliasFanoCompressedList has no ownership of
74 // lower, upper, skipPointers and forwardPointers.
75 // The 7 bytes following the last byte of lower and upper
76 // sequences should be readable.
77 folly::ByteRange lower;
78 folly::ByteRange upper;
80 folly::ByteRange skipPointers;
81 folly::ByteRange forwardPointers;
84 ::free(const_cast<unsigned char*>(lower.data()));
85 ::free(const_cast<unsigned char*>(upper.data()));
86 ::free(const_cast<unsigned char*>(skipPointers.data()));
87 ::free(const_cast<unsigned char*>(forwardPointers.data()));
90 static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
91 if (size == 0 || upperBound < size) {
94 // floor(log(upperBound / size));
95 return folly::findLastSet(upperBound / size) - 1;
98 // WARNING: encode() mallocates lower, upper, skipPointers
99 // and forwardPointers. As EliasFanoCompressedList has
100 // no ownership of them, you need to call free() explicitly.
101 static void encode(const ValueType* list, size_t size,
102 EliasFanoCompressedList& result) {
103 encode(list, list + size, result);
106 template <class RandomAccessIterator>
107 static void encode(RandomAccessIterator begin,
108 RandomAccessIterator end,
109 EliasFanoCompressedList& result) {
111 const size_t size = end - begin;
114 result = EliasFanoCompressedList();
118 DCHECK(std::is_sorted(list, list + size));
120 const ValueType upperBound = list[size - 1];
121 uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
123 // This is detail::writeBits56 limitation.
124 numLowerBits = std::min<uint8_t>(numLowerBits, 56);
125 CHECK_LT(numLowerBits, 8 * sizeof(Value)); // As we shift by numLowerBits.
127 // WARNING: Current read/write logic assumes that the 7 bytes
128 // following the last byte of lower and upper sequences are
129 // readable (stored value doesn't matter and won't be changed),
130 // so we allocate additional 7B, but do not include them in size
131 // of returned value.
134 const size_t lowerSize = (numLowerBits * size + 7) / 8;
135 unsigned char* const lower =
136 static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
137 const ValueType lowerMask = (ValueType(1) << numLowerBits) - 1;
138 for (size_t i = 0; i < size; ++i) {
139 const ValueType lowerBits = list[i] & lowerMask;
140 writeBits56(lower, i * numLowerBits, numLowerBits, lowerBits);
144 // Upper bits are stored using unary delta encoding.
145 // For example, (3 5 5 9) will be encoded as 1000011001000_2.
146 const size_t upperSizeBits =
147 (upperBound >> numLowerBits) + // Number of 0-bits to be stored.
149 const size_t upperSize = (upperSizeBits + 7) / 8;
150 unsigned char* const upper =
151 static_cast<unsigned char*>(calloc(upperSize + 7, 1));
152 for (size_t i = 0; i < size; ++i) {
153 const ValueType upperBits = list[i] >> numLowerBits;
154 const size_t pos = upperBits + i; // upperBits 0-bits and (i + 1) 1-bits.
155 upper[pos / 8] |= 1U << (pos % 8);
158 // *** Skip pointers.
159 // Store (1-indexed) position of every skipQuantum-th
160 // 0-bit in upper bits sequence.
161 SkipValueType* skipPointers = nullptr;
162 size_t numSkipPointers = 0;
163 /* static */ if (skipQuantum != 0) {
164 // Workaround to avoid 'division by zero' compile-time error.
165 constexpr size_t q = skipQuantum ?: 1;
166 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.
169 numSkipPointers = (8 * upperSize - size) / q;
170 skipPointers = static_cast<SkipValueType*>(
173 : calloc(numSkipPointers, sizeof(SkipValueType)));
175 for (size_t i = 0, pos = 0; i < size; ++i) {
176 const ValueType upperBits = list[i] >> numLowerBits;
177 for (; (pos + 1) * q <= upperBits; ++pos) {
178 skipPointers[pos] = i + (pos + 1) * q;
183 // *** Forward pointers.
184 // Store (1-indexed) position of every forwardQuantum-th
185 // 1-bit in upper bits sequence.
186 SkipValueType* forwardPointers = nullptr;
187 size_t numForwardPointers = 0;
188 /* static */ if (forwardQuantum != 0) {
189 // Workaround to avoid 'division by zero' compile-time error.
190 constexpr size_t q = forwardQuantum ?: 1;
191 CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
193 numForwardPointers = size / q;
194 forwardPointers = static_cast<SkipValueType*>(
195 numForwardPointers == 0
197 : malloc(numForwardPointers * sizeof(SkipValueType)));
199 for (size_t i = q - 1, pos = 0; i < size; i += q, ++pos) {
200 const ValueType upperBits = list[i] >> numLowerBits;
201 forwardPointers[pos] = upperBits + i + 1;
207 result.numLowerBits = numLowerBits;
208 result.lower.reset(lower, lowerSize);
209 result.upper.reset(upper, upperSize);
210 result.skipPointers.reset(
211 reinterpret_cast<unsigned char*>(skipPointers),
212 numSkipPointers * sizeof(SkipValueType));
213 result.forwardPointers.reset(
214 reinterpret_cast<unsigned char*>(forwardPointers),
215 numForwardPointers * sizeof(SkipValueType));
219 // Writes value (with len up to 56 bits) to data starting at pos-th bit.
220 static void writeBits56(unsigned char* data, size_t pos,
221 uint8_t len, uint64_t value) {
222 DCHECK_LE(uint32_t(len), 56);
223 DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
224 unsigned char* const ptr = data + (pos / 8);
225 uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
226 ptrv |= value << (pos % 8);
227 folly::storeUnaligned<uint64_t>(ptr, ptrv);
231 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
232 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
233 // it for __builtin_popcountll intrinsic.
234 // But we provide an alternative way for the client code: it can switch to
235 // the appropriate version of EliasFanoReader<> in realtime (client should
236 // implement this switching logic itself) by specifying instruction set to
238 namespace instructions {
241 static bool supported() {
244 static inline uint64_t popcount(uint64_t value) {
245 return __builtin_popcountll(value);
247 static inline int ctz(uint64_t value) {
249 return __builtin_ctzll(value);
253 struct Fast : public Default {
254 static bool supported() {
256 return cpuId.popcnt();
258 static inline uint64_t popcount(uint64_t value) {
260 asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
265 } // namespace instructions
269 template <class CompressedList, class Instructions>
270 class UpperBitsReader {
271 typedef typename CompressedList::SkipValueType SkipValueType;
273 typedef typename CompressedList::ValueType ValueType;
275 explicit UpperBitsReader(const CompressedList& list)
276 : forwardPointers_(list.forwardPointers.data()),
277 skipPointers_(list.skipPointers.data()),
278 start_(list.upper.data()),
279 block_(start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0),
280 outer_(0), // outer offset: number of consumed bytes in upper.
281 inner_(-1), // inner offset: (bit) position in current block.
282 position_(-1), // index of current value (= #reads - 1).
285 size_t position() const { return position_; }
286 ValueType value() const { return value_; }
289 // Skip to the first non-zero block.
290 while (block_ == 0) {
291 outer_ += sizeof(block_t);
292 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
296 inner_ = Instructions::ctz(block_);
297 block_ &= block_ - 1;
302 ValueType skip(size_t n) {
305 position_ += n; // n 1-bits will be read.
307 // Use forward pointer.
308 if (CompressedList::forwardQuantum > 0 &&
309 n > CompressedList::forwardQuantum) {
310 // Workaround to avoid 'division by zero' compile-time error.
311 constexpr size_t q = CompressedList::forwardQuantum ?: 1;
313 const size_t steps = position_ / q;
315 folly::loadUnaligned<SkipValueType>(
316 forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
319 n = position_ + 1 - steps * q; // n is > 0.
320 // correct inner_ will be set at the end.
324 // Find necessary block.
325 while ((cnt = Instructions::popcount(block_)) < n) {
327 outer_ += sizeof(block_t);
328 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
331 // NOTE: Trying to skip half-block here didn't show any
332 // performance improvements.
336 // Kill n - 1 least significant 1-bits.
337 for (size_t i = 0; i < n - 1; ++i) {
338 block_ &= block_ - 1;
341 inner_ = Instructions::ctz(block_);
342 block_ &= block_ - 1;
347 // Skip to the first element that is >= v and located *after* the current
348 // one (so even if current value equals v, position will be increased by 1).
349 ValueType skipToNext(ValueType v) {
350 DCHECK_GE(v, value_);
353 if (CompressedList::skipQuantum > 0 &&
354 v >= value_ + CompressedList::skipQuantum) {
355 // Workaround to avoid 'division by zero' compile-time error.
356 constexpr size_t q = CompressedList::skipQuantum ?: 1;
358 const size_t steps = v / q;
360 folly::loadUnaligned<SkipValueType>(
361 skipPointers_ + (steps - 1) * sizeof(SkipValueType));
364 position_ = dest - q * steps - 1;
365 // Correct inner_ and value_ will be set during the next()
368 // NOTE: Corresponding block of lower bits sequence may be
369 // prefetched here (via __builtin_prefetch), but experiments
370 // didn't show any significant improvements.
375 size_t skip = v - (8 * outer_ - position_ - 1);
377 constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
378 while ((cnt = Instructions::popcount(~block_)) < skip) {
380 position_ += kBitsPerBlock - cnt;
381 outer_ += sizeof(block_t);
382 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
385 // Try to skip half-block.
386 constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
387 constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
388 if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
389 position_ += kBitsPerHalfBlock - cnt;
390 block_ &= ~halfBlockMask;
393 // Just skip until we see expected value.
394 while (next() < v) { }
399 ValueType setValue() {
400 value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
404 void reposition(size_t dest) {
406 block_ = folly::loadUnaligned<block_t>(start_ + outer_);
407 block_ &= ~((block_t(1) << (dest % 8)) - 1);
410 typedef unsigned long long block_t;
411 const unsigned char* const forwardPointers_;
412 const unsigned char* const skipPointers_;
413 const unsigned char* const start_;
421 } // namespace detail
423 template <class CompressedList,
424 class Instructions = instructions::Default>
425 class EliasFanoReader : private boost::noncopyable {
427 typedef typename CompressedList::ValueType ValueType;
429 explicit EliasFanoReader(const CompressedList& list)
431 lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
435 DCHECK(Instructions::supported());
436 // To avoid extra branching during skipTo() while reading
437 // upper sequence we need to know the last element.
438 if (UNLIKELY(list_.size == 0)) {
442 ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
443 auto it = list_.upper.end() - 1;
445 lastUpperValue -= 8 - folly::findLastSet(*it);
446 lastValue_ = readLowerPart(list_.size - 1) |
447 (lastUpperValue << list_.numLowerBits);
450 size_t size() const { return list_.size; }
452 size_t position() const { return progress_ - 1; }
453 ValueType value() const { return value_; }
456 if (UNLIKELY(progress_ == list_.size)) {
457 value_ = std::numeric_limits<ValueType>::max();
460 value_ = readLowerPart(progress_) |
461 (upper_.next() << list_.numLowerBits);
466 bool skip(size_t n) {
470 if (LIKELY(progress_ < list_.size)) {
471 value_ = readLowerPart(progress_) |
472 (upper_.skip(n) << list_.numLowerBits);
477 progress_ = list_.size;
478 value_ = std::numeric_limits<ValueType>::max();
482 bool skipTo(ValueType value) {
483 DCHECK_GE(value, value_);
484 if (value <= value_) {
487 if (value > lastValue_) {
488 progress_ = list_.size;
489 value_ = std::numeric_limits<ValueType>::max();
493 upper_.skipToNext(value >> list_.numLowerBits);
494 progress_ = upper_.position();
495 value_ = readLowerPart(progress_) |
496 (upper_.value() << list_.numLowerBits);
498 while (value_ < value) {
499 value_ = readLowerPart(progress_) |
500 (upper_.next() << list_.numLowerBits);
508 ValueType readLowerPart(size_t i) const {
509 const size_t pos = i * list_.numLowerBits;
510 const unsigned char* ptr = list_.lower.data() + (pos / 8);
511 const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
512 return lowerMask_ & (ptrv >> (pos % 8));
515 const CompressedList list_;
516 const ValueType lowerMask_;
517 detail::UpperBitsReader<CompressedList, Instructions> upper_;
520 ValueType lastValue_;
525 #endif // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H