2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <glog/logging.h>
24 #if !defined(__GNUC__) && !defined(_MSC_VER)
25 #error GroupVarint.h requires GCC or MSVC
28 #include <folly/Portability.h>
30 #if FOLLY_X64 || defined(__i386__) || FOLLY_PPC64 || FOLLY_A64
31 #define HAVE_GROUP_VARINT 1
33 #include <folly/Bits.h>
34 #include <folly/Range.h>
35 #include <folly/detail/GroupVarintDetail.h>
36 #include <folly/portability/Builtins.h>
39 #include <nmmintrin.h>
42 alignas(16) extern const uint64_t groupVarintSSEMasks[];
49 extern const uint8_t groupVarintLengths[];
59 * GroupVarint encoding for 32-bit values.
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)
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.
69 class GroupVarint<uint32_t> : public detail::GroupVarintBase<uint32_t> {
73 * Return the number of bytes used to encode these four values.
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);
80 * Return the number of bytes used to encode four uint32_t values stored
81 * at consecutive positions in an array.
83 static size_t size(const uint32_t* p) {
84 return size(p[0], p[1], p[2], p[3]);
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).
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) {
103 * Return the number of values from *p that are valid from an encoded
104 * buffer of size bytes.
106 static size_t partialCount(const char* p, size_t size) {
107 uint8_t v = uint8_t(*p);
108 size_t s = kHeaderSize;
110 if (s > size) return 0;
112 if (s > size) return 1;
114 if (s > size) return 2;
116 if (s > size) return 3;
121 * Given a pointer to the beginning of an GroupVarint32-encoded block,
122 * return the number of bytes used by the encoding.
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));
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.
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);
143 storeUnaligned(p, b);
145 storeUnaligned(p, c);
147 storeUnaligned(p, d);
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.
156 static char* encode(char* p, const uint32_t* src) {
157 return encode(p, src[0], src[1], src[2], src[3]);
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).
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];
171 size_t k0 = b0key(k);
172 *a = loadUnaligned<uint32_t>(p) & kMask[k0];
174 size_t k1 = b1key(k);
175 *b = loadUnaligned<uint32_t>(p) & kMask[k1];
177 size_t k2 = b2key(k);
178 *c = loadUnaligned<uint32_t>(p) & kMask[k2];
180 size_t k3 = b3key(k);
181 *d = loadUnaligned<uint32_t>(p) & kMask[k3];
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.
190 static const char* decode_simple(const char* p, uint32_t* dest) {
191 return decode_simple(p, dest, dest+1, dest+2, dest+3);
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.
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));
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];
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.
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));
218 _mm_load_si128((const __m128i*)&detail::groupVarintSSEMasks[key * 2]);
219 __m128i r = _mm_shuffle_epi8(val, mask);
221 // Extracting 32 bits at a time out of an XMM register is a SSE4 feature
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__ */
234 return p + detail::groupVarintLengths[key];
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);
243 static const char* decode(const char* p, uint32_t* dest) {
244 return decode_simple(p, dest);
246 #endif /* __SSSE3__ */
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));
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; }
258 static const uint32_t kMask[];
263 * GroupVarint encoding for 64-bit values.
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)
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.
273 class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> {
276 * Return the number of bytes used to encode these five values.
278 static size_t size(uint64_t a, uint64_t b, uint64_t c, uint64_t d,
280 return kHeaderSize + kGroupSize +
281 key(a) + key(b) + key(c) + key(d) + key(e);
285 * Return the number of bytes used to encode five uint64_t values stored
286 * at consecutive positions in an array.
288 static size_t size(const uint64_t* p) {
289 return size(p[0], p[1], p[2], p[3], p[4]);
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).
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) {
308 * Return the number of values from *p that are valid from an encoded
309 * buffer of size bytes.
311 static size_t partialCount(const char* p, size_t size) {
312 uint16_t v = loadUnaligned<uint16_t>(p);
313 size_t s = kHeaderSize;
315 if (s > size) return 0;
317 if (s > size) return 1;
319 if (s > size) return 2;
321 if (s > size) return 3;
323 if (s > size) return 4;
328 * Given a pointer to the beginning of an GroupVarint64-encoded block,
329 * return the number of bytes used by the encoding.
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);
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.
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>(
358 storeUnaligned(p, a);
360 storeUnaligned(p, b);
362 storeUnaligned(p, c);
364 storeUnaligned(p, d);
366 storeUnaligned(p, e);
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.
375 static char* encode(char* p, const uint64_t* src) {
376 return encode(p, src[0], src[1], src[2], src[3], src[4]);
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
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);
389 uint8_t k0 = b0key(k);
390 *a = loadUnaligned<uint64_t>(p) & kMask[k0];
392 uint8_t k1 = b1key(k);
393 *b = loadUnaligned<uint64_t>(p) & kMask[k1];
395 uint8_t k2 = b2key(k);
396 *c = loadUnaligned<uint64_t>(p) & kMask[k2];
398 uint8_t k3 = b3key(k);
399 *d = loadUnaligned<uint64_t>(p) & kMask[k3];
401 uint8_t k4 = b4key(k);
402 *e = loadUnaligned<uint64_t>(p) & kMask[k4];
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.
411 static const char* decode(const char* p, uint64_t* dest) {
412 return decode(p, dest, dest+1, dest+2, dest+3, dest+4);
416 enum { kHeaderBytes = 2 };
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));
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; }
429 static const uint64_t kMask[];
432 typedef GroupVarint<uint32_t> GroupVarint32;
433 typedef GroupVarint<uint64_t> GroupVarint64;
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.
440 * Output is a function object that accepts character ranges:
441 * out(StringPiece) appends the given character range to the output.
443 template <class T, class Output>
444 class GroupVarintEncoder {
446 typedef GroupVarint<T> Base;
449 explicit GroupVarintEncoder(Output out)
454 ~GroupVarintEncoder() {
459 * Add a value to the encoder.
462 buf_[count_++] = val;
463 if (count_ == Base::kGroupSize) {
464 char* p = Base::encode(tmp_, buf_);
465 out_(StringPiece(tmp_, p));
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.
477 // This is not strictly necessary, but it makes testing easy;
478 // uninitialized bytes are guaranteed to be recorded as taking one byte
480 for (size_t i = count_; i < Base::kGroupSize; i++) {
483 Base::encode(tmp_, buf_);
484 out_(StringPiece(tmp_, Base::partialSize(buf_, count_)));
490 * Return the appender that was used.
495 const Output& output() const {
500 * Reset the encoder, disregarding any state (except what was already
501 * flushed to the output, of course).
509 char tmp_[Base::kMaxSize];
510 type buf_[Base::kGroupSize];
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.
519 template <typename T>
520 class GroupVarintDecoder {
522 typedef GroupVarint<T> Base;
525 GroupVarintDecoder() = default;
527 explicit GroupVarintDecoder(StringPiece data,
528 size_t maxCount = (size_t)-1)
529 : rrest_(data.end()),
535 remaining_(maxCount) {
538 void reset(StringPiece data, size_t maxCount = (size_t)-1) {
545 remaining_ = maxCount;
549 * Read and return the next value.
551 bool next(type* val) {
552 if (pos_ == count_) {
554 size_t rem = size_t(end_ - p_);
555 if (rem == 0 || remaining_ == 0) {
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.
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);
569 limit_ = tmp_ + sizeof(tmp_);
572 const char* n = Base::decode(p_, buf_);
574 // Full group could be decoded
575 if (remaining_ >= Base::kGroupSize) {
576 remaining_ -= Base::kGroupSize;
577 count_ = Base::kGroupSize;
582 p_ += Base::partialSize(buf_, count_);
585 // Can't decode a full group
586 count_ = Base::partialCount(p_, size_t(end_ - p_));
587 if (remaining_ >= count_) {
588 remaining_ -= count_;
593 p_ += Base::partialSize(buf_, count_);
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_);
618 char tmp_[2 * Base::kMaxSize];
619 type buf_[Base::kGroupSize];
625 typedef GroupVarintDecoder<uint32_t> GroupVarint32Decoder;
626 typedef GroupVarintDecoder<uint64_t> GroupVarint64Decoder;
630 #endif /* FOLLY_X64 || defined(__i386__) || FOLLY_PPC64 */