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