2 * Copyright 2016 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.
19 #if !defined(__GNUC__) && !defined(_MSC_VER)
20 #error GroupVarint.h requires GCC or MSVC
23 #include <folly/Portability.h>
25 #if FOLLY_X64 || defined(__i386__) || FOLLY_PPC64
26 #define HAVE_GROUP_VARINT 1
30 #include <folly/detail/GroupVarintDetail.h>
31 #include <folly/Bits.h>
32 #include <folly/Range.h>
33 #include <glog/logging.h>
36 #include <x86intrin.h>
39 extern const __m128i groupVarintSSEMasks[];
46 extern const uint8_t groupVarintLengths[];
56 * GroupVarint encoding for 32-bit values.
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)
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.
66 class GroupVarint<uint32_t> : public detail::GroupVarintBase<uint32_t> {
70 * Return the number of bytes used to encode these four values.
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);
77 * Return the number of bytes used to encode four uint32_t values stored
78 * at consecutive positions in an array.
80 static size_t size(const uint32_t* p) {
81 return size(p[0], p[1], p[2], p[3]);
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).
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) {
100 * Return the number of values from *p that are valid from an encoded
101 * buffer of size bytes.
103 static size_t partialCount(const char* p, size_t size) {
105 size_t s = kHeaderSize;
107 if (s > size) return 0;
109 if (s > size) return 1;
111 if (s > size) return 2;
113 if (s > size) return 3;
118 * Given a pointer to the beginning of an GroupVarint32-encoded block,
119 * return the number of bytes used by the encoding.
121 static size_t encodedSize(const char* p) {
122 return (kHeaderSize + kGroupSize +
123 b0key(*p) + b1key(*p) + b2key(*p) + b3key(*p));
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.
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);
139 storeUnaligned(p, b);
141 storeUnaligned(p, c);
143 storeUnaligned(p, d);
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.
152 static char* encode(char* p, const uint32_t* src) {
153 return encode(p, src[0], src[1], src[2], src[3]);
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).
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];
167 size_t k0 = b0key(k);
168 *a = loadUnaligned<uint32_t>(p) & kMask[k0];
170 size_t k1 = b1key(k);
171 *b = loadUnaligned<uint32_t>(p) & kMask[k1];
173 size_t k2 = b2key(k);
174 *c = loadUnaligned<uint32_t>(p) & kMask[k2];
176 size_t k3 = b3key(k);
177 *d = loadUnaligned<uint32_t>(p) & kMask[k3];
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.
186 static const char* decode_simple(const char* p, uint32_t* dest) {
187 return decode_simple(p, dest, dest+1, dest+2, dest+3);
192 * Just like the non-SSSE3 decode below, but with the additional constraint
193 * that we must be able to read at least 17 bytes from the input pointer, p.
195 static const char* decode(const char* p, uint32_t* dest) {
197 __m128i val = _mm_loadu_si128((const __m128i*)(p+1));
198 __m128i mask = detail::groupVarintSSEMasks[key];
199 __m128i r = _mm_shuffle_epi8(val, mask);
200 _mm_storeu_si128((__m128i*)dest, r);
201 return p + detail::groupVarintLengths[key];
205 * Just like decode_simple, but with the additional constraint that
206 * we must be able to read at least 17 bytes from the input pointer, p.
208 static const char* decode(const char* p, uint32_t* a, uint32_t* b,
209 uint32_t* c, uint32_t* d) {
211 __m128i val = _mm_loadu_si128((const __m128i*)(p+1));
212 __m128i mask = detail::groupVarintSSEMasks[key];
213 __m128i r = _mm_shuffle_epi8(val, mask);
215 // Extracting 32 bits at a time out of an XMM register is a SSE4 feature
217 *a = _mm_extract_epi32(r, 0);
218 *b = _mm_extract_epi32(r, 1);
219 *c = _mm_extract_epi32(r, 2);
220 *d = _mm_extract_epi32(r, 3);
221 #else /* !__SSE4__ */
222 *a = _mm_extract_epi16(r, 0) + (_mm_extract_epi16(r, 1) << 16);
223 *b = _mm_extract_epi16(r, 2) + (_mm_extract_epi16(r, 3) << 16);
224 *c = _mm_extract_epi16(r, 4) + (_mm_extract_epi16(r, 5) << 16);
225 *d = _mm_extract_epi16(r, 6) + (_mm_extract_epi16(r, 7) << 16);
226 #endif /* __SSE4__ */
228 return p + detail::groupVarintLengths[key];
231 #else /* !__SSSE3__ */
232 static const char* decode(const char* p, uint32_t* a, uint32_t* b,
233 uint32_t* c, uint32_t* d) {
234 return decode_simple(p, a, b, c, d);
237 static const char* decode(const char* p, uint32_t* dest) {
238 return decode_simple(p, dest);
240 #endif /* __SSSE3__ */
243 static uint8_t key(uint32_t x) {
244 // __builtin_clz is undefined for the x==0 case
245 return 3 - (__builtin_clz(x|1) / 8);
247 static size_t b0key(size_t x) { return x & 3; }
248 static size_t b1key(size_t x) { return (x >> 2) & 3; }
249 static size_t b2key(size_t x) { return (x >> 4) & 3; }
250 static size_t b3key(size_t x) { return (x >> 6) & 3; }
252 static const uint32_t kMask[];
257 * GroupVarint encoding for 64-bit values.
259 * Encodes 5 64-bit integers at once, each using 1-8 bytes depending on size.
260 * There are two bytes of overhead. (The first two bytes contain the lengths
261 * of the five integers encoded as three bits each; 000=1 byte .. 111 = 8 bytes)
263 * This implementation assumes little-endian and does unaligned 64-bit
264 * accesses, so it's basically not portable outside of the x86[_64] world.
267 class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> {
270 * Return the number of bytes used to encode these five values.
272 static size_t size(uint64_t a, uint64_t b, uint64_t c, uint64_t d,
274 return (kHeaderSize + kGroupSize +
275 key(a) + key(b) + key(c) + key(d) + key(e));
279 * Return the number of bytes used to encode five uint64_t values stored
280 * at consecutive positions in an array.
282 static size_t size(const uint64_t* p) {
283 return size(p[0], p[1], p[2], p[3], p[4]);
287 * Return the number of bytes used to encode count (<= 4) values.
288 * If you clip a buffer after these many bytes, you can still decode
289 * the first "count" values correctly (if the remaining size() -
290 * partialSize() bytes are filled with garbage).
292 static size_t partialSize(const type* p, size_t count) {
293 DCHECK_LE(count, kGroupSize);
294 size_t s = kHeaderSize + count;
295 for (; count; --count, ++p) {
302 * Return the number of values from *p that are valid from an encoded
303 * buffer of size bytes.
305 static size_t partialCount(const char* p, size_t size) {
306 uint16_t v = loadUnaligned<uint16_t>(p);
307 size_t s = kHeaderSize;
309 if (s > size) return 0;
311 if (s > size) return 1;
313 if (s > size) return 2;
315 if (s > size) return 3;
317 if (s > size) return 4;
322 * Given a pointer to the beginning of an GroupVarint64-encoded block,
323 * return the number of bytes used by the encoding.
325 static size_t encodedSize(const char* p) {
326 uint16_t n = loadUnaligned<uint16_t>(p);
327 return (kHeaderSize + kGroupSize +
328 b0key(n) + b1key(n) + b2key(n) + b3key(n) + b4key(n));
332 * Encode five uint64_t values into the buffer pointed-to by p, and return
333 * the next position in the buffer (that is, one character past the last
334 * encoded byte). p needs to have at least size()+8 bytes available.
336 static char* encode(char* p, uint64_t a, uint64_t b, uint64_t c,
337 uint64_t d, uint64_t e) {
338 uint8_t b0key = key(a);
339 uint8_t b1key = key(b);
340 uint8_t b2key = key(c);
341 uint8_t b3key = key(d);
342 uint8_t b4key = key(e);
343 storeUnaligned<uint16_t>(
345 (b4key << 12) | (b3key << 9) | (b2key << 6) | (b1key << 3) | b0key);
347 storeUnaligned(p, a);
349 storeUnaligned(p, b);
351 storeUnaligned(p, c);
353 storeUnaligned(p, d);
355 storeUnaligned(p, e);
361 * Encode five uint64_t values from the array pointed-to by src into the
362 * buffer pointed-to by p, similar to encode(p,a,b,c,d,e) above.
364 static char* encode(char* p, const uint64_t* src) {
365 return encode(p, src[0], src[1], src[2], src[3], src[4]);
369 * Decode five uint64_t values from a buffer, and return the next position
370 * in the buffer (that is, one character past the last encoded byte).
371 * The buffer needs to have at least 7 bytes available (they may be read
374 static const char* decode(const char* p, uint64_t* a, uint64_t* b,
375 uint64_t* c, uint64_t* d, uint64_t* e) {
376 uint16_t k = loadUnaligned<uint16_t>(p);
378 uint8_t k0 = b0key(k);
379 *a = loadUnaligned<uint64_t>(p) & kMask[k0];
381 uint8_t k1 = b1key(k);
382 *b = loadUnaligned<uint64_t>(p) & kMask[k1];
384 uint8_t k2 = b2key(k);
385 *c = loadUnaligned<uint64_t>(p) & kMask[k2];
387 uint8_t k3 = b3key(k);
388 *d = loadUnaligned<uint64_t>(p) & kMask[k3];
390 uint8_t k4 = b4key(k);
391 *e = loadUnaligned<uint64_t>(p) & kMask[k4];
397 * Decode five uint64_t values from a buffer and store them in the array
398 * pointed-to by dest, similar to decode(p,a,b,c,d,e) above.
400 static const char* decode(const char* p, uint64_t* dest) {
401 return decode(p, dest, dest+1, dest+2, dest+3, dest+4);
405 enum { kHeaderBytes = 2 };
407 static uint8_t key(uint64_t x) {
408 // __builtin_clzll is undefined for the x==0 case
409 return 7 - (__builtin_clzll(x|1) / 8);
412 static uint8_t b0key(uint16_t x) { return x & 7; }
413 static uint8_t b1key(uint16_t x) { return (x >> 3) & 7; }
414 static uint8_t b2key(uint16_t x) { return (x >> 6) & 7; }
415 static uint8_t b3key(uint16_t x) { return (x >> 9) & 7; }
416 static uint8_t b4key(uint16_t x) { return (x >> 12) & 7; }
418 static const uint64_t kMask[];
421 typedef GroupVarint<uint32_t> GroupVarint32;
422 typedef GroupVarint<uint64_t> GroupVarint64;
425 * Simplify use of GroupVarint* for the case where data is available one
426 * entry at a time (instead of one group at a time). Handles buffering
427 * and an incomplete last chunk.
429 * Output is a function object that accepts character ranges:
430 * out(StringPiece) appends the given character range to the output.
432 template <class T, class Output>
433 class GroupVarintEncoder {
435 typedef GroupVarint<T> Base;
438 explicit GroupVarintEncoder(Output out)
443 ~GroupVarintEncoder() {
448 * Add a value to the encoder.
451 buf_[count_++] = val;
452 if (count_ == Base::kGroupSize) {
453 char* p = Base::encode(tmp_, buf_);
454 out_(StringPiece(tmp_, p));
460 * Finish encoding, flushing any buffered values if necessary.
461 * After finish(), the encoder is immediately ready to encode more data
462 * to the same output.
466 // This is not strictly necessary, but it makes testing easy;
467 // uninitialized bytes are guaranteed to be recorded as taking one byte
469 for (size_t i = count_; i < Base::kGroupSize; i++) {
472 Base::encode(tmp_, buf_);
473 out_(StringPiece(tmp_, Base::partialSize(buf_, count_)));
479 * Return the appender that was used.
484 const Output& output() const {
489 * Reset the encoder, disregarding any state (except what was already
490 * flushed to the output, of course).
498 char tmp_[Base::kMaxSize];
499 type buf_[Base::kGroupSize];
504 * Simplify use of GroupVarint* for the case where the last group in the
505 * input may be incomplete (but the exact size of the input is known).
506 * Allows for extracting values one at a time.
508 template <typename T>
509 class GroupVarintDecoder {
511 typedef GroupVarint<T> Base;
514 GroupVarintDecoder() = default;
516 explicit GroupVarintDecoder(StringPiece data,
517 size_t maxCount = (size_t)-1)
518 : rrest_(data.end()),
524 remaining_(maxCount) {
527 void reset(StringPiece data, size_t maxCount = (size_t)-1) {
534 remaining_ = maxCount;
538 * Read and return the next value.
540 bool next(type* val) {
541 if (pos_ == count_) {
543 size_t rem = end_ - p_;
544 if (rem == 0 || remaining_ == 0) {
547 // next() attempts to read one full group at a time, and so we must have
548 // at least enough bytes readable after its end to handle the case if the
549 // last group is full.
551 // The best way to ensure this is to ensure that data has at least
552 // Base::kMaxSize - 1 bytes readable *after* the end, otherwise we'll copy
553 // into a temporary buffer.
554 if (limit_ - p_ < Base::kMaxSize) {
555 memcpy(tmp_, p_, rem);
558 limit_ = tmp_ + sizeof(tmp_);
561 const char* n = Base::decode(p_, buf_);
563 // Full group could be decoded
564 if (remaining_ >= Base::kGroupSize) {
565 remaining_ -= Base::kGroupSize;
566 count_ = Base::kGroupSize;
571 p_ += Base::partialSize(buf_, count_);
574 // Can't decode a full group
575 count_ = Base::partialCount(p_, end_ - p_);
576 if (remaining_ >= count_) {
577 remaining_ -= count_;
582 p_ += Base::partialSize(buf_, count_);
593 StringPiece rest() const {
594 // This is only valid after next() returned false
595 CHECK(pos_ == count_ && (p_ == end_ || remaining_ == 0));
596 // p_ may point to the internal buffer (tmp_), but we want
597 // to return subpiece of the original data
598 size_t size = end_ - p_;
599 return StringPiece(rrest_ - size, rrest_);
607 char tmp_[2 * Base::kMaxSize];
608 type buf_[Base::kGroupSize];
614 typedef GroupVarintDecoder<uint32_t> GroupVarint32Decoder;
615 typedef GroupVarintDecoder<uint64_t> GroupVarint64Decoder;
619 #endif /* FOLLY_X64 || defined(__i386__) || FOLLY_PPC64 */