Copyright 2012 -> 2013
[folly.git] / folly / GroupVarint.h
1 /*
2  * Copyright 2013 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 #ifndef FOLLY_GROUPVARINT_H_
18 #define FOLLY_GROUPVARINT_H_
19
20 #ifndef __GNUC__
21 #error GroupVarint.h requires GCC
22 #endif
23
24 #if !defined(__x86_64__) && !defined(__i386__)
25 #error GroupVarint.h requires x86_64 or i386
26 #endif
27
28 #include <cstdint>
29 #include <limits>
30 #include "folly/detail/GroupVarintDetail.h"
31 #include "folly/Bits.h"
32 #include "folly/Range.h"
33 #include <glog/logging.h>
34
35 #ifdef __SSSE3__
36 #include <x86intrin.h>
37 namespace folly {
38 namespace detail {
39 extern const __m128i groupVarintSSEMasks[];
40 }  // namespace detail
41 }  // namespace folly
42 #endif
43
44 namespace folly {
45 namespace detail {
46 extern const uint8_t groupVarintLengths[];
47 }  // namespace detail
48 }  // namespace folly
49
50 namespace folly {
51
52 template <typename T>
53 class GroupVarint;
54
55 /**
56  * GroupVarint encoding for 32-bit values.
57  *
58  * Encodes 4 32-bit integers at once, each using 1-4 bytes depending on size.
59  * There is one byte of overhead.  (The first byte contains the lengths of
60  * the four integers encoded as two bits each; 00=1 byte .. 11=4 bytes)
61  *
62  * This implementation assumes little-endian and does unaligned 32-bit
63  * accesses, so it's basically not portable outside of the x86[_64] world.
64  */
65 template <>
66 class GroupVarint<uint32_t> : public detail::GroupVarintBase<uint32_t> {
67  public:
68
69   /**
70    * Return the number of bytes used to encode these four values.
71    */
72   static size_t size(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
73     return kHeaderSize + kGroupSize + key(a) + key(b) + key(c) + key(d);
74   }
75
76   /**
77    * Return the number of bytes used to encode four uint32_t values stored
78    * at consecutive positions in an array.
79    */
80   static size_t size(const uint32_t* p) {
81     return size(p[0], p[1], p[2], p[3]);
82   }
83
84   /**
85    * Return the number of bytes used to encode count (<= 4) values.
86    * If you clip a buffer after these many bytes, you can still decode
87    * the first "count" values correctly (if the remaining size() -
88    * partialSize() bytes are filled with garbage).
89    */
90   static size_t partialSize(const type* p, size_t count) {
91     DCHECK_LE(count, kGroupSize);
92     size_t s = kHeaderSize + count;
93     for (; count; --count, ++p) {
94       s += key(*p);
95     }
96     return s;
97   }
98
99   /**
100    * Return the number of values from *p that are valid from an encoded
101    * buffer of size bytes.
102    */
103   static size_t partialCount(const char* p, size_t size) {
104     char v = *p;
105     size_t s = kHeaderSize;
106     s += 1 + b0key(v);
107     if (s > size) return 0;
108     s += 1 + b1key(v);
109     if (s > size) return 1;
110     s += 1 + b2key(v);
111     if (s > size) return 2;
112     s += 1 + b3key(v);
113     if (s > size) return 3;
114     return 4;
115   }
116
117   /**
118    * Given a pointer to the beginning of an GroupVarint32-encoded block,
119    * return the number of bytes used by the encoding.
120    */
121   static size_t encodedSize(const char* p) {
122     return (kHeaderSize + kGroupSize +
123             b0key(*p) + b1key(*p) + b2key(*p) + b3key(*p));
124   }
125
126   /**
127    * Encode four uint32_t values into the buffer pointed-to by p, and return
128    * the next position in the buffer (that is, one character past the last
129    * encoded byte).  p needs to have at least size()+4 bytes available.
130    */
131   static char* encode(char* p, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
132     uint8_t b0key = key(a);
133     uint8_t b1key = key(b);
134     uint8_t b2key = key(c);
135     uint8_t b3key = key(d);
136     *p++ = (b3key << 6) | (b2key << 4) | (b1key << 2) | b0key;
137     storeUnaligned(p, a);
138     p += b0key+1;
139     storeUnaligned(p, b);
140     p += b1key+1;
141     storeUnaligned(p, c);
142     p += b2key+1;
143     storeUnaligned(p, d);
144     p += b3key+1;
145     return p;
146   }
147
148   /**
149    * Encode four uint32_t values from the array pointed-to by src into the
150    * buffer pointed-to by p, similar to encode(p,a,b,c,d) above.
151    */
152   static char* encode(char* p, const uint32_t* src) {
153     return encode(p, src[0], src[1], src[2], src[3]);
154   }
155
156   /**
157    * Decode four uint32_t values from a buffer, and return the next position
158    * in the buffer (that is, one character past the last encoded byte).
159    * The buffer needs to have at least 3 extra bytes available (they
160    * may be read but ignored).
161    */
162   static const char* decode_simple(const char* p, uint32_t* a, uint32_t* b,
163                                    uint32_t* c, uint32_t* d) {
164     size_t k = loadUnaligned<uint8_t>(p);
165     const char* end = p + detail::groupVarintLengths[k];
166     ++p;
167     size_t k0 = b0key(k);
168     *a = loadUnaligned<uint32_t>(p) & kMask[k0];
169     p += k0+1;
170     size_t k1 = b1key(k);
171     *b = loadUnaligned<uint32_t>(p) & kMask[k1];
172     p += k1+1;
173     size_t k2 = b2key(k);
174     *c = loadUnaligned<uint32_t>(p) & kMask[k2];
175     p += k2+1;
176     size_t k3 = b3key(k);
177     *d = loadUnaligned<uint32_t>(p) & kMask[k3];
178     p += k3+1;
179     return end;
180   }
181
182   /**
183    * Decode four uint32_t values from a buffer and store them in the array
184    * pointed-to by dest, similar to decode(p,a,b,c,d) above.
185    */
186   static const char* decode_simple(const char* p, uint32_t* dest) {
187     return decode_simple(p, dest, dest+1, dest+2, dest+3);
188   }
189
190 #ifdef __SSSE3__
191   static const char* decode(const char* p, uint32_t* dest) {
192     uint8_t key = p[0];
193     __m128i val = _mm_loadu_si128((const __m128i*)(p+1));
194     __m128i mask = detail::groupVarintSSEMasks[key];
195     __m128i r = _mm_shuffle_epi8(val, mask);
196     _mm_storeu_si128((__m128i*)dest, r);
197     return p + detail::groupVarintLengths[key];
198   }
199
200   static const char* decode(const char* p, uint32_t* a, uint32_t* b,
201                             uint32_t* c, uint32_t* d) {
202     uint8_t key = p[0];
203     __m128i val = _mm_loadu_si128((const __m128i*)(p+1));
204     __m128i mask = detail::groupVarintSSEMasks[key];
205     __m128i r = _mm_shuffle_epi8(val, mask);
206
207     // Extracting 32 bits at a time out of an XMM register is a SSE4 feature
208 #ifdef __SSE4__
209     *a = _mm_extract_epi32(r, 0);
210     *b = _mm_extract_epi32(r, 1);
211     *c = _mm_extract_epi32(r, 2);
212     *d = _mm_extract_epi32(r, 3);
213 #else  /* !__SSE4__ */
214     *a = _mm_extract_epi16(r, 0) + (_mm_extract_epi16(r, 1) << 16);
215     *b = _mm_extract_epi16(r, 2) + (_mm_extract_epi16(r, 3) << 16);
216     *c = _mm_extract_epi16(r, 4) + (_mm_extract_epi16(r, 5) << 16);
217     *d = _mm_extract_epi16(r, 6) + (_mm_extract_epi16(r, 7) << 16);
218 #endif  /* __SSE4__ */
219
220     return p + detail::groupVarintLengths[key];
221   }
222
223 #else  /* !__SSSE3__ */
224   static const char* decode(const char* p, uint32_t* a, uint32_t* b,
225                             uint32_t* c, uint32_t* d) {
226     return decode_simple(p, a, b, c, d);
227   }
228
229   static const char* decode(const char* p, uint32_t* dest) {
230     return decode_simple(p, dest);
231   }
232 #endif  /* __SSSE3__ */
233
234  private:
235   static uint8_t key(uint32_t x) {
236     // __builtin_clz is undefined for the x==0 case
237     return 3 - (__builtin_clz(x|1) / 8);
238   }
239   static size_t b0key(size_t x) { return x & 3; }
240   static size_t b1key(size_t x) { return (x >> 2) & 3; }
241   static size_t b2key(size_t x) { return (x >> 4) & 3; }
242   static size_t b3key(size_t x) { return (x >> 6) & 3; }
243
244   static const uint32_t kMask[];
245 };
246
247
248 /**
249  * GroupVarint encoding for 64-bit values.
250  *
251  * Encodes 5 64-bit integers at once, each using 1-8 bytes depending on size.
252  * There are two bytes of overhead.  (The first two bytes contain the lengths
253  * of the five integers encoded as three bits each; 000=1 byte .. 111 = 8 bytes)
254  *
255  * This implementation assumes little-endian and does unaligned 64-bit
256  * accesses, so it's basically not portable outside of the x86[_64] world.
257  */
258 template <>
259 class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> {
260  public:
261   /**
262    * Return the number of bytes used to encode these five values.
263    */
264   static size_t size(uint64_t a, uint64_t b, uint64_t c, uint64_t d,
265                      uint64_t e) {
266     return (kHeaderSize + kGroupSize +
267             key(a) + key(b) + key(c) + key(d) + key(e));
268   }
269
270   /**
271    * Return the number of bytes used to encode five uint64_t values stored
272    * at consecutive positions in an array.
273    */
274   static size_t size(const uint64_t* p) {
275     return size(p[0], p[1], p[2], p[3], p[4]);
276   }
277
278   /**
279    * Return the number of bytes used to encode count (<= 4) values.
280    * If you clip a buffer after these many bytes, you can still decode
281    * the first "count" values correctly (if the remaining size() -
282    * partialSize() bytes are filled with garbage).
283    */
284   static size_t partialSize(const type* p, size_t count) {
285     DCHECK_LE(count, kGroupSize);
286     size_t s = kHeaderSize + count;
287     for (; count; --count, ++p) {
288       s += key(*p);
289     }
290     return s;
291   }
292
293   /**
294    * Return the number of values from *p that are valid from an encoded
295    * buffer of size bytes.
296    */
297   static size_t partialCount(const char* p, size_t size) {
298     uint16_t v = loadUnaligned<uint16_t>(p);
299     size_t s = kHeaderSize;
300     s += 1 + b0key(v);
301     if (s > size) return 0;
302     s += 1 + b1key(v);
303     if (s > size) return 1;
304     s += 1 + b2key(v);
305     if (s > size) return 2;
306     s += 1 + b3key(v);
307     if (s > size) return 3;
308     s += 1 + b4key(v);
309     if (s > size) return 4;
310     return 5;
311   }
312
313   /**
314    * Given a pointer to the beginning of an GroupVarint64-encoded block,
315    * return the number of bytes used by the encoding.
316    */
317   static size_t encodedSize(const char* p) {
318     uint16_t n = loadUnaligned<uint16_t>(p);
319     return (kHeaderSize + kGroupSize +
320             b0key(n) + b1key(n) + b2key(n) + b3key(n) + b4key(n));
321   }
322
323   /**
324    * Encode five uint64_t values into the buffer pointed-to by p, and return
325    * the next position in the buffer (that is, one character past the last
326    * encoded byte).  p needs to have at least size()+8 bytes available.
327    */
328   static char* encode(char* p, uint64_t a, uint64_t b, uint64_t c,
329                       uint64_t d, uint64_t e) {
330     uint8_t b0key = key(a);
331     uint8_t b1key = key(b);
332     uint8_t b2key = key(c);
333     uint8_t b3key = key(d);
334     uint8_t b4key = key(e);
335     storeUnaligned<uint16_t>(
336         p,
337         (b4key << 12) | (b3key << 9) | (b2key << 6) | (b1key << 3) | b0key);
338     p += 2;
339     storeUnaligned(p, a);
340     p += b0key+1;
341     storeUnaligned(p, b);
342     p += b1key+1;
343     storeUnaligned(p, c);
344     p += b2key+1;
345     storeUnaligned(p, d);
346     p += b3key+1;
347     storeUnaligned(p, e);
348     p += b4key+1;
349     return p;
350   }
351
352   /**
353    * Encode five uint64_t values from the array pointed-to by src into the
354    * buffer pointed-to by p, similar to encode(p,a,b,c,d,e) above.
355    */
356   static char* encode(char* p, const uint64_t* src) {
357     return encode(p, src[0], src[1], src[2], src[3], src[4]);
358   }
359
360   /**
361    * Decode five uint64_t values from a buffer, and return the next position
362    * in the buffer (that is, one character past the last encoded byte).
363    * The buffer needs to have at least 7 bytes available (they may be read
364    * but ignored).
365    */
366   static const char* decode(const char* p, uint64_t* a, uint64_t* b,
367                             uint64_t* c, uint64_t* d, uint64_t* e) {
368     uint16_t k = loadUnaligned<uint16_t>(p);
369     p += 2;
370     uint8_t k0 = b0key(k);
371     *a = loadUnaligned<uint64_t>(p) & kMask[k0];
372     p += k0+1;
373     uint8_t k1 = b1key(k);
374     *b = loadUnaligned<uint64_t>(p) & kMask[k1];
375     p += k1+1;
376     uint8_t k2 = b2key(k);
377     *c = loadUnaligned<uint64_t>(p) & kMask[k2];
378     p += k2+1;
379     uint8_t k3 = b3key(k);
380     *d = loadUnaligned<uint64_t>(p) & kMask[k3];
381     p += k3+1;
382     uint8_t k4 = b4key(k);
383     *e = loadUnaligned<uint64_t>(p) & kMask[k4];
384     p += k4+1;
385     return p;
386   }
387
388   /**
389    * Decode five uint64_t values from a buffer and store them in the array
390    * pointed-to by dest, similar to decode(p,a,b,c,d,e) above.
391    */
392   static const char* decode(const char* p, uint64_t* dest) {
393     return decode(p, dest, dest+1, dest+2, dest+3, dest+4);
394   }
395
396  private:
397   enum { kHeaderBytes = 2 };
398
399   static uint8_t key(uint64_t x) {
400     // __builtin_clzll is undefined for the x==0 case
401     return 7 - (__builtin_clzll(x|1) / 8);
402   }
403
404   static uint8_t b0key(uint16_t x) { return x & 7; }
405   static uint8_t b1key(uint16_t x) { return (x >> 3) & 7; }
406   static uint8_t b2key(uint16_t x) { return (x >> 6) & 7; }
407   static uint8_t b3key(uint16_t x) { return (x >> 9) & 7; }
408   static uint8_t b4key(uint16_t x) { return (x >> 12) & 7; }
409
410   static const uint64_t kMask[];
411 };
412
413 typedef GroupVarint<uint32_t> GroupVarint32;
414 typedef GroupVarint<uint64_t> GroupVarint64;
415
416 /**
417  * Simplify use of GroupVarint* for the case where data is available one
418  * entry at a time (instead of one group at a time).  Handles buffering
419  * and an incomplete last chunk.
420  *
421  * Output is a function object that accepts character ranges:
422  * out(StringPiece) appends the given character range to the output.
423  */
424 template <class T, class Output>
425 class GroupVarintEncoder {
426  public:
427   typedef GroupVarint<T> Base;
428   typedef T type;
429
430   explicit GroupVarintEncoder(Output out)
431     : out_(out),
432       count_(0) {
433   }
434
435   ~GroupVarintEncoder() {
436     finish();
437   }
438
439   /**
440    * Add a value to the encoder.
441    */
442   void add(type val) {
443     buf_[count_++] = val;
444     if (count_ == Base::kGroupSize) {
445       char* p = Base::encode(tmp_, buf_);
446       out_(StringPiece(tmp_, p));
447       count_ = 0;
448     }
449   }
450
451   /**
452    * Finish encoding, flushing any buffered values if necessary.
453    * After finish(), the encoder is immediately ready to encode more data
454    * to the same output.
455    */
456   void finish() {
457     if (count_) {
458       // This is not strictly necessary, but it makes testing easy;
459       // uninitialized bytes are guaranteed to be recorded as taking one byte
460       // (not more).
461       for (size_t i = count_; i < Base::kGroupSize; i++) {
462         buf_[i] = 0;
463       }
464       Base::encode(tmp_, buf_);
465       out_(StringPiece(tmp_, Base::partialSize(buf_, count_)));
466       count_ = 0;
467     }
468   }
469
470   /**
471    * Return the appender that was used.
472    */
473   Output& output() {
474     return out_;
475   }
476   const Output& output() const {
477     return out_;
478   }
479
480   /**
481    * Reset the encoder, disregarding any state (except what was already
482    * flushed to the output, of course).
483    */
484   void clear() {
485     count_ = 0;
486   }
487
488  private:
489   Output out_;
490   char tmp_[Base::kMaxSize];
491   type buf_[Base::kGroupSize];
492   size_t count_;
493 };
494
495 /**
496  * Simplify use of GroupVarint* for the case where the last group in the
497  * input may be incomplete (but the exact size of the input is known).
498  * Allows for extracting values one at a time.
499  */
500 template <typename T>
501 class GroupVarintDecoder {
502  public:
503   typedef GroupVarint<T> Base;
504   typedef T type;
505
506   GroupVarintDecoder() { }
507
508   explicit GroupVarintDecoder(StringPiece data,
509                               size_t maxCount = (size_t)-1)
510     : rrest_(data.end()),
511       p_(data.data()),
512       end_(data.end()),
513       pos_(0),
514       count_(0),
515       remaining_(maxCount) {
516   }
517
518   void reset(StringPiece data, size_t maxCount=(size_t)-1) {
519     rrest_ = data.end();
520     p_ = data.data();
521     end_ = data.end();
522     pos_ = 0;
523     count_ = 0;
524     remaining_ = maxCount;
525   }
526
527   /**
528    * Read and return the next value.
529    */
530   bool next(type* val) {
531     if (pos_ == count_) {
532       // refill
533       size_t rem = end_ - p_;
534       if (rem == 0 || remaining_ == 0) {
535         return false;
536       }
537       // next() attempts to read one full group at a time, and so we must have
538       // at least enough bytes readable after its end to handle the case if the
539       // last group is full.
540       //
541       // The best way to ensure this is to ensure that data has at least
542       // Base::kMaxSize - 1 bytes readable *after* the end, otherwise we'll copy
543       // into a temporary buffer.
544       if (rem < Base::kMaxSize) {
545         memcpy(tmp_, p_, rem);
546         p_ = tmp_;
547         end_ = p_ + rem;
548       }
549       pos_ = 0;
550       const char* n = Base::decode(p_, buf_);
551       if (n <= end_) {
552         // Full group could be decoded
553         if (remaining_ >= Base::kGroupSize) {
554           remaining_ -= Base::kGroupSize;
555           count_ = Base::kGroupSize;
556           p_ = n;
557         } else {
558           count_ = remaining_;
559           remaining_ = 0;
560           p_ += Base::partialSize(buf_, count_);
561         }
562       } else {
563         // Can't decode a full group
564         count_ = Base::partialCount(p_, end_ - p_);
565         if (remaining_ >= count_) {
566           remaining_ -= count_;
567           p_ = end_;
568         } else {
569           count_ = remaining_;
570           remaining_ = 0;
571           p_ += Base::partialSize(buf_, count_);
572         }
573         if (count_ == 0) {
574           return false;
575         }
576       }
577     }
578     *val = buf_[pos_++];
579     return true;
580   }
581
582   StringPiece rest() const {
583     // This is only valid after next() returned false
584     CHECK(pos_ == count_ && (p_ == end_ || remaining_ == 0));
585     // p_ may point to the internal buffer (tmp_), but we want
586     // to return subpiece of the original data
587     size_t size = end_ - p_;
588     return StringPiece(rrest_ - size, rrest_);
589   }
590
591  private:
592   const char* rrest_;
593   const char* p_;
594   const char* end_;
595   char tmp_[Base::kMaxSize];
596   type buf_[Base::kGroupSize];
597   size_t pos_;
598   size_t count_;
599   size_t remaining_;
600 };
601
602 typedef GroupVarintDecoder<uint32_t> GroupVarint32Decoder;
603 typedef GroupVarintDecoder<uint64_t> GroupVarint64Decoder;
604
605 }  // namespace folly
606
607 #endif /* FOLLY_GROUPVARINT_H_ */
608