Fix a corner case in EliasFanoReader::previousValue
[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/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 #if !FOLLY_X64
40 #error EliasFanoCoding.h requires x86_64
41 #endif
42
43 namespace folly { namespace compression {
44
45 static_assert(kIsLittleEndian, "EliasFanoCoding.h requires little endianness");
46
47 template <class Pointer>
48 struct EliasFanoCompressedListBase {
49   EliasFanoCompressedListBase() = default;
50
51   template <class OtherPointer>
52   EliasFanoCompressedListBase(
53       const EliasFanoCompressedListBase<OtherPointer>& other)
54       : size(other.size),
55         numLowerBits(other.numLowerBits),
56         data(other.data),
57         skipPointers(reinterpret_cast<Pointer>(other.skipPointers)),
58         forwardPointers(reinterpret_cast<Pointer>(other.forwardPointers)),
59         lower(reinterpret_cast<Pointer>(other.lower)),
60         upper(reinterpret_cast<Pointer>(other.upper)) { }
61
62   template <class T = Pointer>
63   auto free() -> decltype(::free(T(nullptr))) {
64     return ::free(data.data());
65   }
66
67   size_t upperSize() const {
68     return size_t(data.end() - upper);
69   }
70
71   size_t size = 0;
72   uint8_t numLowerBits = 0;
73
74   // WARNING: EliasFanoCompressedList has no ownership of data. The 7
75   // bytes following the last byte should be readable.
76   folly::Range<Pointer> data;
77
78   Pointer skipPointers = nullptr;
79   Pointer forwardPointers = nullptr;
80   Pointer lower = nullptr;
81   Pointer upper = nullptr;
82 };
83
84 typedef EliasFanoCompressedListBase<const uint8_t*> EliasFanoCompressedList;
85 typedef EliasFanoCompressedListBase<uint8_t*> MutableEliasFanoCompressedList;
86
87 template <class Value,
88           class SkipValue = size_t,
89           size_t kSkipQuantum = 0,     // 0 = disabled
90           size_t kForwardQuantum = 0>  // 0 = disabled
91 struct EliasFanoEncoderV2 {
92   static_assert(std::is_integral<Value>::value &&
93                     std::is_unsigned<Value>::value,
94                 "Value should be unsigned integral");
95
96   typedef EliasFanoCompressedList CompressedList;
97   typedef MutableEliasFanoCompressedList MutableCompressedList;
98
99   typedef Value ValueType;
100   typedef SkipValue SkipValueType;
101   struct Layout;
102
103   static constexpr size_t skipQuantum = kSkipQuantum;
104   static constexpr size_t forwardQuantum = kForwardQuantum;
105
106   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
107     if (UNLIKELY(size == 0 || upperBound < size)) {
108       return 0;
109     }
110     // Result that should be returned is "floor(log(upperBound / size))".
111     // In order to avoid expensive division, we rely on
112     // "floor(a) - floor(b) - 1 <= floor(a - b) <= floor(a) - floor(b)".
113     // Assuming "candidate = floor(log(upperBound)) - floor(log(upperBound))",
114     // then result is either "candidate - 1" or "candidate".
115     auto candidate = folly::findLastSet(upperBound) - folly::findLastSet(size);
116     // NOTE: As size != 0, "candidate" is always < 64.
117     return (size > (upperBound >> candidate)) ? candidate - 1 : candidate;
118   }
119
120   // Requires: input range (begin, end) is sorted (encoding
121   // crashes if it's not).
122   // WARNING: encode() mallocates EliasFanoCompressedList::data. As
123   // EliasFanoCompressedList has no ownership of it, you need to call
124   // free() explicitly.
125   template <class RandomAccessIterator>
126   static MutableCompressedList encode(RandomAccessIterator begin,
127                                       RandomAccessIterator end) {
128     if (begin == end) {
129       return MutableCompressedList();
130     }
131     EliasFanoEncoderV2 encoder(size_t(end - begin), *(end - 1));
132     for (; begin != end; ++begin) {
133       encoder.add(*begin);
134     }
135     return encoder.finish();
136   }
137
138   explicit EliasFanoEncoderV2(const MutableCompressedList& result)
139       : lower_(result.lower),
140         upper_(result.upper),
141         skipPointers_(reinterpret_cast<SkipValueType*>(
142               result.skipPointers)),
143         forwardPointers_(reinterpret_cast<SkipValueType*>(
144               result.forwardPointers)),
145         result_(result) {
146     std::fill(result.data.begin(), result.data.end(), 0);
147   }
148
149   EliasFanoEncoderV2(size_t size, ValueType upperBound)
150       : EliasFanoEncoderV2(
151             Layout::fromUpperBoundAndSize(upperBound, size).allocList()) { }
152
153   void add(ValueType value) {
154     CHECK_LT(value, std::numeric_limits<ValueType>::max());
155     CHECK_GE(value, lastValue_);
156
157     const auto numLowerBits = result_.numLowerBits;
158     const ValueType upperBits = value >> numLowerBits;
159
160     // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
161     const size_t pos = upperBits + size_;
162     upper_[pos / 8] |= 1U << (pos % 8);
163     // Append numLowerBits bits to lower sequence.
164     if (numLowerBits != 0) {
165       const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
166       writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
167     }
168
169     /* static */ if (skipQuantum != 0) {
170       while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
171         // Store the number of preceding 1-bits.
172         skipPointers_[skipPointersSize_++] = SkipValue(size_);
173       }
174     }
175
176     /* static */ if (forwardQuantum != 0) {
177       if ((size_ + 1) % forwardQuantum == 0) {
178         const auto k = size_ / forwardQuantum;
179         // Store the number of preceding 0-bits.
180         forwardPointers_[k] = upperBits;
181       }
182     }
183
184     lastValue_ = value;
185     ++size_;
186   }
187
188   const MutableCompressedList& finish() const {
189     CHECK_EQ(size_, result_.size);
190     return result_;
191   }
192
193  private:
194   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
195   static void writeBits56(unsigned char* data, size_t pos,
196                           uint8_t len, uint64_t value) {
197     DCHECK_LE(uint32_t(len), 56);
198     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
199     unsigned char* const ptr = data + (pos / 8);
200     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
201     ptrv |= value << (pos % 8);
202     folly::storeUnaligned<uint64_t>(ptr, ptrv);
203   }
204
205   unsigned char* lower_ = nullptr;
206   unsigned char* upper_ = nullptr;
207   SkipValueType* skipPointers_ = nullptr;
208   SkipValueType* forwardPointers_ = nullptr;
209
210   ValueType lastValue_ = 0;
211   size_t size_ = 0;
212   size_t skipPointersSize_ = 0;
213
214   MutableCompressedList result_;
215 };
216
217 template <class Value,
218           class SkipValue,
219           size_t kSkipQuantum,
220           size_t kForwardQuantum>
221 struct EliasFanoEncoderV2<Value,
222                           SkipValue,
223                           kSkipQuantum,
224                           kForwardQuantum>::Layout {
225   static Layout fromUpperBoundAndSize(size_t upperBound, size_t size) {
226     // numLowerBits can be at most 56 because of detail::writeBits56.
227     const uint8_t numLowerBits = std::min(defaultNumLowerBits(upperBound,
228                                                               size),
229                                           uint8_t(56));
230     // *** Upper bits.
231     // Upper bits are stored using unary delta encoding.
232     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
233     const size_t upperSizeBits =
234       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
235       size;                           // 1-bits.
236     const size_t upper = (upperSizeBits + 7) / 8;
237
238     // *** Validity checks.
239     // Shift by numLowerBits must be valid.
240     CHECK_LT(numLowerBits, 8 * sizeof(Value));
241     CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
242     CHECK_LT(upperBound >> numLowerBits,
243              std::numeric_limits<SkipValueType>::max());
244
245     return fromInternalSizes(numLowerBits, upper, size);
246   }
247
248   static Layout fromInternalSizes(uint8_t numLowerBits,
249                                   size_t upper,
250                                   size_t size) {
251     Layout layout;
252     layout.size = size;
253     layout.numLowerBits = numLowerBits;
254
255     layout.lower = (numLowerBits * size + 7) / 8;
256     layout.upper = upper;
257
258     // *** Skip pointers.
259     // Store (1-indexed) position of every skipQuantum-th
260     // 0-bit in upper bits sequence.
261     /* static */ if (skipQuantum != 0) {
262       // 8 * upper is used here instead of upperSizeBits, as that is
263       // more serialization-friendly way (upperSizeBits doesn't need
264       // to be known by this function, unlike upper).
265
266       size_t numSkipPointers = (8 * upper - size) / skipQuantum;
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;
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_ = std::numeric_limits<size_t>::max();
350     position_ = std::numeric_limits<size_t>::max();
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_ = size_t(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       const size_t steps = position_ / Encoder::forwardQuantum;
379       const size_t dest =
380         folly::loadUnaligned<SkipValueType>(
381             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
382
383       reposition(dest + steps * Encoder::forwardQuantum);
384       n = position_ + 1 - steps * Encoder::forwardQuantum; // n is > 0.
385       // Correct inner_ will be set at the end.
386     }
387
388     size_t cnt;
389     // Find necessary block.
390     while ((cnt = Instructions::popcount(block_)) < n) {
391       n -= cnt;
392       outer_ += sizeof(block_t);
393       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
394     }
395
396     // Skip to the n-th one in the block.
397     DCHECK_GT(n, 0);
398     inner_ = select64<Instructions>(block_, n - 1);
399     block_ &= (block_t(-1) << inner_) << 1;
400
401     return setValue();
402   }
403
404   // Skip to the first element that is >= v and located *after* the current
405   // one (so even if current value equals v, position will be increased by 1).
406   ValueType skipToNext(ValueType v) {
407     DCHECK_GE(v, value_);
408
409     // Use skip pointer.
410     if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
411       const size_t steps = v / Encoder::skipQuantum;
412       const size_t dest =
413         folly::loadUnaligned<SkipValueType>(
414             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
415
416       reposition(dest + Encoder::skipQuantum * steps);
417       position_ = dest - 1;
418
419       // Correct inner_ and value_ will be set during the next()
420       // call at the end.
421
422       // NOTE: Corresponding block of lower bits sequence may be
423       // prefetched here (via __builtin_prefetch), but experiments
424       // didn't show any significant improvements.
425     }
426
427     // Skip by blocks.
428     size_t cnt;
429     size_t skip = v - (8 * outer_ - position_ - 1);
430
431     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
432     while ((cnt = Instructions::popcount(~block_)) < skip) {
433       skip -= cnt;
434       position_ += kBitsPerBlock - cnt;
435       outer_ += sizeof(block_t);
436       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
437     }
438
439     if (LIKELY(skip)) {
440       auto inner = select64<Instructions>(~block_, skip - 1);
441       position_ += inner - skip + 1;
442       block_ &= block_t(-1) << inner;
443     }
444
445     next();
446     return value_;
447   }
448
449   ValueType jump(size_t n) {
450     if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
451       reset();
452     } else {
453       position_ = size_t(-1); // Avoid reading the head, skip() will reposition.
454     }
455     return skip(n);
456   }
457
458   ValueType jumpToNext(ValueType v) {
459     if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
460       reset();
461     } else {
462       value_ = 0;  // Avoid reading the head, skipToNext() will reposition.
463     }
464     return skipToNext(v);
465   }
466
467   ValueType previousValue() const {
468     DCHECK_NE(position(), -1);
469     DCHECK_GT(position(), 0);
470
471     size_t outer = outer_;
472     block_t block = folly::loadUnaligned<block_t>(start_ + outer);
473     block &= (block_t(1) << inner_) - 1;
474
475     while (UNLIKELY(block == 0)) {
476       DCHECK_GT(outer, 0);
477       outer -= std::min(sizeof(block_t), outer);
478       block = folly::loadUnaligned<block_t>(start_ + outer);
479     }
480
481     auto inner = 8 * sizeof(block_t) - 1 - Instructions::clz(block);
482     return static_cast<ValueType>(8 * outer + inner - (position_ - 1));
483   }
484
485   void setDone(size_t endPos) {
486     position_ = endPos;
487   }
488
489  private:
490   ValueType setValue() {
491     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
492     return value_;
493   }
494
495   void reposition(size_t dest) {
496     outer_ = dest / 8;
497     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
498     block_ &= ~((block_t(1) << (dest % 8)) - 1);
499   }
500
501   typedef uint64_t block_t;
502   const unsigned char* const forwardPointers_;
503   const unsigned char* const skipPointers_;
504   const unsigned char* const start_;
505   block_t block_;
506   size_t outer_;  // Outer offset: number of consumed bytes in upper.
507   size_t inner_;  // Inner offset: (bit) position in current block.
508   size_t position_;  // Index of current value (= #reads - 1).
509   ValueType value_;
510 };
511
512 }  // namespace detail
513
514 // If kUnchecked = true the caller must guarantee that all the
515 // operations return valid elements, i.e., they would never return
516 // false if checked.
517 template <class Encoder,
518           class Instructions = instructions::Default,
519           bool kUnchecked = false>
520 class EliasFanoReader {
521  public:
522   typedef Encoder EncoderType;
523   typedef typename Encoder::ValueType ValueType;
524
525   explicit EliasFanoReader(const typename Encoder::CompressedList& list)
526       : size_(list.size),
527         lower_(list.lower),
528         upper_(list),
529         lowerMask_((ValueType(1) << list.numLowerBits) - 1),
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     return lowerMask_ & (ptrv >> (pos % 8));
658   }
659
660   void iterateTo(ValueType value) {
661     while (true) {
662       value_ = readLowerPart(upper_.position()) |
663         (upper_.value() << numLowerBits_);
664       if (LIKELY(value_ >= value)) break;
665       upper_.next();
666     }
667   }
668
669   constexpr static size_t kLinearScanThreshold = 8;
670
671   size_t size_;
672   const uint8_t* lower_;
673   detail::UpperBitsReader<Encoder, Instructions> upper_;
674   const ValueType lowerMask_;
675   ValueType value_ = kInvalidValue;
676   ValueType lastValue_;
677   uint8_t numLowerBits_;
678 };
679
680 }}  // namespaces