b428d54384da3d2d0d16772e19f62e25a2cc0ebc
[folly.git] / folly / experimental / EliasFanoCoding.h
1 /*
2  * Copyright 2015 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 #include <cstdlib>
28 #include <limits>
29 #include <type_traits>
30
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>
38
39 #ifndef __GNUC__
40 #error EliasFanoCoding.h requires GCC
41 #endif
42
43 #if !FOLLY_X64
44 #error EliasFanoCoding.h requires x86_64
45 #endif
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 template <class Pointer>
54 struct EliasFanoCompressedListBase {
55   EliasFanoCompressedListBase() = default;
56
57   template <class OtherPointer>
58   EliasFanoCompressedListBase(
59       const EliasFanoCompressedListBase<OtherPointer>& other)
60       : size(other.size),
61         numLowerBits(other.numLowerBits),
62         data(other.data),
63         skipPointers(reinterpret_cast<Pointer>(other.skipPointers)),
64         forwardPointers(reinterpret_cast<Pointer>(other.forwardPointers)),
65         lower(reinterpret_cast<Pointer>(other.lower)),
66         upper(reinterpret_cast<Pointer>(other.upper)) { }
67
68   template <class T = Pointer>
69   auto free() -> decltype(::free(T(nullptr))) {
70     return ::free(data.data());
71   }
72
73   size_t upperSize() const { return data.end() - upper; }
74
75   size_t size = 0;
76   uint8_t numLowerBits = 0;
77
78   // WARNING: EliasFanoCompressedList has no ownership of data. The 7
79   // bytes following the last byte should be readable.
80   folly::Range<Pointer> data;
81
82   Pointer skipPointers = nullptr;
83   Pointer forwardPointers = nullptr;
84   Pointer lower = nullptr;
85   Pointer upper = nullptr;
86 };
87
88 typedef EliasFanoCompressedListBase<const uint8_t*> EliasFanoCompressedList;
89 typedef EliasFanoCompressedListBase<uint8_t*> MutableEliasFanoCompressedList;
90
91 template <class Value,
92           class SkipValue = size_t,
93           size_t kSkipQuantum = 0,     // 0 = disabled
94           size_t kForwardQuantum = 0>  // 0 = disabled
95 struct EliasFanoEncoderV2 {
96   static_assert(std::is_integral<Value>::value &&
97                     std::is_unsigned<Value>::value,
98                 "Value should be unsigned integral");
99
100   typedef EliasFanoCompressedList CompressedList;
101   typedef MutableEliasFanoCompressedList MutableCompressedList;
102
103   typedef Value ValueType;
104   typedef SkipValue SkipValueType;
105   struct Layout;
106
107   static constexpr size_t skipQuantum = kSkipQuantum;
108   static constexpr size_t forwardQuantum = kForwardQuantum;
109
110   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
111     if (size == 0 || upperBound < size) {
112       return 0;
113     }
114     // floor(log(upperBound / size));
115     return folly::findLastSet(upperBound / size) - 1;
116   }
117
118   // Requires: input range (begin, end) is sorted (encoding
119   // crashes if it's not).
120   // WARNING: encode() mallocates EliasFanoCompressedList::data. As
121   // EliasFanoCompressedList has no ownership of it, you need to call
122   // free() explicitly.
123   template <class RandomAccessIterator>
124   static MutableCompressedList encode(RandomAccessIterator begin,
125                                       RandomAccessIterator end) {
126     if (begin == end) {
127       return MutableCompressedList();
128     }
129     EliasFanoEncoderV2 encoder(end - begin, *(end - 1));
130     for (; begin != end; ++begin) {
131       encoder.add(*begin);
132     }
133     return encoder.finish();
134   }
135
136   explicit EliasFanoEncoderV2(const MutableCompressedList& result)
137       : lower_(result.lower),
138         upper_(result.upper),
139         skipPointers_(reinterpret_cast<SkipValueType*>(
140               result.skipPointers)),
141         forwardPointers_(reinterpret_cast<SkipValueType*>(
142               result.forwardPointers)),
143         result_(result) {
144     memset(result.data.data(), 0, result.data.size());
145   }
146
147   EliasFanoEncoderV2(size_t size, ValueType upperBound)
148       : EliasFanoEncoderV2(
149             Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
150
151   void add(ValueType value) {
152     CHECK_LT(value, std::numeric_limits<ValueType>::max());
153     CHECK_GE(value, lastValue_);
154
155     const auto numLowerBits = result_.numLowerBits;
156     const ValueType upperBits = value >> numLowerBits;
157
158     // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
159     const size_t pos = upperBits + size_;
160     upper_[pos / 8] |= 1U << (pos % 8);
161     // Append numLowerBits bits to lower sequence.
162     if (numLowerBits != 0) {
163       const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
164       writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
165     }
166
167     /* static */ if (skipQuantum != 0) {
168       while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
169         // Store the number of preceding 1-bits.
170         skipPointers_[skipPointersSize_++] = size_;
171       }
172     }
173
174     /* static */ if (forwardQuantum != 0) {
175       if ((size_ + 1) % forwardQuantum == 0) {
176         const auto pos = size_ / forwardQuantum;
177         // Store the number of preceding 0-bits.
178         forwardPointers_[pos] = upperBits;
179       }
180     }
181
182     lastValue_ = value;
183     ++size_;
184   }
185
186   const MutableCompressedList& finish() const {
187     CHECK_EQ(size_, result_.size);
188     return result_;
189   }
190
191  private:
192   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
193   static void writeBits56(unsigned char* data, size_t pos,
194                           uint8_t len, uint64_t value) {
195     DCHECK_LE(uint32_t(len), 56);
196     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
197     unsigned char* const ptr = data + (pos / 8);
198     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
199     ptrv |= value << (pos % 8);
200     folly::storeUnaligned<uint64_t>(ptr, ptrv);
201   }
202
203   unsigned char* lower_ = nullptr;
204   unsigned char* upper_ = nullptr;
205   SkipValueType* skipPointers_ = nullptr;
206   SkipValueType* forwardPointers_ = nullptr;
207
208   ValueType lastValue_ = 0;
209   size_t size_ = 0;
210   size_t skipPointersSize_ = 0;
211
212   MutableCompressedList result_;
213 };
214
215 template <class Value,
216           class SkipValue,
217           size_t kSkipQuantum,
218           size_t kForwardQuantum>
219 struct EliasFanoEncoderV2<Value,
220                           SkipValue,
221                           kSkipQuantum,
222                           kForwardQuantum>::Layout {
223   static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
224     // numLowerBits can be at most 56 because of detail::writeBits56.
225     const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
226                                                               size),
227                                           uint8_t(56));
228     // *** Upper bits.
229     // Upper bits are stored using unary delta encoding.
230     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
231     const size_t upperSizeBits =
232       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
233       size;                           // 1-bits.
234     const size_t upper = (upperSizeBits + 7) / 8;
235
236     // *** Validity checks.
237     // Shift by numLowerBits must be valid.
238     CHECK_LT(numLowerBits, 8 * sizeof(Value));
239     CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
240     CHECK_LT(upperBound >> numLowerBits,
241              std::numeric_limits<SkipValueType>::max());
242
243     return fromInternalSizes(numLowerBits, upper, size);
244   }
245
246   static Layout fromInternalSizes(uint8_t numLowerBits,
247                                   size_t upper,
248                                   size_t size) {
249     Layout layout;
250     layout.size = size;
251     layout.numLowerBits = numLowerBits;
252
253     layout.lower = (numLowerBits * size + 7) / 8;
254     layout.upper = upper;
255
256     // *** Skip pointers.
257     // Store (1-indexed) position of every skipQuantum-th
258     // 0-bit in upper bits sequence.
259     /* static */ if (skipQuantum != 0) {
260       // 8 * upper is used here instead of upperSizeBits, as that is
261       // more serialization-friendly way (upperSizeBits doesn't need
262       // to be known by this function, unlike upper).
263
264       // '?: 1' is a workaround for false 'division by zero'
265       // compile-time error.
266       size_t numSkipPointers = (8 * upper - size) / (skipQuantum ?: 1);
267       layout.skipPointers = numSkipPointers * sizeof(SkipValueType);
268     }
269
270     // *** Forward pointers.
271     // Store (1-indexed) position of every forwardQuantum-th
272     // 1-bit in upper bits sequence.
273     /* static */ if (forwardQuantum != 0) {
274       size_t numForwardPointers = size / (forwardQuantum ?: 1);
275       layout.forwardPointers = numForwardPointers * sizeof(SkipValueType);
276     }
277
278     return layout;
279   }
280
281   size_t bytes() const {
282     return lower + upper + skipPointers + forwardPointers;
283   }
284
285   template <class Range>
286   EliasFanoCompressedListBase<typename Range::iterator>
287   openList(Range& buf) const {
288     EliasFanoCompressedListBase<typename Range::iterator> result;
289     result.size = size;
290     result.numLowerBits = numLowerBits;
291     result.data = buf.subpiece(0, bytes());
292
293     auto advance = [&] (size_t n) {
294       auto begin = buf.data();
295       buf.advance(n);
296       return begin;
297     };
298
299     result.skipPointers = advance(skipPointers);
300     result.forwardPointers = advance(forwardPointers);
301     result.lower = advance(lower);
302     result.upper = advance(upper);
303
304     return result;
305   }
306
307   MutableCompressedList allocList() const {
308     uint8_t* buf = nullptr;
309     // WARNING: Current read/write logic assumes that the 7 bytes
310     // following the last byte of lower and upper sequences are
311     // readable (stored value doesn't matter and won't be changed), so
312     // we allocate additional 7 bytes, but do not include them in size
313     // of returned value.
314     if (size > 0) {
315       buf = static_cast<uint8_t*>(malloc(bytes() + 7));
316     }
317     folly::MutableByteRange bufRange(buf, bytes());
318     return openList(bufRange);
319   }
320
321   size_t size = 0;
322   uint8_t numLowerBits = 0;
323
324   // Sizes in bytes.
325   size_t lower = 0;
326   size_t upper = 0;
327   size_t skipPointers = 0;
328   size_t forwardPointers = 0;
329 };
330
331 namespace detail {
332
333 template <class Encoder, class Instructions>
334 class UpperBitsReader {
335   typedef typename Encoder::SkipValueType SkipValueType;
336  public:
337   typedef typename Encoder::ValueType ValueType;
338
339   explicit UpperBitsReader(const typename Encoder::CompressedList& list)
340       : forwardPointers_(list.forwardPointers),
341         skipPointers_(list.skipPointers),
342         start_(list.upper) {
343     reset();
344   }
345
346   void reset() {
347     block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
348     outer_ = 0;
349     inner_ = -1;
350     position_ = -1;
351     value_ = 0;
352   }
353
354   size_t position() const { return position_; }
355   ValueType value() const { return value_; }
356
357   ValueType next() {
358     // Skip to the first non-zero block.
359     while (block_ == 0) {
360       outer_ += sizeof(block_t);
361       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
362     }
363
364     ++position_;
365     inner_ = Instructions::ctz(block_);
366     block_ = Instructions::blsr(block_);
367
368     return setValue();
369   }
370
371   ValueType skip(size_t n) {
372     DCHECK_GT(n, 0);
373
374     position_ += n;  // n 1-bits will be read.
375
376     // Use forward pointer.
377     if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
378       // Workaround to avoid 'division by zero' compile-time error.
379       constexpr size_t q = Encoder::forwardQuantum ?: 1;
380
381       const size_t steps = position_ / q;
382       const size_t dest =
383         folly::loadUnaligned<SkipValueType>(
384             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
385
386       reposition(dest + steps * q);
387       n = position_ + 1 - steps * q;  // n is > 0.
388       // Correct inner_ will be set at the end.
389     }
390
391     size_t cnt;
392     // Find necessary block.
393     while ((cnt = Instructions::popcount(block_)) < n) {
394       n -= cnt;
395       outer_ += sizeof(block_t);
396       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
397     }
398
399     // Skip to the n-th one in the block.
400     DCHECK_GT(n, 0);
401     inner_ = select64<Instructions>(block_, n - 1);
402     block_ &= (block_t(-1) << inner_) << 1;
403
404     return setValue();
405   }
406
407   // Skip to the first element that is >= v and located *after* the current
408   // one (so even if current value equals v, position will be increased by 1).
409   ValueType skipToNext(ValueType v) {
410     DCHECK_GE(v, value_);
411
412     // Use skip pointer.
413     if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
414       // Workaround to avoid 'division by zero' compile-time error.
415       constexpr size_t q = Encoder::skipQuantum ?: 1;
416
417       const size_t steps = v / q;
418       const size_t dest =
419         folly::loadUnaligned<SkipValueType>(
420             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
421
422       reposition(dest + q * steps);
423       position_ = dest - 1;
424
425       // Correct inner_ and value_ will be set during the next()
426       // call at the end.
427
428       // NOTE: Corresponding block of lower bits sequence may be
429       // prefetched here (via __builtin_prefetch), but experiments
430       // didn't show any significant improvements.
431     }
432
433     // Skip by blocks.
434     size_t cnt;
435     size_t skip = v - (8 * outer_ - position_ - 1);
436
437     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
438     while ((cnt = Instructions::popcount(~block_)) < skip) {
439       skip -= cnt;
440       position_ += kBitsPerBlock - cnt;
441       outer_ += sizeof(block_t);
442       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
443     }
444
445     if (LIKELY(skip)) {
446       auto inner = select64<Instructions>(~block_, skip - 1);
447       position_ += inner - skip + 1;
448       block_ &= block_t(-1) << inner;
449     }
450
451     next();
452     return value_;
453   }
454
455   ValueType jump(size_t n) {
456     if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
457       reset();
458     } else {
459       position_ = -1;  // Avoid reading the head, skip() will reposition.
460     }
461     return skip(n);
462   }
463
464   ValueType jumpToNext(ValueType v) {
465     if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
466       reset();
467     } else {
468       value_ = 0;  // Avoid reading the head, skipToNext() will reposition.
469     }
470     return skipToNext(v);
471   }
472
473   ValueType previousValue() const {
474     DCHECK_NE(position(), -1);
475     DCHECK_GT(position(), 0);
476
477     size_t outer = outer_;
478     block_t block = folly::loadUnaligned<block_t>(start_ + outer);
479     block &= (block_t(1) << inner_) - 1;
480
481     while (UNLIKELY(block == 0)) {
482       DCHECK_GE(outer, sizeof(block_t));
483       outer -= sizeof(block_t);
484       block = folly::loadUnaligned<block_t>(start_ + outer);
485     }
486
487     auto inner = 8 * sizeof(block_t) - 1 - Instructions::clz(block);
488     return static_cast<ValueType>(8 * outer + inner - (position_ - 1));
489   }
490
491   void setDone(size_t endPos) {
492     position_ = endPos;
493   }
494
495  private:
496   ValueType setValue() {
497     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
498     return value_;
499   }
500
501   void reposition(size_t dest) {
502     outer_ = dest / 8;
503     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
504     block_ &= ~((block_t(1) << (dest % 8)) - 1);
505   }
506
507   typedef uint64_t block_t;
508   const unsigned char* const forwardPointers_;
509   const unsigned char* const skipPointers_;
510   const unsigned char* const start_;
511   block_t block_;
512   size_t outer_;  // Outer offset: number of consumed bytes in upper.
513   size_t inner_;  // Inner offset: (bit) position in current block.
514   size_t position_;  // Index of current value (= #reads - 1).
515   ValueType value_;
516 };
517
518 }  // namespace detail
519
520 // If kUnchecked = true the caller must guarantee that all the
521 // operations return valid elements, i.e., they would never return
522 // false if checked.
523 template <class Encoder,
524           class Instructions = instructions::Default,
525           bool kUnchecked = false>
526 class EliasFanoReader {
527  public:
528   typedef Encoder EncoderType;
529   typedef typename Encoder::ValueType ValueType;
530
531   explicit EliasFanoReader(const typename Encoder::CompressedList& list)
532       : size_(list.size),
533         lower_(list.lower),
534         upper_(list),
535         lowerMask_((ValueType(1) << list.numLowerBits) - 1),
536         numLowerBits_(list.numLowerBits) {
537     DCHECK(Instructions::supported());
538     // To avoid extra branching during skipTo() while reading
539     // upper sequence we need to know the last element.
540     // If kUnchecked == true, we do not check that skipTo() is called
541     // within the bounds, so we can avoid initializing lastValue_.
542     if (kUnchecked || UNLIKELY(list.size == 0)) {
543       lastValue_ = 0;
544       return;
545     }
546     ValueType lastUpperValue = 8 * list.upperSize() - size_;
547     auto it = list.upper + list.upperSize() - 1;
548     DCHECK_NE(*it, 0);
549     lastUpperValue -= 8 - folly::findLastSet(*it);
550     lastValue_ = readLowerPart(size_ - 1) | (lastUpperValue << numLowerBits_);
551   }
552
553   void reset() {
554     upper_.reset();
555     value_ = kInvalidValue;
556   }
557
558   bool next() {
559     if (!kUnchecked && UNLIKELY(position() + 1 >= size_)) {
560       return setDone();
561     }
562     upper_.next();
563     value_ = readLowerPart(upper_.position()) |
564              (upper_.value() << numLowerBits_);
565     return true;
566   }
567
568   bool skip(size_t n) {
569     CHECK_GT(n, 0);
570
571     if (kUnchecked || LIKELY(position() + n < size_)) {
572       if (LIKELY(n < kLinearScanThreshold)) {
573         for (size_t i = 0; i < n; ++i) upper_.next();
574       } else {
575         upper_.skip(n);
576       }
577       value_ = readLowerPart(upper_.position()) |
578         (upper_.value() << numLowerBits_);
579       return true;
580     }
581
582     return setDone();
583   }
584
585   bool skipTo(ValueType value) {
586     // Also works when value_ == kInvalidValue.
587     if (value != kInvalidValue) { DCHECK_GE(value + 1, value_ + 1); }
588
589     if (!kUnchecked && value > lastValue_) {
590       return setDone();
591     } else if (value == value_) {
592       return true;
593     }
594
595     size_t upperValue = (value >> numLowerBits_);
596     size_t upperSkip = upperValue - upper_.value();
597     // The average density of ones in upper bits is 1/2.
598     // LIKELY here seems to make things worse, even for small skips.
599     if (upperSkip < 2 * kLinearScanThreshold) {
600       do {
601         upper_.next();
602       } while (UNLIKELY(upper_.value() < upperValue));
603     } else {
604       upper_.skipToNext(upperValue);
605     }
606
607     iterateTo(value);
608     return true;
609   }
610
611   bool jump(size_t n) {
612     if (LIKELY(n < size_)) {  // Also checks that n != -1.
613       value_ = readLowerPart(n) | (upper_.jump(n + 1) << numLowerBits_);
614       return true;
615     }
616     return setDone();
617   }
618
619   bool jumpTo(ValueType value) {
620     if (!kUnchecked && value > lastValue_) {
621       return setDone();
622     }
623
624     upper_.jumpToNext(value >> numLowerBits_);
625     iterateTo(value);
626     return true;
627   }
628
629   ValueType previousValue() const {
630     DCHECK_GT(position(), 0);
631     DCHECK_LT(position(), size());
632     return readLowerPart(upper_.position() - 1) |
633       (upper_.previousValue() << numLowerBits_);
634   }
635
636   size_t size() const { return size_; }
637
638   bool valid() const {
639     return position() < size(); // Also checks that position() != -1.
640   }
641
642   size_t position() const { return upper_.position(); }
643   ValueType value() const {
644     DCHECK(valid());
645     return value_;
646   }
647
648  private:
649   constexpr static ValueType kInvalidValue =
650     std::numeric_limits<ValueType>::max();  // Must hold kInvalidValue + 1 == 0.
651
652   bool setDone() {
653     value_ = kInvalidValue;
654     upper_.setDone(size_);
655     return false;
656   }
657
658   ValueType readLowerPart(size_t i) const {
659     DCHECK_LT(i, size_);
660     const size_t pos = i * numLowerBits_;
661     const unsigned char* ptr = lower_ + (pos / 8);
662     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
663     return lowerMask_ & (ptrv >> (pos % 8));
664   }
665
666   void iterateTo(ValueType value) {
667     while (true) {
668       value_ = readLowerPart(upper_.position()) |
669         (upper_.value() << numLowerBits_);
670       if (LIKELY(value_ >= value)) break;
671       upper_.next();
672     }
673   }
674
675   constexpr static size_t kLinearScanThreshold = 8;
676
677   size_t size_;
678   const uint8_t* lower_;
679   detail::UpperBitsReader<Encoder, Instructions> upper_;
680   const ValueType lowerMask_;
681   ValueType value_ = kInvalidValue;
682   ValueType lastValue_;
683   uint8_t numLowerBits_;
684 };
685
686 }}  // namespaces
687
688 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H