CHECK EliasFanoCompressedList::encode input is sorted
[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 !defined(__x86_64__)
32 #error EliasFanoCoding.h requires x86_64
33 #endif
34
35 #include <cstdlib>
36 #include <algorithm>
37 #include <limits>
38 #include <type_traits>
39 #include <boost/noncopyable.hpp>
40 #include <glog/logging.h>
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 template <class Value,
53           class SkipValue = size_t,
54           size_t kSkipQuantum = 0,     // 0 = disabled
55           size_t kForwardQuantum = 0>  // 0 = disabled
56 struct EliasFanoCompressedList {
57   static_assert(std::is_integral<Value>::value &&
58                 std::is_unsigned<Value>::value,
59                 "Value should be unsigned integral");
60
61   typedef Value ValueType;
62   typedef SkipValue SkipValueType;
63
64   EliasFanoCompressedList()
65     : size(0), numLowerBits(0) { }
66
67   static constexpr size_t skipQuantum = kSkipQuantum;
68   static constexpr size_t forwardQuantum = kForwardQuantum;
69
70   size_t size;
71   uint8_t numLowerBits;
72
73   // WARNING: EliasFanoCompressedList has no ownership of
74   // lower, upper, skipPointers and forwardPointers.
75   // The 7 bytes following the last byte of lower and upper
76   // sequences should be readable.
77   folly::ByteRange lower;
78   folly::ByteRange upper;
79
80   folly::ByteRange skipPointers;
81   folly::ByteRange forwardPointers;
82
83   void free() {
84     ::free(const_cast<unsigned char*>(lower.data()));
85     ::free(const_cast<unsigned char*>(upper.data()));
86     ::free(const_cast<unsigned char*>(skipPointers.data()));
87     ::free(const_cast<unsigned char*>(forwardPointers.data()));
88   }
89
90   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
91     if (size == 0 || upperBound < size) {
92       return 0;
93     }
94     // floor(log(upperBound / size));
95     return folly::findLastSet(upperBound / size) - 1;
96   }
97
98   // WARNING: encode() mallocates lower, upper, skipPointers
99   // and forwardPointers. As EliasFanoCompressedList has
100   // no ownership of them, you need to call free() explicitly.
101   static void encode(const ValueType* list, size_t size,
102                      EliasFanoCompressedList& result) {
103     encode(list, list + size, result);
104   }
105
106   // Range (begin, end) should be sorted.
107   template <class RandomAccessIterator>
108   static void encode(RandomAccessIterator begin,
109                      RandomAccessIterator end,
110                      EliasFanoCompressedList& result) {
111     CHECK(std::is_sorted(begin, end));
112
113     auto list = begin;
114     const size_t size = end - begin;
115
116     if (size == 0) {
117       result = EliasFanoCompressedList();
118       return;
119     }
120
121     const ValueType upperBound = list[size - 1];
122     uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
123
124     // This is detail::writeBits56 limitation.
125     numLowerBits = std::min<uint8_t>(numLowerBits, 56);
126     CHECK_LT(numLowerBits, 8 * sizeof(Value));  // As we shift by numLowerBits.
127
128     // WARNING: Current read/write logic assumes that the 7 bytes
129     // following the last byte of lower and upper sequences are
130     // readable (stored value doesn't matter and won't be changed),
131     // so we allocate additional 7B, but do not include them in size
132     // of returned value.
133
134     // *** Lower bits.
135     const size_t lowerSize = (numLowerBits * size + 7) / 8;
136     unsigned char* lower = nullptr;
137     if (lowerSize > 0) {  // numLowerBits != 0
138       lower = static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
139       const ValueType lowerMask = (ValueType(1) << numLowerBits) - 1;
140       for (size_t i = 0; i < size; ++i) {
141         const ValueType lowerBits = list[i] & lowerMask;
142         writeBits56(lower, i * numLowerBits, numLowerBits, lowerBits);
143       }
144     }
145
146     // *** Upper bits.
147     // Upper bits are stored using unary delta encoding.
148     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
149     const size_t upperSizeBits =
150       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
151       size;                           // 1-bits.
152     const size_t upperSize = (upperSizeBits + 7) / 8;
153     unsigned char* const upper =
154       static_cast<unsigned char*>(calloc(upperSize + 7, 1));
155     for (size_t i = 0; i < size; ++i) {
156       const ValueType upperBits = list[i] >> numLowerBits;
157       const size_t pos = upperBits + i;  // upperBits 0-bits and (i + 1) 1-bits.
158       upper[pos / 8] |= 1U << (pos % 8);
159     }
160
161     // *** Skip pointers.
162     // Store (1-indexed) position of every skipQuantum-th
163     // 0-bit in upper bits sequence.
164     SkipValueType* skipPointers = nullptr;
165     size_t numSkipPointers = 0;
166     /* static */ if (skipQuantum != 0) {
167       // Workaround to avoid 'division by zero' compile-time error.
168       constexpr size_t q = skipQuantum ?: 1;
169       CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
170       // 8 * upperSize is used here instead of upperSizeBits, as that is
171       // more serialization-friendly way.
172       numSkipPointers = (8 * upperSize - size) / q;
173       skipPointers = static_cast<SkipValueType*>(
174           numSkipPointers == 0
175             ? nullptr
176             : calloc(numSkipPointers, sizeof(SkipValueType)));
177
178       for (size_t i = 0, pos = 0; i < size; ++i) {
179         const ValueType upperBits = list[i] >> numLowerBits;
180         for (; (pos + 1) * q <= upperBits; ++pos) {
181           skipPointers[pos] = i + (pos + 1) * q;
182         }
183       }
184     }
185
186     // *** Forward pointers.
187     // Store (1-indexed) position of every forwardQuantum-th
188     // 1-bit in upper bits sequence.
189     SkipValueType* forwardPointers = nullptr;
190     size_t numForwardPointers = 0;
191     /* static */ if (forwardQuantum != 0) {
192       // Workaround to avoid 'division by zero' compile-time error.
193       constexpr size_t q = forwardQuantum ?: 1;
194       CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
195
196       numForwardPointers = size / q;
197       forwardPointers = static_cast<SkipValueType*>(
198         numForwardPointers == 0
199           ? nullptr
200           : malloc(numForwardPointers * sizeof(SkipValueType)));
201
202       for (size_t i = q - 1, pos = 0; i < size; i += q, ++pos) {
203         const ValueType upperBits = list[i] >> numLowerBits;
204         forwardPointers[pos] = upperBits + i + 1;
205       }
206     }
207
208     // *** Result.
209     result.size = size;
210     result.numLowerBits = numLowerBits;
211     result.lower.reset(lower, lowerSize);
212     result.upper.reset(upper, upperSize);
213     result.skipPointers.reset(
214         reinterpret_cast<unsigned char*>(skipPointers),
215         numSkipPointers * sizeof(SkipValueType));
216     result.forwardPointers.reset(
217         reinterpret_cast<unsigned char*>(forwardPointers),
218         numForwardPointers * sizeof(SkipValueType));
219   }
220
221  private:
222   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
223   static void writeBits56(unsigned char* data, size_t pos,
224                           uint8_t len, uint64_t value) {
225     DCHECK_LE(uint32_t(len), 56);
226     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
227     unsigned char* const ptr = data + (pos / 8);
228     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
229     ptrv |=  value << (pos % 8);
230     folly::storeUnaligned<uint64_t>(ptr, ptrv);
231   }
232 };
233
234 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
235 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
236 // it for __builtin_popcountll intrinsic.
237 // But we provide an alternative way for the client code: it can switch to
238 // the appropriate version of EliasFanoReader<> in realtime (client should
239 // implement this switching logic itself) by specifying instruction set to
240 // use explicitly.
241 namespace instructions {
242
243 struct Default {
244   static bool supported() {
245     return true;
246   }
247   static inline uint64_t popcount(uint64_t value) {
248     return __builtin_popcountll(value);
249   }
250   static inline int ctz(uint64_t value) {
251     DCHECK_GT(value, 0);
252     return __builtin_ctzll(value);
253   }
254 };
255
256 struct Fast : public Default {
257   static bool supported() {
258     folly::CpuId cpuId;
259     return cpuId.popcnt();
260   }
261   static inline uint64_t popcount(uint64_t value) {
262     uint64_t result;
263     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
264     return result;
265   }
266 };
267
268 }  // namespace instructions
269
270 namespace detail {
271
272 template <class CompressedList, class Instructions>
273 class UpperBitsReader {
274   typedef typename CompressedList::SkipValueType SkipValueType;
275  public:
276   typedef typename CompressedList::ValueType ValueType;
277
278   explicit UpperBitsReader(const CompressedList& list)
279     : forwardPointers_(list.forwardPointers.data()),
280       skipPointers_(list.skipPointers.data()),
281       start_(list.upper.data()),
282       block_(start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0),
283       outer_(0),  // outer offset: number of consumed bytes in upper.
284       inner_(-1),  // inner offset: (bit) position in current block.
285       position_(-1),  // index of current value (= #reads - 1).
286       value_(0) { }
287
288   size_t position() const { return position_; }
289   ValueType value() const { return value_; }
290
291   ValueType next() {
292     // Skip to the first non-zero block.
293     while (block_ == 0) {
294       outer_ += sizeof(block_t);
295       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
296     }
297
298     ++position_;
299     inner_ = Instructions::ctz(block_);
300     block_ &= block_ - 1;
301
302     return setValue();
303   }
304
305   ValueType skip(size_t n) {
306     DCHECK_GT(n, 0);
307
308     position_ += n;  // n 1-bits will be read.
309
310     // Use forward pointer.
311     if (CompressedList::forwardQuantum > 0 &&
312         n > CompressedList::forwardQuantum) {
313       // Workaround to avoid 'division by zero' compile-time error.
314       constexpr size_t q = CompressedList::forwardQuantum ?: 1;
315
316       const size_t steps = position_ / q;
317       const size_t dest =
318         folly::loadUnaligned<SkipValueType>(
319             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
320
321       reposition(dest);
322       n = position_ + 1 - steps * q;  // n is > 0.
323       // correct inner_ will be set at the end.
324     }
325
326     size_t cnt;
327     // Find necessary block.
328     while ((cnt = Instructions::popcount(block_)) < n) {
329       n -= cnt;
330       outer_ += sizeof(block_t);
331       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
332     }
333
334     // NOTE: Trying to skip half-block here didn't show any
335     // performance improvements.
336
337     DCHECK_GT(n, 0);
338
339     // Kill n - 1 least significant 1-bits.
340     for (size_t i = 0; i < n - 1; ++i) {
341       block_ &= block_ - 1;
342     }
343
344     inner_ = Instructions::ctz(block_);
345     block_ &= block_ - 1;
346
347     return setValue();
348   }
349
350   // Skip to the first element that is >= v and located *after* the current
351   // one (so even if current value equals v, position will be increased by 1).
352   ValueType skipToNext(ValueType v) {
353     DCHECK_GE(v, value_);
354
355     // Use skip pointer.
356     if (CompressedList::skipQuantum > 0 &&
357         v >= value_ + CompressedList::skipQuantum) {
358       // Workaround to avoid 'division by zero' compile-time error.
359       constexpr size_t q = CompressedList::skipQuantum ?: 1;
360
361       const size_t steps = v / q;
362       const size_t dest =
363         folly::loadUnaligned<SkipValueType>(
364             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
365
366       reposition(dest);
367       position_ = dest - q * steps - 1;
368       // Correct inner_ and value_ will be set during the next()
369       // call at the end.
370
371       // NOTE: Corresponding block of lower bits sequence may be
372       // prefetched here (via __builtin_prefetch), but experiments
373       // didn't show any significant improvements.
374     }
375
376     // Skip by blocks.
377     size_t cnt;
378     size_t skip = v - (8 * outer_ - position_ - 1);
379
380     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
381     while ((cnt = Instructions::popcount(~block_)) < skip) {
382       skip -= cnt;
383       position_ += kBitsPerBlock - cnt;
384       outer_ += sizeof(block_t);
385       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
386     }
387
388     // Try to skip half-block.
389     constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
390     constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
391     if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
392       position_ += kBitsPerHalfBlock - cnt;
393       block_ &= ~halfBlockMask;
394     }
395
396     // Just skip until we see expected value.
397     while (next() < v) { }
398     return value_;
399   }
400
401  private:
402   ValueType setValue() {
403     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
404     return value_;
405   }
406
407   void reposition(size_t dest) {
408     outer_ = dest / 8;
409     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
410     block_ &= ~((block_t(1) << (dest % 8)) - 1);
411   }
412
413   typedef unsigned long long block_t;
414   const unsigned char* const forwardPointers_;
415   const unsigned char* const skipPointers_;
416   const unsigned char* const start_;
417   block_t block_;
418   size_t outer_;
419   size_t inner_;
420   size_t position_;
421   ValueType value_;
422 };
423
424 }  // namespace detail
425
426 template <class CompressedList,
427           class Instructions = instructions::Default>
428 class EliasFanoReader : private boost::noncopyable {
429  public:
430   typedef typename CompressedList::ValueType ValueType;
431
432   explicit EliasFanoReader(const CompressedList& list)
433     : list_(list),
434       lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
435       upper_(list),
436       progress_(0),
437       value_(0) {
438     DCHECK(Instructions::supported());
439     // To avoid extra branching during skipTo() while reading
440     // upper sequence we need to know the last element.
441     if (UNLIKELY(list_.size == 0)) {
442       lastValue_ = 0;
443       return;
444     }
445     ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
446     auto it = list_.upper.end() - 1;
447     DCHECK_NE(*it, 0);
448     lastUpperValue -= 8 - folly::findLastSet(*it);
449     lastValue_ = readLowerPart(list_.size - 1) |
450                  (lastUpperValue << list_.numLowerBits);
451   }
452
453   size_t size() const { return list_.size; }
454
455   size_t position() const { return progress_ - 1; }
456   ValueType value() const { return value_; }
457
458   bool next() {
459     if (UNLIKELY(progress_ == list_.size)) {
460       value_ = std::numeric_limits<ValueType>::max();
461       return false;
462     }
463     value_ = readLowerPart(progress_) |
464              (upper_.next() << list_.numLowerBits);
465     ++progress_;
466     return true;
467   }
468
469   bool skip(size_t n) {
470     CHECK_GT(n, 0);
471
472     progress_ += n - 1;
473     if (LIKELY(progress_ < list_.size)) {
474       value_ = readLowerPart(progress_) |
475                (upper_.skip(n) << list_.numLowerBits);
476       ++progress_;
477       return true;
478     }
479
480     progress_ = list_.size;
481     value_ = std::numeric_limits<ValueType>::max();
482     return false;
483   }
484
485   bool skipTo(ValueType value) {
486     DCHECK_GE(value, value_);
487     if (value <= value_) {
488       return true;
489     }
490     if (value > lastValue_) {
491       progress_ = list_.size;
492       value_ = std::numeric_limits<ValueType>::max();
493       return false;
494     }
495
496     upper_.skipToNext(value >> list_.numLowerBits);
497     progress_ = upper_.position();
498     value_ = readLowerPart(progress_) |
499              (upper_.value() << list_.numLowerBits);
500     ++progress_;
501     while (value_ < value) {
502       value_ = readLowerPart(progress_) |
503                (upper_.next() << list_.numLowerBits);
504       ++progress_;
505     }
506
507     return true;
508   }
509
510  private:
511   ValueType readLowerPart(size_t i) const {
512     const size_t pos = i * list_.numLowerBits;
513     const unsigned char* ptr = list_.lower.data() + (pos / 8);
514     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
515     return lowerMask_ & (ptrv >> (pos % 8));
516   }
517
518   const CompressedList list_;
519   const ValueType lowerMask_;
520   detail::UpperBitsReader<CompressedList, Instructions> upper_;
521   size_t progress_;
522   ValueType value_;
523   ValueType lastValue_;
524 };
525
526 }}  // namespaces
527
528 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H