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