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