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