2 * Copyright 2013 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.
17 #ifndef FOLLY_GROUPVARINT_H_
18 #define FOLLY_GROUPVARINT_H_
21 #error GroupVarint.h requires GCC
24 #if !defined(__x86_64__) && !defined(__i386__)
25 #error GroupVarint.h requires x86_64 or i386
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);
191 static const char* decode(const char* p, uint32_t* dest) {
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];
200 static const char* decode(const char* p, uint32_t* a, uint32_t* b,
201 uint32_t* c, uint32_t* d) {
203 __m128i val = _mm_loadu_si128((const __m128i*)(p+1));
204 __m128i mask = detail::groupVarintSSEMasks[key];
205 __m128i r = _mm_shuffle_epi8(val, mask);
207 // Extracting 32 bits at a time out of an XMM register is a SSE4 feature
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__ */
220 return p + detail::groupVarintLengths[key];
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);
229 static const char* decode(const char* p, uint32_t* dest) {
230 return decode_simple(p, dest);
232 #endif /* __SSSE3__ */
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);
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; }
244 static const uint32_t kMask[];
249 * GroupVarint encoding for 64-bit values.
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)
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.
259 class GroupVarint<uint64_t> : public detail::GroupVarintBase<uint64_t> {
262 * Return the number of bytes used to encode these five values.
264 static size_t size(uint64_t a, uint64_t b, uint64_t c, uint64_t d,
266 return (kHeaderSize + kGroupSize +
267 key(a) + key(b) + key(c) + key(d) + key(e));
271 * Return the number of bytes used to encode five uint64_t values stored
272 * at consecutive positions in an array.
274 static size_t size(const uint64_t* p) {
275 return size(p[0], p[1], p[2], p[3], p[4]);
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).
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) {
294 * Return the number of values from *p that are valid from an encoded
295 * buffer of size bytes.
297 static size_t partialCount(const char* p, size_t size) {
298 uint16_t v = loadUnaligned<uint16_t>(p);
299 size_t s = kHeaderSize;
301 if (s > size) return 0;
303 if (s > size) return 1;
305 if (s > size) return 2;
307 if (s > size) return 3;
309 if (s > size) return 4;
314 * Given a pointer to the beginning of an GroupVarint64-encoded block,
315 * return the number of bytes used by the encoding.
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));
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.
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>(
337 (b4key << 12) | (b3key << 9) | (b2key << 6) | (b1key << 3) | b0key);
339 storeUnaligned(p, a);
341 storeUnaligned(p, b);
343 storeUnaligned(p, c);
345 storeUnaligned(p, d);
347 storeUnaligned(p, e);
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.
356 static char* encode(char* p, const uint64_t* src) {
357 return encode(p, src[0], src[1], src[2], src[3], src[4]);
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
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);
370 uint8_t k0 = b0key(k);
371 *a = loadUnaligned<uint64_t>(p) & kMask[k0];
373 uint8_t k1 = b1key(k);
374 *b = loadUnaligned<uint64_t>(p) & kMask[k1];
376 uint8_t k2 = b2key(k);
377 *c = loadUnaligned<uint64_t>(p) & kMask[k2];
379 uint8_t k3 = b3key(k);
380 *d = loadUnaligned<uint64_t>(p) & kMask[k3];
382 uint8_t k4 = b4key(k);
383 *e = loadUnaligned<uint64_t>(p) & kMask[k4];
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.
392 static const char* decode(const char* p, uint64_t* dest) {
393 return decode(p, dest, dest+1, dest+2, dest+3, dest+4);
397 enum { kHeaderBytes = 2 };
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);
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; }
410 static const uint64_t kMask[];
413 typedef GroupVarint<uint32_t> GroupVarint32;
414 typedef GroupVarint<uint64_t> GroupVarint64;
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.
421 * Output is a function object that accepts character ranges:
422 * out(StringPiece) appends the given character range to the output.
424 template <class T, class Output>
425 class GroupVarintEncoder {
427 typedef GroupVarint<T> Base;
430 explicit GroupVarintEncoder(Output out)
435 ~GroupVarintEncoder() {
440 * Add a value to the encoder.
443 buf_[count_++] = val;
444 if (count_ == Base::kGroupSize) {
445 char* p = Base::encode(tmp_, buf_);
446 out_(StringPiece(tmp_, p));
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.
458 // This is not strictly necessary, but it makes testing easy;
459 // uninitialized bytes are guaranteed to be recorded as taking one byte
461 for (size_t i = count_; i < Base::kGroupSize; i++) {
464 Base::encode(tmp_, buf_);
465 out_(StringPiece(tmp_, Base::partialSize(buf_, count_)));
471 * Return the appender that was used.
476 const Output& output() const {
481 * Reset the encoder, disregarding any state (except what was already
482 * flushed to the output, of course).
490 char tmp_[Base::kMaxSize];
491 type buf_[Base::kGroupSize];
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.
500 template <typename T>
501 class GroupVarintDecoder {
503 typedef GroupVarint<T> Base;
506 GroupVarintDecoder() { }
508 explicit GroupVarintDecoder(StringPiece data,
509 size_t maxCount = (size_t)-1)
510 : rrest_(data.end()),
515 remaining_(maxCount) {
518 void reset(StringPiece data, size_t maxCount=(size_t)-1) {
524 remaining_ = maxCount;
528 * Read and return the next value.
530 bool next(type* val) {
531 if (pos_ == count_) {
533 size_t rem = end_ - p_;
534 if (rem == 0 || remaining_ == 0) {
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.
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);
550 const char* n = Base::decode(p_, buf_);
552 // Full group could be decoded
553 if (remaining_ >= Base::kGroupSize) {
554 remaining_ -= Base::kGroupSize;
555 count_ = Base::kGroupSize;
560 p_ += Base::partialSize(buf_, count_);
563 // Can't decode a full group
564 count_ = Base::partialCount(p_, end_ - p_);
565 if (remaining_ >= count_) {
566 remaining_ -= count_;
571 p_ += Base::partialSize(buf_, count_);
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_);
595 char tmp_[Base::kMaxSize];
596 type buf_[Base::kGroupSize];
602 typedef GroupVarintDecoder<uint32_t> GroupVarint32Decoder;
603 typedef GroupVarintDecoder<uint64_t> GroupVarint64Decoder;
607 #endif /* FOLLY_GROUPVARINT_H_ */