Fix #includes
[folly.git] / folly / experimental / EliasFanoCoding.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * @author Philip Pronin (philipp@fb.com)
19  *
20  * Based on the paper by Sebastiano Vigna,
21  * "Quasi-succinct indices" (arxiv:1206.4300).
22  */
23
24 #ifndef FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
25 #define FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
26
27 #ifndef __GNUC__
28 #error EliasFanoCoding.h requires GCC
29 #endif
30
31 #if !FOLLY_X64
32 #error EliasFanoCoding.h requires x86_64
33 #endif
34
35 #include <cstdlib>
36 #include <limits>
37 #include <type_traits>
38 #include <boost/noncopyable.hpp>
39 #include <glog/logging.h>
40
41 #include <folly/Bits.h>
42 #include <folly/CpuId.h>
43 #include <folly/Likely.h>
44 #include <folly/Range.h>
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 struct EliasFanoCompressedList {
53   EliasFanoCompressedList() { }
54
55   void free() {
56     ::free(const_cast<unsigned char*>(lower.data()));
57     ::free(const_cast<unsigned char*>(upper.data()));
58     ::free(const_cast<unsigned char*>(skipPointers.data()));
59     ::free(const_cast<unsigned char*>(forwardPointers.data()));
60   }
61
62   size_t size = 0;
63   uint8_t numLowerBits = 0;
64
65   // WARNING: EliasFanoCompressedList has no ownership of
66   // lower, upper, skipPointers and forwardPointers.
67   // The 7 bytes following the last byte of lower and upper
68   // sequences should be readable.
69   folly::ByteRange lower;
70   folly::ByteRange upper;
71
72   folly::ByteRange skipPointers;
73   folly::ByteRange forwardPointers;
74 };
75
76 // Version history:
77 // In version 1 skip / forward pointers encoding has been changed,
78 // so SkipValue = uint32_t is able to address up to ~4B elements,
79 // instead of only ~2B.
80 template <class Value,
81           class SkipValue = size_t,
82           size_t kSkipQuantum = 0,     // 0 = disabled
83           size_t kForwardQuantum = 0,  // 0 = disabled
84           size_t kVersion = 0>
85 struct EliasFanoEncoder {
86   static_assert(std::is_integral<Value>::value &&
87                 std::is_unsigned<Value>::value,
88                 "Value should be unsigned integral");
89
90   typedef EliasFanoCompressedList CompressedList;
91
92   typedef Value ValueType;
93   typedef SkipValue SkipValueType;
94
95   static constexpr size_t skipQuantum = kSkipQuantum;
96   static constexpr size_t forwardQuantum = kForwardQuantum;
97   static constexpr size_t version = kVersion;
98
99   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
100     if (size == 0 || upperBound < size) {
101       return 0;
102     }
103     // floor(log(upperBound / size));
104     return folly::findLastSet(upperBound / size) - 1;
105   }
106
107   // Requires: input range (begin, end) is sorted (encoding
108   // crashes if it's not).
109   // WARNING: encode() mallocates lower, upper, skipPointers
110   // and forwardPointers. As EliasFanoCompressedList has
111   // no ownership of them, you need to call free() explicitly.
112   template <class RandomAccessIterator>
113   static EliasFanoCompressedList encode(RandomAccessIterator begin,
114                                         RandomAccessIterator end) {
115     if (begin == end) {
116       return EliasFanoCompressedList();
117     }
118     EliasFanoEncoder encoder(end - begin, *(end - 1));
119     for (; begin != end; ++begin) {
120       encoder.add(*begin);
121     }
122     return encoder.finish();
123   }
124
125   EliasFanoEncoder(size_t size, ValueType upperBound) {
126     if (size == 0) {
127       return;
128     }
129
130     uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
131
132     // This is detail::writeBits56 limitation.
133     numLowerBits = std::min<uint8_t>(numLowerBits, 56);
134     CHECK_LT(numLowerBits, 8 * sizeof(Value));  // As we shift by numLowerBits.
135
136     // WARNING: Current read/write logic assumes that the 7 bytes
137     // following the last byte of lower and upper sequences are
138     // readable (stored value doesn't matter and won't be changed),
139     // so we allocate additional 7B, but do not include them in size
140     // of returned value.
141
142     // *** Lower bits.
143     const size_t lowerSize = (numLowerBits * size + 7) / 8;
144     if (lowerSize > 0) {  // numLowerBits != 0
145       lower_ = static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
146     }
147
148     // *** Upper bits.
149     // Upper bits are stored using unary delta encoding.
150     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
151     const size_t upperSizeBits =
152       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
153       size;                           // 1-bits.
154     const size_t upperSize = (upperSizeBits + 7) / 8;
155     upper_ = static_cast<unsigned char*>(calloc(upperSize + 7, 1));
156
157     // *** Skip pointers.
158     // Store (1-indexed) position of every skipQuantum-th
159     // 0-bit in upper bits sequence.
160     size_t numSkipPointers = 0;
161     /* static */ if (skipQuantum != 0) {
162       /* static */ if (kVersion > 0) {
163         CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
164       } else {
165         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
166       }
167       // 8 * upperSize is used here instead of upperSizeBits, as that is
168       // more serialization-friendly way (upperSizeBits isn't known outside of
169       // this function, unlike upperSize; thus numSkipPointers could easily be
170       // deduced from upperSize).
171       numSkipPointers = (8 * upperSize - size) / (skipQuantum ?: 1);
172       skipPointers_ = static_cast<SkipValueType*>(
173           numSkipPointers == 0
174             ? nullptr
175             : calloc(numSkipPointers, sizeof(SkipValueType)));
176     }
177
178     // *** Forward pointers.
179     // Store (1-indexed) position of every forwardQuantum-th
180     // 1-bit in upper bits sequence.
181     size_t numForwardPointers = 0;
182     /* static */ if (forwardQuantum != 0) {
183       /* static */ if (kVersion > 0) {
184         CHECK_LT(upperBound >> numLowerBits,
185                  std::numeric_limits<SkipValueType>::max());
186       } else {
187         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
188       }
189
190       // '?: 1' is a workaround for false 'division by zero' compile-time error.
191       numForwardPointers = size / (forwardQuantum ?: 1);
192       forwardPointers_ = static_cast<SkipValueType*>(
193         numForwardPointers == 0
194           ? nullptr
195           : malloc(numForwardPointers * sizeof(SkipValueType)));
196     }
197
198     // *** Result.
199     result_.size = size;
200     result_.numLowerBits = numLowerBits;
201     result_.lower.reset(lower_, lowerSize);
202     result_.upper.reset(upper_, upperSize);
203     result_.skipPointers.reset(
204         reinterpret_cast<unsigned char*>(skipPointers_),
205         numSkipPointers * sizeof(SkipValueType));
206     result_.forwardPointers.reset(
207         reinterpret_cast<unsigned char*>(forwardPointers_),
208         numForwardPointers * sizeof(SkipValueType));
209   }
210
211   void add(ValueType value) {
212     CHECK_GE(value, lastValue_);
213
214     const auto numLowerBits = result_.numLowerBits;
215     const ValueType upperBits = value >> numLowerBits;
216
217     // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
218     const size_t pos = upperBits + size_;
219     upper_[pos / 8] |= 1U << (pos % 8);
220     // Append numLowerBits bits to lower sequence.
221     if (numLowerBits != 0) {
222       const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
223       writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
224     }
225
226     /* static */ if (skipQuantum != 0) {
227       while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
228         /* static */ if (kVersion > 0) {
229           // Since version 1, just the number of preceding 1-bits is stored.
230           skipPointers_[skipPointersSize_] = size_;
231         } else {
232           skipPointers_[skipPointersSize_] =
233             size_ + (skipPointersSize_ + 1) * skipQuantum;
234         }
235         ++skipPointersSize_;
236       }
237     }
238
239     /* static */ if (forwardQuantum != 0) {
240       if ((size_ + 1) % forwardQuantum == 0) {
241         const auto pos = size_ / forwardQuantum;
242         /* static */ if (kVersion > 0) {
243           // Since version 1, just the number of preceding 0-bits is stored.
244           forwardPointers_[pos] = upperBits;
245         } else {
246           forwardPointers_[pos] = upperBits + size_ + 1;
247         }
248       }
249     }
250
251     lastValue_ = value;
252     ++size_;
253   }
254
255   const EliasFanoCompressedList& finish() const {
256     CHECK_EQ(size_, result_.size);
257     return result_;
258   }
259
260  private:
261   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
262   static void writeBits56(unsigned char* data, size_t pos,
263                           uint8_t len, uint64_t value) {
264     DCHECK_LE(uint32_t(len), 56);
265     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
266     unsigned char* const ptr = data + (pos / 8);
267     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
268     ptrv |= value << (pos % 8);
269     folly::storeUnaligned<uint64_t>(ptr, ptrv);
270   }
271
272   unsigned char* lower_ = nullptr;
273   unsigned char* upper_ = nullptr;
274   SkipValueType* skipPointers_ = nullptr;
275   SkipValueType* forwardPointers_ = nullptr;
276
277   ValueType lastValue_ = 0;
278   size_t size_ = 0;
279   size_t skipPointersSize_ = 0;
280
281   EliasFanoCompressedList result_;
282 };
283
284 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
285 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
286 // it for __builtin_popcountll intrinsic.
287 // But we provide an alternative way for the client code: it can switch to
288 // the appropriate version of EliasFanoReader<> in realtime (client should
289 // implement this switching logic itself) by specifying instruction set to
290 // use explicitly.
291 namespace instructions {
292
293 struct Default {
294   static bool supported() {
295     return true;
296   }
297   static inline uint64_t popcount(uint64_t value) {
298     return __builtin_popcountll(value);
299   }
300   static inline int ctz(uint64_t value) {
301     DCHECK_GT(value, 0);
302     return __builtin_ctzll(value);
303   }
304 };
305
306 struct Fast : public Default {
307   static bool supported() {
308     folly::CpuId cpuId;
309     return cpuId.popcnt();
310   }
311   static inline uint64_t popcount(uint64_t value) {
312     uint64_t result;
313     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
314     return result;
315   }
316 };
317
318 }  // namespace instructions
319
320 namespace detail {
321
322 template <class Encoder, class Instructions>
323 class UpperBitsReader {
324   typedef typename Encoder::SkipValueType SkipValueType;
325  public:
326   typedef typename Encoder::ValueType ValueType;
327
328   explicit UpperBitsReader(const EliasFanoCompressedList& list)
329     : forwardPointers_(list.forwardPointers.data()),
330       skipPointers_(list.skipPointers.data()),
331       start_(list.upper.data()) {
332     reset();
333   }
334
335   void reset() {
336     block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
337     outer_ = 0;
338     inner_ = -1;
339     position_ = -1;
340     value_ = 0;
341   }
342
343   size_t position() const { return position_; }
344   ValueType value() const { return value_; }
345
346   ValueType next() {
347     // Skip to the first non-zero block.
348     while (block_ == 0) {
349       outer_ += sizeof(block_t);
350       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
351     }
352
353     ++position_;
354     inner_ = Instructions::ctz(block_);
355     block_ &= block_ - 1;
356
357     return setValue();
358   }
359
360   ValueType skip(size_t n) {
361     DCHECK_GT(n, 0);
362
363     position_ += n;  // n 1-bits will be read.
364
365     // Use forward pointer.
366     if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
367       // Workaround to avoid 'division by zero' compile-time error.
368       constexpr size_t q = Encoder::forwardQuantum ?: 1;
369
370       const size_t steps = position_ / q;
371       const size_t dest =
372         folly::loadUnaligned<SkipValueType>(
373             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
374
375       /* static */ if (Encoder::version > 0) {
376         reposition(dest + steps * q);
377       } else {
378         reposition(dest);
379       }
380       n = position_ + 1 - steps * q;  // n is > 0.
381       // correct inner_ will be set at the end.
382     }
383
384     size_t cnt;
385     // Find necessary block.
386     while ((cnt = Instructions::popcount(block_)) < n) {
387       n -= cnt;
388       outer_ += sizeof(block_t);
389       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
390     }
391
392     // NOTE: Trying to skip half-block here didn't show any
393     // performance improvements.
394
395     DCHECK_GT(n, 0);
396
397     // Kill n - 1 least significant 1-bits.
398     for (size_t i = 0; i < n - 1; ++i) {
399       block_ &= block_ - 1;
400     }
401
402     inner_ = Instructions::ctz(block_);
403     block_ &= block_ - 1;
404
405     return setValue();
406   }
407
408   // Skip to the first element that is >= v and located *after* the current
409   // one (so even if current value equals v, position will be increased by 1).
410   ValueType skipToNext(ValueType v) {
411     DCHECK_GE(v, value_);
412
413     // Use skip pointer.
414     if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
415       // Workaround to avoid 'division by zero' compile-time error.
416       constexpr size_t q = Encoder::skipQuantum ?: 1;
417
418       const size_t steps = v / q;
419       const size_t dest =
420         folly::loadUnaligned<SkipValueType>(
421             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
422
423       /* static */ if (Encoder::version > 0) {
424         reposition(dest + q * steps);
425         position_ = dest - 1;
426       } else {
427         reposition(dest);
428         position_ = dest - q * steps - 1;
429       }
430       // Correct inner_ and value_ will be set during the next()
431       // call at the end.
432
433       // NOTE: Corresponding block of lower bits sequence may be
434       // prefetched here (via __builtin_prefetch), but experiments
435       // didn't show any significant improvements.
436     }
437
438     // Skip by blocks.
439     size_t cnt;
440     size_t skip = v - (8 * outer_ - position_ - 1);
441
442     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
443     while ((cnt = Instructions::popcount(~block_)) < skip) {
444       skip -= cnt;
445       position_ += kBitsPerBlock - cnt;
446       outer_ += sizeof(block_t);
447       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
448     }
449
450     // Try to skip half-block.
451     constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
452     constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
453     if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
454       position_ += kBitsPerHalfBlock - cnt;
455       block_ &= ~halfBlockMask;
456     }
457
458     // Just skip until we see expected value.
459     while (next() < v) { }
460     return value_;
461   }
462
463   ValueType jump(size_t n) {
464     if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
465       reset();
466     } else {
467       position_ = -1;  // Avoid reading the head, skip() will reposition.
468     }
469     return skip(n);
470   }
471
472   ValueType jumpToNext(ValueType v) {
473     if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
474       reset();
475     } else {
476       value_ = 0;  // Avoid reading the head, skipToNext() will reposition.
477     }
478     return skipToNext(v);
479   }
480
481  private:
482   ValueType setValue() {
483     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
484     return value_;
485   }
486
487   void reposition(size_t dest) {
488     outer_ = dest / 8;
489     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
490     block_ &= ~((block_t(1) << (dest % 8)) - 1);
491   }
492
493   typedef unsigned long long block_t;
494   const unsigned char* const forwardPointers_;
495   const unsigned char* const skipPointers_;
496   const unsigned char* const start_;
497   block_t block_;
498   size_t outer_;  // Outer offset: number of consumed bytes in upper.
499   size_t inner_;  // Inner offset: (bit) position in current block.
500   size_t position_;  // Index of current value (= #reads - 1).
501   ValueType value_;
502 };
503
504 }  // namespace detail
505
506 template <class Encoder,
507           class Instructions = instructions::Default>
508 class EliasFanoReader : private boost::noncopyable {
509  public:
510   typedef Encoder EncoderType;
511   typedef typename Encoder::ValueType ValueType;
512
513   explicit EliasFanoReader(const EliasFanoCompressedList& list)
514     : list_(list),
515       lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
516       upper_(list_) {
517     DCHECK(Instructions::supported());
518     // To avoid extra branching during skipTo() while reading
519     // upper sequence we need to know the last element.
520     if (UNLIKELY(list_.size == 0)) {
521       lastValue_ = 0;
522       return;
523     }
524     ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
525     auto it = list_.upper.end() - 1;
526     DCHECK_NE(*it, 0);
527     lastUpperValue -= 8 - folly::findLastSet(*it);
528     lastValue_ = readLowerPart(list_.size - 1) |
529                  (lastUpperValue << list_.numLowerBits);
530   }
531
532   void reset() {
533     upper_.reset();
534     progress_ = 0;
535     value_ = 0;
536   }
537
538   bool next() {
539     if (UNLIKELY(progress_ == list_.size)) {
540       value_ = std::numeric_limits<ValueType>::max();
541       return false;
542     }
543     value_ = readLowerPart(progress_) |
544              (upper_.next() << list_.numLowerBits);
545     ++progress_;
546     return true;
547   }
548
549   bool skip(size_t n) {
550     CHECK_GT(n, 0);
551
552     progress_ += n;
553     if (LIKELY(progress_ <= list_.size)) {
554       value_ = readLowerPart(progress_ - 1) |
555                (upper_.skip(n) << list_.numLowerBits);
556       return true;
557     }
558
559     progress_ = list_.size;
560     value_ = std::numeric_limits<ValueType>::max();
561     return false;
562   }
563
564   bool skipTo(ValueType value) {
565     DCHECK_GE(value, value_);
566     if (value <= value_) {
567       return true;
568     } else if (value > lastValue_) {
569       progress_ = list_.size;
570       value_ = std::numeric_limits<ValueType>::max();
571       return false;
572     }
573
574     upper_.skipToNext(value >> list_.numLowerBits);
575     iterateTo(value);
576     return true;
577   }
578
579   bool jump(size_t n) {
580     if (LIKELY(n - 1 < list_.size)) {  // n > 0 && n <= list_.size
581       progress_ = n;
582       value_ = readLowerPart(n - 1) | (upper_.jump(n) << list_.numLowerBits);
583       return true;
584     } else if (n == 0) {
585       reset();
586       return true;
587     }
588     progress_ = list_.size;
589     value_ = std::numeric_limits<ValueType>::max();
590     return false;
591   }
592
593   ValueType jumpTo(ValueType value) {
594     if (value <= 0) {
595       reset();
596       return true;
597     } else if (value > lastValue_) {
598       progress_ = list_.size;
599       value_ = std::numeric_limits<ValueType>::max();
600       return false;
601     }
602
603     upper_.jumpToNext(value >> list_.numLowerBits);
604     iterateTo(value);
605     return true;
606   }
607
608   size_t size() const { return list_.size; }
609
610   size_t position() const { return progress_ - 1; }
611   ValueType value() const { return value_; }
612
613  private:
614   ValueType readLowerPart(size_t i) const {
615     DCHECK_LT(i, list_.size);
616     const size_t pos = i * list_.numLowerBits;
617     const unsigned char* ptr = list_.lower.data() + (pos / 8);
618     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
619     return lowerMask_ & (ptrv >> (pos % 8));
620   }
621
622   void iterateTo(ValueType value) {
623     progress_ = upper_.position();
624     value_ = readLowerPart(progress_) | (upper_.value() << list_.numLowerBits);
625     ++progress_;
626     while (value_ < value) {
627       value_ = readLowerPart(progress_) | (upper_.next() << list_.numLowerBits);
628       ++progress_;
629     }
630   }
631
632   const EliasFanoCompressedList list_;
633   const ValueType lowerMask_;
634   detail::UpperBitsReader<Encoder, Instructions> upper_;
635   size_t progress_ = 0;
636   ValueType value_ = 0;
637   ValueType lastValue_;
638 };
639
640 }}  // namespaces
641
642 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H