EliasFanoReader::goTo()
[folly.git] / folly / experimental / EliasFanoCoding.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * @author Philip Pronin (philipp@fb.com)
19  *
20  * Based on the paper by Sebastiano Vigna,
21  * "Quasi-succinct indices" (arxiv:1206.4300).
22  */
23
24 #ifndef FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
25 #define FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
26
27 #ifndef __GNUC__
28 #error EliasFanoCoding.h requires GCC
29 #endif
30
31 #if !FOLLY_X64
32 #error EliasFanoCoding.h requires x86_64
33 #endif
34
35 #include <algorithm>
36 #include <cstdlib>
37 #include <limits>
38 #include <type_traits>
39 #include <boost/noncopyable.hpp>
40 #include <glog/logging.h>
41
42 #include <folly/Bits.h>
43 #include <folly/CpuId.h>
44 #include <folly/Likely.h>
45 #include <folly/Range.h>
46
47 #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
48 #error EliasFanoCoding.h requires little endianness
49 #endif
50
51 namespace folly { namespace compression {
52
53 struct EliasFanoCompressedList {
54   EliasFanoCompressedList()
55     : size(0), numLowerBits(0) { }
56
57   void free() {
58     ::free(const_cast<unsigned char*>(lower.data()));
59     ::free(const_cast<unsigned char*>(upper.data()));
60     ::free(const_cast<unsigned char*>(skipPointers.data()));
61     ::free(const_cast<unsigned char*>(forwardPointers.data()));
62   }
63
64   size_t size;
65   uint8_t numLowerBits;
66
67   // WARNING: EliasFanoCompressedList has no ownership of
68   // lower, upper, skipPointers and forwardPointers.
69   // The 7 bytes following the last byte of lower and upper
70   // sequences should be readable.
71   folly::ByteRange lower;
72   folly::ByteRange upper;
73
74   folly::ByteRange skipPointers;
75   folly::ByteRange forwardPointers;
76 };
77
78 // Version history:
79 // In version 1 skip / forward pointers encoding has been changed,
80 // so SkipValue = uint32_t is able to address up to ~4B elements,
81 // instead of only ~2B.
82 template <class Value,
83           class SkipValue = size_t,
84           size_t kSkipQuantum = 0,     // 0 = disabled
85           size_t kForwardQuantum = 0,  // 0 = disabled
86           size_t kVersion = 0>
87 struct EliasFanoEncoder {
88   static_assert(std::is_integral<Value>::value &&
89                 std::is_unsigned<Value>::value,
90                 "Value should be unsigned integral");
91
92   typedef EliasFanoCompressedList CompressedList;
93
94   typedef Value ValueType;
95   typedef SkipValue SkipValueType;
96
97   static constexpr size_t skipQuantum = kSkipQuantum;
98   static constexpr size_t forwardQuantum = kForwardQuantum;
99   static constexpr size_t version = kVersion;
100
101   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
102     if (size == 0 || upperBound < size) {
103       return 0;
104     }
105     // floor(log(upperBound / size));
106     return folly::findLastSet(upperBound / size) - 1;
107   }
108
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   static void encode(const ValueType* list, size_t size,
113                      EliasFanoCompressedList& result) {
114     encode(list, list + size, result);
115   }
116
117   // Range (begin, end) should be sorted.
118   template <class RandomAccessIterator>
119   static void encode(RandomAccessIterator begin,
120                      RandomAccessIterator end,
121                      EliasFanoCompressedList& result) {
122     CHECK(std::is_sorted(begin, end));
123
124     auto list = begin;
125     const size_t size = end - begin;
126
127     if (size == 0) {
128       result = EliasFanoCompressedList();
129       return;
130     }
131
132     const ValueType upperBound = list[size - 1];
133     uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
134
135     // This is detail::writeBits56 limitation.
136     numLowerBits = std::min<uint8_t>(numLowerBits, 56);
137     CHECK_LT(numLowerBits, 8 * sizeof(Value));  // As we shift by numLowerBits.
138
139     // WARNING: Current read/write logic assumes that the 7 bytes
140     // following the last byte of lower and upper sequences are
141     // readable (stored value doesn't matter and won't be changed),
142     // so we allocate additional 7B, but do not include them in size
143     // of returned value.
144
145     // *** Lower bits.
146     const size_t lowerSize = (numLowerBits * size + 7) / 8;
147     unsigned char* lower = nullptr;
148     if (lowerSize > 0) {  // numLowerBits != 0
149       lower = static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
150       const ValueType lowerMask = (ValueType(1) << numLowerBits) - 1;
151       for (size_t i = 0; i < size; ++i) {
152         const ValueType lowerBits = list[i] & lowerMask;
153         writeBits56(lower, i * numLowerBits, numLowerBits, lowerBits);
154       }
155     }
156
157     // *** Upper bits.
158     // Upper bits are stored using unary delta encoding.
159     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
160     const size_t upperSizeBits =
161       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
162       size;                           // 1-bits.
163     const size_t upperSize = (upperSizeBits + 7) / 8;
164     unsigned char* const upper =
165       static_cast<unsigned char*>(calloc(upperSize + 7, 1));
166     for (size_t i = 0; i < size; ++i) {
167       const ValueType upperBits = list[i] >> numLowerBits;
168       const size_t pos = upperBits + i;  // upperBits 0-bits and (i + 1) 1-bits.
169       upper[pos / 8] |= 1U << (pos % 8);
170     }
171
172     // *** Skip pointers.
173     // Store (1-indexed) position of every skipQuantum-th
174     // 0-bit in upper bits sequence.
175     SkipValueType* skipPointers = nullptr;
176     size_t numSkipPointers = 0;
177     /* static */ if (skipQuantum != 0) {
178       // Workaround to avoid 'division by zero' compile-time error.
179       constexpr size_t q = skipQuantum ?: 1;
180       /* static */ if (kVersion > 0) {
181         CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
182       } else {
183         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
184       }
185       // 8 * upperSize is used here instead of upperSizeBits, as that is
186       // more serialization-friendly way (upperSizeBits isn't known outside of
187       // this function, unlike upperSize; thus numSkipPointers could easily be
188       // deduced from upperSize).
189       numSkipPointers = (8 * upperSize - size) / q;
190       skipPointers = static_cast<SkipValueType*>(
191           numSkipPointers == 0
192             ? nullptr
193             : calloc(numSkipPointers, sizeof(SkipValueType)));
194
195       for (size_t i = 0, pos = 0; i < size; ++i) {
196         const ValueType upperBits = list[i] >> numLowerBits;
197         for (; (pos + 1) * q <= upperBits; ++pos) {
198           /* static */ if (kVersion > 0) {
199             // Since version 1, just the number of preceding 1-bits is stored.
200             skipPointers[pos] = i;
201           } else {
202             skipPointers[pos] = i + (pos + 1) * q;
203           }
204         }
205       }
206     }
207
208     // *** Forward pointers.
209     // Store (1-indexed) position of every forwardQuantum-th
210     // 1-bit in upper bits sequence.
211     SkipValueType* forwardPointers = nullptr;
212     size_t numForwardPointers = 0;
213     /* static */ if (forwardQuantum != 0) {
214       // Workaround to avoid 'division by zero' compile-time error.
215       constexpr size_t q = forwardQuantum ?: 1;
216       /* static */ if (kVersion > 0) {
217         CHECK_LT(upperBound >> numLowerBits,
218                  std::numeric_limits<SkipValueType>::max());
219       } else {
220         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
221       }
222
223       numForwardPointers = size / q;
224       forwardPointers = static_cast<SkipValueType*>(
225         numForwardPointers == 0
226           ? nullptr
227           : malloc(numForwardPointers * sizeof(SkipValueType)));
228
229       for (size_t i = q - 1, pos = 0; i < size; i += q, ++pos) {
230         const ValueType upperBits = list[i] >> numLowerBits;
231         /* static */ if (kVersion > 0) {
232           // Since version 1, just the number of preceding 0-bits is stored.
233           forwardPointers[pos] = upperBits;
234         } else {
235           forwardPointers[pos] = upperBits + i + 1;
236         }
237       }
238     }
239
240     // *** Result.
241     result.size = size;
242     result.numLowerBits = numLowerBits;
243     result.lower.reset(lower, lowerSize);
244     result.upper.reset(upper, upperSize);
245     result.skipPointers.reset(
246         reinterpret_cast<unsigned char*>(skipPointers),
247         numSkipPointers * sizeof(SkipValueType));
248     result.forwardPointers.reset(
249         reinterpret_cast<unsigned char*>(forwardPointers),
250         numForwardPointers * sizeof(SkipValueType));
251   }
252
253  private:
254   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
255   static void writeBits56(unsigned char* data, size_t pos,
256                           uint8_t len, uint64_t value) {
257     DCHECK_LE(uint32_t(len), 56);
258     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
259     unsigned char* const ptr = data + (pos / 8);
260     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
261     ptrv |= value << (pos % 8);
262     folly::storeUnaligned<uint64_t>(ptr, ptrv);
263   }
264 };
265
266 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
267 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
268 // it for __builtin_popcountll intrinsic.
269 // But we provide an alternative way for the client code: it can switch to
270 // the appropriate version of EliasFanoReader<> in realtime (client should
271 // implement this switching logic itself) by specifying instruction set to
272 // use explicitly.
273 namespace instructions {
274
275 struct Default {
276   static bool supported() {
277     return true;
278   }
279   static inline uint64_t popcount(uint64_t value) {
280     return __builtin_popcountll(value);
281   }
282   static inline int ctz(uint64_t value) {
283     DCHECK_GT(value, 0);
284     return __builtin_ctzll(value);
285   }
286 };
287
288 struct Fast : public Default {
289   static bool supported() {
290     folly::CpuId cpuId;
291     return cpuId.popcnt();
292   }
293   static inline uint64_t popcount(uint64_t value) {
294     uint64_t result;
295     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
296     return result;
297   }
298 };
299
300 }  // namespace instructions
301
302 namespace detail {
303
304 template <class Encoder, class Instructions>
305 class UpperBitsReader {
306   typedef typename Encoder::SkipValueType SkipValueType;
307  public:
308   typedef typename Encoder::ValueType ValueType;
309
310   explicit UpperBitsReader(const EliasFanoCompressedList& list)
311     : forwardPointers_(list.forwardPointers.data()),
312       skipPointers_(list.skipPointers.data()),
313       start_(list.upper.data()) {
314     reset();
315   }
316
317   void reset() {
318     block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
319     outer_ = 0;
320     inner_ = -1;
321     position_ = -1;
322     value_ = 0;
323   }
324
325   size_t position() const { return position_; }
326   ValueType value() const { return value_; }
327
328   ValueType next() {
329     // Skip to the first non-zero block.
330     while (block_ == 0) {
331       outer_ += sizeof(block_t);
332       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
333     }
334
335     ++position_;
336     inner_ = Instructions::ctz(block_);
337     block_ &= block_ - 1;
338
339     return setValue();
340   }
341
342   ValueType skip(size_t n) {
343     DCHECK_GT(n, 0);
344
345     position_ += n;  // n 1-bits will be read.
346
347     // Use forward pointer.
348     if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
349       // Workaround to avoid 'division by zero' compile-time error.
350       constexpr size_t q = Encoder::forwardQuantum ?: 1;
351
352       const size_t steps = position_ / q;
353       const size_t dest =
354         folly::loadUnaligned<SkipValueType>(
355             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
356
357       /* static */ if (Encoder::version > 0) {
358         reposition(dest + steps * q);
359       } else {
360         reposition(dest);
361       }
362       n = position_ + 1 - steps * q;  // n is > 0.
363       // correct inner_ will be set at the end.
364     }
365
366     size_t cnt;
367     // Find necessary block.
368     while ((cnt = Instructions::popcount(block_)) < n) {
369       n -= cnt;
370       outer_ += sizeof(block_t);
371       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
372     }
373
374     // NOTE: Trying to skip half-block here didn't show any
375     // performance improvements.
376
377     DCHECK_GT(n, 0);
378
379     // Kill n - 1 least significant 1-bits.
380     for (size_t i = 0; i < n - 1; ++i) {
381       block_ &= block_ - 1;
382     }
383
384     inner_ = Instructions::ctz(block_);
385     block_ &= block_ - 1;
386
387     return setValue();
388   }
389
390   // Skip to the first element that is >= v and located *after* the current
391   // one (so even if current value equals v, position will be increased by 1).
392   ValueType skipToNext(ValueType v) {
393     DCHECK_GE(v, value_);
394
395     // Use skip pointer.
396     if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
397       // Workaround to avoid 'division by zero' compile-time error.
398       constexpr size_t q = Encoder::skipQuantum ?: 1;
399
400       const size_t steps = v / q;
401       const size_t dest =
402         folly::loadUnaligned<SkipValueType>(
403             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
404
405       /* static */ if (Encoder::version > 0) {
406         reposition(dest + q * steps);
407         position_ = dest - 1;
408       } else {
409         reposition(dest);
410         position_ = dest - q * steps - 1;
411       }
412       // Correct inner_ and value_ will be set during the next()
413       // call at the end.
414
415       // NOTE: Corresponding block of lower bits sequence may be
416       // prefetched here (via __builtin_prefetch), but experiments
417       // didn't show any significant improvements.
418     }
419
420     // Skip by blocks.
421     size_t cnt;
422     size_t skip = v - (8 * outer_ - position_ - 1);
423
424     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
425     while ((cnt = Instructions::popcount(~block_)) < skip) {
426       skip -= cnt;
427       position_ += kBitsPerBlock - cnt;
428       outer_ += sizeof(block_t);
429       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
430     }
431
432     // Try to skip half-block.
433     constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
434     constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
435     if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
436       position_ += kBitsPerHalfBlock - cnt;
437       block_ &= ~halfBlockMask;
438     }
439
440     // Just skip until we see expected value.
441     while (next() < v) { }
442     return value_;
443   }
444
445   ValueType goTo(size_t n) {
446     if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
447       reset();
448     } else {
449       position_ = -1;  // Avoid reading the head, skip() will call reposition().
450     }
451     return skip(n);
452   }
453
454  private:
455   ValueType setValue() {
456     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
457     return value_;
458   }
459
460   void reposition(size_t dest) {
461     outer_ = dest / 8;
462     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
463     block_ &= ~((block_t(1) << (dest % 8)) - 1);
464   }
465
466   typedef unsigned long long block_t;
467   const unsigned char* const forwardPointers_;
468   const unsigned char* const skipPointers_;
469   const unsigned char* const start_;
470   block_t block_;
471   size_t outer_;  // Outer offset: number of consumed bytes in upper.
472   size_t inner_;  // Inner offset: (bit) position in current block.
473   size_t position_;  // Index of current value (= #reads - 1).
474   ValueType value_;
475 };
476
477 }  // namespace detail
478
479 template <class Encoder,
480           class Instructions = instructions::Default>
481 class EliasFanoReader : private boost::noncopyable {
482  public:
483   typedef Encoder EncoderType;
484   typedef typename Encoder::ValueType ValueType;
485
486   explicit EliasFanoReader(const EliasFanoCompressedList& list)
487     : list_(list),
488       lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
489       upper_(list_) {
490     DCHECK(Instructions::supported());
491     // To avoid extra branching during skipTo() while reading
492     // upper sequence we need to know the last element.
493     if (UNLIKELY(list_.size == 0)) {
494       lastValue_ = 0;
495       return;
496     }
497     ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
498     auto it = list_.upper.end() - 1;
499     DCHECK_NE(*it, 0);
500     lastUpperValue -= 8 - folly::findLastSet(*it);
501     lastValue_ = readLowerPart(list_.size - 1) |
502                  (lastUpperValue << list_.numLowerBits);
503   }
504
505   size_t size() const { return list_.size; }
506
507   size_t position() const { return progress_ - 1; }
508   ValueType value() const { return value_; }
509
510   bool next() {
511     if (UNLIKELY(progress_ == list_.size)) {
512       value_ = std::numeric_limits<ValueType>::max();
513       return false;
514     }
515     value_ = readLowerPart(progress_) |
516              (upper_.next() << list_.numLowerBits);
517     ++progress_;
518     return true;
519   }
520
521   bool skip(size_t n) {
522     CHECK_GT(n, 0);
523
524     progress_ += n;
525     if (LIKELY(progress_ <= list_.size)) {
526       value_ = readLowerPart(progress_ - 1) |
527                (upper_.skip(n) << list_.numLowerBits);
528       return true;
529     }
530
531     progress_ = list_.size;
532     value_ = std::numeric_limits<ValueType>::max();
533     return false;
534   }
535
536   bool skipTo(ValueType value) {
537     DCHECK_GE(value, value_);
538     if (value <= value_) {
539       return true;
540     }
541     if (value > lastValue_) {
542       progress_ = list_.size;
543       value_ = std::numeric_limits<ValueType>::max();
544       return false;
545     }
546
547     upper_.skipToNext(value >> list_.numLowerBits);
548     progress_ = upper_.position();
549     value_ = readLowerPart(progress_) |
550              (upper_.value() << list_.numLowerBits);
551     ++progress_;
552     while (value_ < value) {
553       value_ = readLowerPart(progress_) |
554                (upper_.next() << list_.numLowerBits);
555       ++progress_;
556     }
557
558     return true;
559   }
560
561   bool goTo(size_t n) {
562     if (LIKELY(n - 1 < list_.size)) {  // n > 0 && n <= list_.size
563       progress_ = n;
564       value_ = readLowerPart(n - 1) | (upper_.goTo(n) << list_.numLowerBits);
565       return true;
566     } else if (n == 0) {
567       upper_.reset();
568       progress_ = 0;
569       value_ = 0;
570       return true;
571     }
572     progress_ = list_.size;
573     value_ = std::numeric_limits<ValueType>::max();
574     return false;
575   }
576
577  private:
578   ValueType readLowerPart(size_t i) const {
579     DCHECK_LT(i, list_.size);
580     const size_t pos = i * list_.numLowerBits;
581     const unsigned char* ptr = list_.lower.data() + (pos / 8);
582     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
583     return lowerMask_ & (ptrv >> (pos % 8));
584   }
585
586   const EliasFanoCompressedList list_;
587   const ValueType lowerMask_;
588   detail::UpperBitsReader<Encoder, Instructions> upper_;
589   size_t progress_ = 0;
590   ValueType value_ = 0;
591   ValueType lastValue_;
592 };
593
594 }}  // namespaces
595
596 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H