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