snappy-ruby 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +77 -0
  4. data/Rakefile +12 -0
  5. data/ext/snappy/extconf.rb +83 -0
  6. data/ext/snappy/snappy-src/AUTHORS +1 -0
  7. data/ext/snappy/snappy-src/BUILD.bazel +211 -0
  8. data/ext/snappy/snappy-src/CMakeLists.txt +467 -0
  9. data/ext/snappy/snappy-src/CONTRIBUTING.md +31 -0
  10. data/ext/snappy/snappy-src/COPYING +54 -0
  11. data/ext/snappy/snappy-src/MODULE.bazel +23 -0
  12. data/ext/snappy/snappy-src/NEWS +215 -0
  13. data/ext/snappy/snappy-src/README.md +165 -0
  14. data/ext/snappy/snappy-src/WORKSPACE +27 -0
  15. data/ext/snappy/snappy-src/WORKSPACE.bzlmod +0 -0
  16. data/ext/snappy/snappy-src/cmake/SnappyConfig.cmake.in +33 -0
  17. data/ext/snappy/snappy-src/cmake/config.h.in +75 -0
  18. data/ext/snappy/snappy-src/config.h +78 -0
  19. data/ext/snappy/snappy-src/docs/README.md +72 -0
  20. data/ext/snappy/snappy-src/format_description.txt +110 -0
  21. data/ext/snappy/snappy-src/framing_format.txt +135 -0
  22. data/ext/snappy/snappy-src/snappy-c.cc +90 -0
  23. data/ext/snappy/snappy-src/snappy-c.h +138 -0
  24. data/ext/snappy/snappy-src/snappy-internal.h +444 -0
  25. data/ext/snappy/snappy-src/snappy-sinksource.cc +121 -0
  26. data/ext/snappy/snappy-src/snappy-sinksource.h +182 -0
  27. data/ext/snappy/snappy-src/snappy-stubs-internal.cc +42 -0
  28. data/ext/snappy/snappy-src/snappy-stubs-internal.h +531 -0
  29. data/ext/snappy/snappy-src/snappy-stubs-public.h +60 -0
  30. data/ext/snappy/snappy-src/snappy-stubs-public.h.in +63 -0
  31. data/ext/snappy/snappy-src/snappy-test.cc +503 -0
  32. data/ext/snappy/snappy-src/snappy-test.h +342 -0
  33. data/ext/snappy/snappy-src/snappy.cc +2666 -0
  34. data/ext/snappy/snappy-src/snappy.h +257 -0
  35. data/ext/snappy/snappy-src/snappy_test_data.cc +57 -0
  36. data/ext/snappy/snappy-src/snappy_test_data.h +68 -0
  37. data/ext/snappy/snappy-src/snappy_test_tool.cc +471 -0
  38. data/ext/snappy/snappy-src/snappy_unittest.cc +1023 -0
  39. data/ext/snappy/snappy.c +282 -0
  40. data/lib/snappy/snappy.so +0 -0
  41. data/lib/snappy.rb +5 -0
  42. metadata +142 -0
@@ -0,0 +1,2666 @@
1
+ // Copyright 2005 Google Inc. All Rights Reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ #include "snappy-internal.h"
30
+ #include "snappy-sinksource.h"
31
+ #include "snappy.h"
32
+ #if !defined(SNAPPY_HAVE_BMI2)
33
+ // __BMI2__ is defined by GCC and Clang. Visual Studio doesn't target BMI2
34
+ // specifically, but it does define __AVX2__ when AVX2 support is available.
35
+ // Fortunately, AVX2 was introduced in Haswell, just like BMI2.
36
+ //
37
+ // BMI2 is not defined as a subset of AVX2 (unlike SSSE3 and AVX above). So,
38
+ // GCC and Clang can build code with AVX2 enabled but BMI2 disabled, in which
39
+ // case issuing BMI2 instructions results in a compiler error.
40
+ #if defined(__BMI2__) || (defined(_MSC_VER) && defined(__AVX2__))
41
+ #define SNAPPY_HAVE_BMI2 1
42
+ #else
43
+ #define SNAPPY_HAVE_BMI2 0
44
+ #endif
45
+ #endif // !defined(SNAPPY_HAVE_BMI2)
46
+
47
+ #if !defined(SNAPPY_HAVE_X86_CRC32)
48
+ #if defined(__SSE4_2__)
49
+ #define SNAPPY_HAVE_X86_CRC32 1
50
+ #else
51
+ #define SNAPPY_HAVE_X86_CRC32 0
52
+ #endif
53
+ #endif // !defined(SNAPPY_HAVE_X86_CRC32)
54
+
55
+ #if !defined(SNAPPY_HAVE_NEON_CRC32)
56
+ #if SNAPPY_HAVE_NEON && defined(__ARM_FEATURE_CRC32)
57
+ #define SNAPPY_HAVE_NEON_CRC32 1
58
+ #else
59
+ #define SNAPPY_HAVE_NEON_CRC32 0
60
+ #endif
61
+ #endif // !defined(SNAPPY_HAVE_NEON_CRC32)
62
+
63
+ #if SNAPPY_HAVE_BMI2 || SNAPPY_HAVE_X86_CRC32
64
+ // Please do not replace with <x86intrin.h>. or with headers that assume more
65
+ // advanced SSE versions without checking with all the OWNERS.
66
+ #include <immintrin.h>
67
+ #elif SNAPPY_HAVE_NEON_CRC32
68
+ #include <arm_acle.h>
69
+ #endif
70
+
71
+ #include <algorithm>
72
+ #include <array>
73
+ #include <cstddef>
74
+ #include <cstdint>
75
+ #include <cstdio>
76
+ #include <cstring>
77
+ #include <functional>
78
+ #include <memory>
79
+ #include <string>
80
+ #include <utility>
81
+ #include <vector>
82
+
83
+ namespace snappy {
84
+
85
+ namespace {
86
+
87
+ // The amount of slop bytes writers are using for unconditional copies.
88
+ constexpr int kSlopBytes = 64;
89
+
90
+ using internal::char_table;
91
+ using internal::COPY_1_BYTE_OFFSET;
92
+ using internal::COPY_2_BYTE_OFFSET;
93
+ using internal::COPY_4_BYTE_OFFSET;
94
+ using internal::kMaximumTagLength;
95
+ using internal::LITERAL;
96
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
97
+ using internal::V128;
98
+ using internal::V128_Load;
99
+ using internal::V128_LoadU;
100
+ using internal::V128_Shuffle;
101
+ using internal::V128_StoreU;
102
+ using internal::V128_DupChar;
103
+ #endif
104
+
105
+ // We translate the information encoded in a tag through a lookup table to a
106
+ // format that requires fewer instructions to decode. Effectively we store
107
+ // the length minus the tag part of the offset. The lowest significant byte
108
+ // thus stores the length. While total length - offset is given by
109
+ // entry - ExtractOffset(type). The nice thing is that the subtraction
110
+ // immediately sets the flags for the necessary check that offset >= length.
111
+ // This folds the cmp with sub. We engineer the long literals and copy-4 to
112
+ // always fail this check, so their presence doesn't affect the fast path.
113
+ // To prevent literals from triggering the guard against offset < length (offset
114
+ // does not apply to literals) the table is giving them a spurious offset of
115
+ // 256.
116
+ inline constexpr int16_t MakeEntry(int16_t len, int16_t offset) {
117
+ return len - (offset << 8);
118
+ }
119
+
120
+ inline constexpr int16_t LengthMinusOffset(int data, int type) {
121
+ return type == 3 ? 0xFF // copy-4 (or type == 3)
122
+ : type == 2 ? MakeEntry(data + 1, 0) // copy-2
123
+ : type == 1 ? MakeEntry((data & 7) + 4, data >> 3) // copy-1
124
+ : data < 60 ? MakeEntry(data + 1, 1) // note spurious offset.
125
+ : 0xFF; // long literal
126
+ }
127
+
128
+ inline constexpr int16_t LengthMinusOffset(uint8_t tag) {
129
+ return LengthMinusOffset(tag >> 2, tag & 3);
130
+ }
131
+
132
+ template <size_t... Ints>
133
+ struct index_sequence {};
134
+
135
+ template <std::size_t N, size_t... Is>
136
+ struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {};
137
+
138
+ template <size_t... Is>
139
+ struct make_index_sequence<0, Is...> : index_sequence<Is...> {};
140
+
141
+ template <size_t... seq>
142
+ constexpr std::array<int16_t, 256> MakeTable(index_sequence<seq...>) {
143
+ return std::array<int16_t, 256>{LengthMinusOffset(seq)...};
144
+ }
145
+
146
+ alignas(64) const std::array<int16_t, 256> kLengthMinusOffset =
147
+ MakeTable(make_index_sequence<256>{});
148
+
149
+ // Given a table of uint16_t whose size is mask / 2 + 1, return a pointer to the
150
+ // relevant entry, if any, for the given bytes. Any hash function will do,
151
+ // but a good hash function reduces the number of collisions and thus yields
152
+ // better compression for compressible input.
153
+ //
154
+ // REQUIRES: mask is 2 * (table_size - 1), and table_size is a power of two.
155
+ inline uint16_t* TableEntry(uint16_t* table, uint32_t bytes, uint32_t mask) {
156
+ // Our choice is quicker-and-dirtier than the typical hash function;
157
+ // empirically, that seems beneficial. The upper bits of kMagic * bytes are a
158
+ // higher-quality hash than the lower bits, so when using kMagic * bytes we
159
+ // also shift right to get a higher-quality end result. There's no similar
160
+ // issue with a CRC because all of the output bits of a CRC are equally good
161
+ // "hashes." So, a CPU instruction for CRC, if available, tends to be a good
162
+ // choice.
163
+ #if SNAPPY_HAVE_NEON_CRC32
164
+ // We use mask as the second arg to the CRC function, as it's about to
165
+ // be used anyway; it'd be equally correct to use 0 or some constant.
166
+ // Mathematically, _mm_crc32_u32 (or similar) is a function of the
167
+ // xor of its arguments.
168
+ const uint32_t hash = __crc32cw(bytes, mask);
169
+ #elif SNAPPY_HAVE_X86_CRC32
170
+ const uint32_t hash = _mm_crc32_u32(bytes, mask);
171
+ #else
172
+ constexpr uint32_t kMagic = 0x1e35a7bd;
173
+ const uint32_t hash = (kMagic * bytes) >> (31 - kMaxHashTableBits);
174
+ #endif
175
+ return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
176
+ (hash & mask));
177
+ }
178
+
179
+ inline uint16_t* TableEntry4ByteMatch(uint16_t* table, uint32_t bytes,
180
+ uint32_t mask) {
181
+ constexpr uint32_t kMagic = 2654435761U;
182
+ const uint32_t hash = (kMagic * bytes) >> (32 - kMaxHashTableBits);
183
+ return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
184
+ (hash & mask));
185
+ }
186
+
187
+ inline uint16_t* TableEntry8ByteMatch(uint16_t* table, uint64_t bytes,
188
+ uint32_t mask) {
189
+ constexpr uint64_t kMagic = 58295818150454627ULL;
190
+ const uint32_t hash = (kMagic * bytes) >> (64 - kMaxHashTableBits);
191
+ return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
192
+ (hash & mask));
193
+ }
194
+
195
+ } // namespace
196
+
197
+ size_t MaxCompressedLength(size_t source_bytes) {
198
+ // Compressed data can be defined as:
199
+ // compressed := item* literal*
200
+ // item := literal* copy
201
+ //
202
+ // The trailing literal sequence has a space blowup of at most 62/60
203
+ // since a literal of length 60 needs one tag byte + one extra byte
204
+ // for length information.
205
+ //
206
+ // Item blowup is trickier to measure. Suppose the "copy" op copies
207
+ // 4 bytes of data. Because of a special check in the encoding code,
208
+ // we produce a 4-byte copy only if the offset is < 65536. Therefore
209
+ // the copy op takes 3 bytes to encode, and this type of item leads
210
+ // to at most the 62/60 blowup for representing literals.
211
+ //
212
+ // Suppose the "copy" op copies 5 bytes of data. If the offset is big
213
+ // enough, it will take 5 bytes to encode the copy op. Therefore the
214
+ // worst case here is a one-byte literal followed by a five-byte copy.
215
+ // I.e., 6 bytes of input turn into 7 bytes of "compressed" data.
216
+ //
217
+ // This last factor dominates the blowup, so the final estimate is:
218
+ return 32 + source_bytes + source_bytes / 6;
219
+ }
220
+
221
+ namespace {
222
+
223
+ void UnalignedCopy64(const void* src, void* dst) {
224
+ char tmp[8];
225
+ std::memcpy(tmp, src, 8);
226
+ std::memcpy(dst, tmp, 8);
227
+ }
228
+
229
+ void UnalignedCopy128(const void* src, void* dst) {
230
+ // std::memcpy() gets vectorized when the appropriate compiler options are
231
+ // used. For example, x86 compilers targeting SSE2+ will optimize to an SSE2
232
+ // load and store.
233
+ char tmp[16];
234
+ std::memcpy(tmp, src, 16);
235
+ std::memcpy(dst, tmp, 16);
236
+ }
237
+
238
+ template <bool use_16bytes_chunk>
239
+ inline void ConditionalUnalignedCopy128(const char* src, char* dst) {
240
+ if (use_16bytes_chunk) {
241
+ UnalignedCopy128(src, dst);
242
+ } else {
243
+ UnalignedCopy64(src, dst);
244
+ UnalignedCopy64(src + 8, dst + 8);
245
+ }
246
+ }
247
+
248
+ // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used
249
+ // for handling COPY operations where the input and output regions may overlap.
250
+ // For example, suppose:
251
+ // src == "ab"
252
+ // op == src + 2
253
+ // op_limit == op + 20
254
+ // After IncrementalCopySlow(src, op, op_limit), the result will have eleven
255
+ // copies of "ab"
256
+ // ababababababababababab
257
+ // Note that this does not match the semantics of either std::memcpy() or
258
+ // std::memmove().
259
+ inline char* IncrementalCopySlow(const char* src, char* op,
260
+ char* const op_limit) {
261
+ // TODO: Remove pragma when LLVM is aware this
262
+ // function is only called in cold regions and when cold regions don't get
263
+ // vectorized or unrolled.
264
+ #ifdef __clang__
265
+ #pragma clang loop unroll(disable)
266
+ #endif
267
+ while (op < op_limit) {
268
+ *op++ = *src++;
269
+ }
270
+ return op_limit;
271
+ }
272
+
273
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
274
+
275
+ // Computes the bytes for shuffle control mask (please read comments on
276
+ // 'pattern_generation_masks' as well) for the given index_offset and
277
+ // pattern_size. For example, when the 'offset' is 6, it will generate a
278
+ // repeating pattern of size 6. So, the first 16 byte indexes will correspond to
279
+ // the pattern-bytes {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3} and the
280
+ // next 16 byte indexes will correspond to the pattern-bytes {4, 5, 0, 1, 2, 3,
281
+ // 4, 5, 0, 1, 2, 3, 4, 5, 0, 1}. These byte index sequences are generated by
282
+ // calling MakePatternMaskBytes(0, 6, index_sequence<16>()) and
283
+ // MakePatternMaskBytes(16, 6, index_sequence<16>()) respectively.
284
+
285
+
286
+ template <size_t... indexes>
287
+ inline constexpr std::array<char, sizeof...(indexes)> MakePatternMaskBytes(
288
+ int index_offset, int pattern_size, index_sequence<indexes...>) {
289
+ return {static_cast<char>((index_offset + indexes) % pattern_size)...};
290
+ }
291
+
292
+ // Computes the shuffle control mask bytes array for given pattern-sizes and
293
+ // returns an array.
294
+ template <size_t... pattern_sizes_minus_one>
295
+ inline constexpr std::array<std::array<char, sizeof(V128)>,
296
+ sizeof...(pattern_sizes_minus_one)>
297
+ MakePatternMaskBytesTable(int index_offset,
298
+ index_sequence<pattern_sizes_minus_one...>) {
299
+ return {
300
+ MakePatternMaskBytes(index_offset, pattern_sizes_minus_one + 1,
301
+ make_index_sequence</*indexes=*/sizeof(V128)>())...};
302
+ }
303
+ // This is an array of shuffle control masks that can be used as the source
304
+ // operand for PSHUFB to permute the contents of the destination XMM register
305
+ // into a repeating byte pattern.
306
+ alignas(16) constexpr std::array<std::array<char, sizeof(V128)>,
307
+ 16> pattern_generation_masks =
308
+ MakePatternMaskBytesTable(
309
+ /*index_offset=*/0,
310
+ /*pattern_sizes_minus_one=*/make_index_sequence<16>());
311
+
312
+ // Similar to 'pattern_generation_masks', this table is used to "rotate" the
313
+ // pattern so that we can copy the *next 16 bytes* consistent with the pattern.
314
+ // Basically, pattern_reshuffle_masks is a continuation of
315
+ // pattern_generation_masks. It follows that, pattern_reshuffle_masks is same as
316
+ // pattern_generation_masks for offsets 1, 2, 4, 8 and 16.
317
+ alignas(16) constexpr std::array<std::array<char, sizeof(V128)>,
318
+ 16> pattern_reshuffle_masks =
319
+ MakePatternMaskBytesTable(
320
+ /*index_offset=*/16,
321
+ /*pattern_sizes_minus_one=*/make_index_sequence<16>());
322
+
323
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
324
+ static inline V128 LoadPattern(const char* src, const size_t pattern_size) {
325
+ V128 generation_mask = V128_Load(reinterpret_cast<const V128*>(
326
+ pattern_generation_masks[pattern_size - 1].data()));
327
+ // Uninitialized bytes are masked out by the shuffle mask.
328
+ // TODO: remove annotation and macro defs once MSan is fixed.
329
+ SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(src + pattern_size, 16 - pattern_size);
330
+ return V128_Shuffle(V128_LoadU(reinterpret_cast<const V128*>(src)),
331
+ generation_mask);
332
+ }
333
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
334
+ static inline std::pair<V128 /* pattern */, V128 /* reshuffle_mask */>
335
+ LoadPatternAndReshuffleMask(const char* src, const size_t pattern_size) {
336
+ V128 pattern = LoadPattern(src, pattern_size);
337
+
338
+ // This mask will generate the next 16 bytes in-place. Doing so enables us to
339
+ // write data by at most 4 V128_StoreU.
340
+ //
341
+ // For example, suppose pattern is: abcdefabcdefabcd
342
+ // Shuffling with this mask will generate: efabcdefabcdefab
343
+ // Shuffling again will generate: cdefabcdefabcdef
344
+ V128 reshuffle_mask = V128_Load(reinterpret_cast<const V128*>(
345
+ pattern_reshuffle_masks[pattern_size - 1].data()));
346
+ return {pattern, reshuffle_mask};
347
+ }
348
+ #endif // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
349
+
350
+ // Fallback for when we need to copy while extending the pattern, for example
351
+ // copying 10 bytes from 3 positions back abc -> abcabcabcabca.
352
+ //
353
+ // REQUIRES: [dst - offset, dst + 64) is a valid address range.
354
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
355
+ static inline bool Copy64BytesWithPatternExtension(char* dst, size_t offset) {
356
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
357
+ if (SNAPPY_PREDICT_TRUE(offset <= 16)) {
358
+ switch (offset) {
359
+ case 0:
360
+ return false;
361
+ case 1: {
362
+ // TODO: Ideally we should memset, move back once the
363
+ // codegen issues are fixed.
364
+ V128 pattern = V128_DupChar(dst[-1]);
365
+ for (int i = 0; i < 4; i++) {
366
+ V128_StoreU(reinterpret_cast<V128*>(dst + 16 * i), pattern);
367
+ }
368
+ return true;
369
+ }
370
+ case 2:
371
+ case 4:
372
+ case 8:
373
+ case 16: {
374
+ V128 pattern = LoadPattern(dst - offset, offset);
375
+ for (int i = 0; i < 4; i++) {
376
+ V128_StoreU(reinterpret_cast<V128*>(dst + 16 * i), pattern);
377
+ }
378
+ return true;
379
+ }
380
+ default: {
381
+ auto pattern_and_reshuffle_mask =
382
+ LoadPatternAndReshuffleMask(dst - offset, offset);
383
+ V128 pattern = pattern_and_reshuffle_mask.first;
384
+ V128 reshuffle_mask = pattern_and_reshuffle_mask.second;
385
+ for (int i = 0; i < 4; i++) {
386
+ V128_StoreU(reinterpret_cast<V128*>(dst + 16 * i), pattern);
387
+ pattern = V128_Shuffle(pattern, reshuffle_mask);
388
+ }
389
+ return true;
390
+ }
391
+ }
392
+ }
393
+ #else
394
+ if (SNAPPY_PREDICT_TRUE(offset < 16)) {
395
+ if (SNAPPY_PREDICT_FALSE(offset == 0)) return false;
396
+ // Extend the pattern to the first 16 bytes.
397
+ // The simpler formulation of `dst[i - offset]` induces undefined behavior.
398
+ for (int i = 0; i < 16; i++) dst[i] = (dst - offset)[i];
399
+ // Find a multiple of pattern >= 16.
400
+ static std::array<uint8_t, 16> pattern_sizes = []() {
401
+ std::array<uint8_t, 16> res;
402
+ for (int i = 1; i < 16; i++) res[i] = (16 / i + 1) * i;
403
+ return res;
404
+ }();
405
+ offset = pattern_sizes[offset];
406
+ for (int i = 1; i < 4; i++) {
407
+ std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
408
+ }
409
+ return true;
410
+ }
411
+ #endif // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
412
+
413
+ // Very rare.
414
+ for (int i = 0; i < 4; i++) {
415
+ std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
416
+ }
417
+ return true;
418
+ }
419
+
420
+ // Copy [src, src+(op_limit-op)) to [op, op_limit) but faster than
421
+ // IncrementalCopySlow. buf_limit is the address past the end of the writable
422
+ // region of the buffer.
423
+ inline char* IncrementalCopy(const char* src, char* op, char* const op_limit,
424
+ char* const buf_limit) {
425
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
426
+ constexpr int big_pattern_size_lower_bound = 16;
427
+ #else
428
+ constexpr int big_pattern_size_lower_bound = 8;
429
+ #endif
430
+
431
+ // Terminology:
432
+ //
433
+ // slop = buf_limit - op
434
+ // pat = op - src
435
+ // len = op_limit - op
436
+ assert(src < op);
437
+ assert(op < op_limit);
438
+ assert(op_limit <= buf_limit);
439
+ // NOTE: The copy tags use 3 or 6 bits to store the copy length, so len <= 64.
440
+ assert(op_limit - op <= 64);
441
+ // NOTE: In practice the compressor always emits len >= 4, so it is ok to
442
+ // assume that to optimize this function, but this is not guaranteed by the
443
+ // compression format, so we have to also handle len < 4 in case the input
444
+ // does not satisfy these conditions.
445
+
446
+ size_t pattern_size = op - src;
447
+ // The cases are split into different branches to allow the branch predictor,
448
+ // FDO, and static prediction hints to work better. For each input we list the
449
+ // ratio of invocations that match each condition.
450
+ //
451
+ // input slop < 16 pat < 8 len > 16
452
+ // ------------------------------------------
453
+ // html|html4|cp 0% 1.01% 27.73%
454
+ // urls 0% 0.88% 14.79%
455
+ // jpg 0% 64.29% 7.14%
456
+ // pdf 0% 2.56% 58.06%
457
+ // txt[1-4] 0% 0.23% 0.97%
458
+ // pb 0% 0.96% 13.88%
459
+ // bin 0.01% 22.27% 41.17%
460
+ //
461
+ // It is very rare that we don't have enough slop for doing block copies. It
462
+ // is also rare that we need to expand a pattern. Small patterns are common
463
+ // for incompressible formats and for those we are plenty fast already.
464
+ // Lengths are normally not greater than 16 but they vary depending on the
465
+ // input. In general if we always predict len <= 16 it would be an ok
466
+ // prediction.
467
+ //
468
+ // In order to be fast we want a pattern >= 16 bytes (or 8 bytes in non-SSE)
469
+ // and an unrolled loop copying 1x 16 bytes (or 2x 8 bytes in non-SSE) at a
470
+ // time.
471
+
472
+ // Handle the uncommon case where pattern is less than 16 (or 8 in non-SSE)
473
+ // bytes.
474
+ if (pattern_size < big_pattern_size_lower_bound) {
475
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
476
+ // Load the first eight bytes into an 128-bit XMM register, then use PSHUFB
477
+ // to permute the register's contents in-place into a repeating sequence of
478
+ // the first "pattern_size" bytes.
479
+ // For example, suppose:
480
+ // src == "abc"
481
+ // op == op + 3
482
+ // After V128_Shuffle(), "pattern" will have five copies of "abc"
483
+ // followed by one byte of slop: abcabcabcabcabca.
484
+ //
485
+ // The non-SSE fallback implementation suffers from store-forwarding stalls
486
+ // because its loads and stores partly overlap. By expanding the pattern
487
+ // in-place, we avoid the penalty.
488
+
489
+ // Typically, the op_limit is the gating factor so try to simplify the loop
490
+ // based on that.
491
+ if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 15)) {
492
+ auto pattern_and_reshuffle_mask =
493
+ LoadPatternAndReshuffleMask(src, pattern_size);
494
+ V128 pattern = pattern_and_reshuffle_mask.first;
495
+ V128 reshuffle_mask = pattern_and_reshuffle_mask.second;
496
+ // There is at least one, and at most four 16-byte blocks. Writing four
497
+ // conditionals instead of a loop allows FDO to layout the code with
498
+ // respect to the actual probabilities of each length.
499
+ // TODO: Replace with loop with trip count hint.
500
+ V128_StoreU(reinterpret_cast<V128*>(op), pattern);
501
+
502
+ if (op + 16 < op_limit) {
503
+ pattern = V128_Shuffle(pattern, reshuffle_mask);
504
+ V128_StoreU(reinterpret_cast<V128*>(op + 16), pattern);
505
+ }
506
+ if (op + 32 < op_limit) {
507
+ pattern = V128_Shuffle(pattern, reshuffle_mask);
508
+ V128_StoreU(reinterpret_cast<V128*>(op + 32), pattern);
509
+ }
510
+ if (op + 48 < op_limit) {
511
+ pattern = V128_Shuffle(pattern, reshuffle_mask);
512
+ V128_StoreU(reinterpret_cast<V128*>(op + 48), pattern);
513
+ }
514
+ return op_limit;
515
+ }
516
+ char* const op_end = buf_limit - 15;
517
+ if (SNAPPY_PREDICT_TRUE(op < op_end)) {
518
+ auto pattern_and_reshuffle_mask =
519
+ LoadPatternAndReshuffleMask(src, pattern_size);
520
+ V128 pattern = pattern_and_reshuffle_mask.first;
521
+ V128 reshuffle_mask = pattern_and_reshuffle_mask.second;
522
+ // This code path is relatively cold however so we save code size
523
+ // by avoiding unrolling and vectorizing.
524
+ //
525
+ // TODO: Remove pragma when when cold regions don't get
526
+ // vectorized or unrolled.
527
+ #ifdef __clang__
528
+ #pragma clang loop unroll(disable)
529
+ #endif
530
+ do {
531
+ V128_StoreU(reinterpret_cast<V128*>(op), pattern);
532
+ pattern = V128_Shuffle(pattern, reshuffle_mask);
533
+ op += 16;
534
+ } while (SNAPPY_PREDICT_TRUE(op < op_end));
535
+ }
536
+ return IncrementalCopySlow(op - pattern_size, op, op_limit);
537
+ #else // !SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
538
+ // If plenty of buffer space remains, expand the pattern to at least 8
539
+ // bytes. The way the following loop is written, we need 8 bytes of buffer
540
+ // space if pattern_size >= 4, 11 bytes if pattern_size is 1 or 3, and 10
541
+ // bytes if pattern_size is 2. Precisely encoding that is probably not
542
+ // worthwhile; instead, invoke the slow path if we cannot write 11 bytes
543
+ // (because 11 are required in the worst case).
544
+ if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) {
545
+ while (pattern_size < 8) {
546
+ UnalignedCopy64(src, op);
547
+ op += pattern_size;
548
+ pattern_size *= 2;
549
+ }
550
+ if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
551
+ } else {
552
+ return IncrementalCopySlow(src, op, op_limit);
553
+ }
554
+ #endif // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
555
+ }
556
+ assert(pattern_size >= big_pattern_size_lower_bound);
557
+ constexpr bool use_16bytes_chunk = big_pattern_size_lower_bound == 16;
558
+
559
+ // Copy 1x 16 bytes (or 2x 8 bytes in non-SSE) at a time. Because op - src can
560
+ // be < 16 in non-SSE, a single UnalignedCopy128 might overwrite data in op.
561
+ // UnalignedCopy64 is safe because expanding the pattern to at least 8 bytes
562
+ // guarantees that op - src >= 8.
563
+ //
564
+ // Typically, the op_limit is the gating factor so try to simplify the loop
565
+ // based on that.
566
+ if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 15)) {
567
+ // There is at least one, and at most four 16-byte blocks. Writing four
568
+ // conditionals instead of a loop allows FDO to layout the code with respect
569
+ // to the actual probabilities of each length.
570
+ // TODO: Replace with loop with trip count hint.
571
+ ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
572
+ if (op + 16 < op_limit) {
573
+ ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 16, op + 16);
574
+ }
575
+ if (op + 32 < op_limit) {
576
+ ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 32, op + 32);
577
+ }
578
+ if (op + 48 < op_limit) {
579
+ ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 48, op + 48);
580
+ }
581
+ return op_limit;
582
+ }
583
+
584
+ // Fall back to doing as much as we can with the available slop in the
585
+ // buffer. This code path is relatively cold however so we save code size by
586
+ // avoiding unrolling and vectorizing.
587
+ //
588
+ // TODO: Remove pragma when when cold regions don't get vectorized
589
+ // or unrolled.
590
+ #ifdef __clang__
591
+ #pragma clang loop unroll(disable)
592
+ #endif
593
+ for (char* op_end = buf_limit - 16; op < op_end; op += 16, src += 16) {
594
+ ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
595
+ }
596
+ if (op >= op_limit) return op_limit;
597
+
598
+ // We only take this branch if we didn't have enough slop and we can do a
599
+ // single 8 byte copy.
600
+ if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) {
601
+ UnalignedCopy64(src, op);
602
+ src += 8;
603
+ op += 8;
604
+ }
605
+ return IncrementalCopySlow(src, op, op_limit);
606
+ }
607
+
608
+ } // namespace
609
+
610
+ template <bool allow_fast_path>
611
+ static inline char* EmitLiteral(char* op, const char* literal, int len) {
612
+ // The vast majority of copies are below 16 bytes, for which a
613
+ // call to std::memcpy() is overkill. This fast path can sometimes
614
+ // copy up to 15 bytes too much, but that is okay in the
615
+ // main loop, since we have a bit to go on for both sides:
616
+ //
617
+ // - The input will always have kInputMarginBytes = 15 extra
618
+ // available bytes, as long as we're in the main loop, and
619
+ // if not, allow_fast_path = false.
620
+ // - The output will always have 32 spare bytes (see
621
+ // MaxCompressedLength).
622
+ assert(len > 0); // Zero-length literals are disallowed
623
+ int n = len - 1;
624
+ if (allow_fast_path && len <= 16) {
625
+ // Fits in tag byte
626
+ *op++ = LITERAL | (n << 2);
627
+
628
+ UnalignedCopy128(literal, op);
629
+ return op + len;
630
+ }
631
+
632
+ if (n < 60) {
633
+ // Fits in tag byte
634
+ *op++ = LITERAL | (n << 2);
635
+ } else {
636
+ int count = (Bits::Log2Floor(n) >> 3) + 1;
637
+ assert(count >= 1);
638
+ assert(count <= 4);
639
+ *op++ = LITERAL | ((59 + count) << 2);
640
+ // Encode in upcoming bytes.
641
+ // Write 4 bytes, though we may care about only 1 of them. The output buffer
642
+ // is guaranteed to have at least 3 more spaces left as 'len >= 61' holds
643
+ // here and there is a std::memcpy() of size 'len' below.
644
+ LittleEndian::Store32(op, n);
645
+ op += count;
646
+ }
647
+ // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
+ if (allow_fast_path) {
649
+ char* destination = op;
650
+ const char* source = literal;
651
+ const char* end = destination + len;
652
+ do {
653
+ std::memcpy(destination, source, 16);
654
+ destination += 16;
655
+ source += 16;
656
+ } while (destination < end);
657
+ } else {
658
+ std::memcpy(op, literal, len);
659
+ }
660
+ return op + len;
661
+ }
662
+
663
+ template <bool len_less_than_12>
664
+ static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
+ assert(len <= 64);
666
+ assert(len >= 4);
667
+ assert(offset < 65536);
668
+ assert(len_less_than_12 == (len < 12));
669
+
670
+ if (len_less_than_12) {
671
+ uint32_t u = (len << 2) + (offset << 8);
672
+ uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
+ uint32_t copy2 = COPY_2_BYTE_OFFSET - (1 << 2);
674
+ // It turns out that offset < 2048 is a difficult to predict branch.
675
+ // `perf record` shows this is the highest percentage of branch misses in
676
+ // benchmarks. This code produces branch free code, the data dependency
677
+ // chain that bottlenecks the throughput is so long that a few extra
678
+ // instructions are completely free (IPC << 6 because of data deps).
679
+ u += offset < 2048 ? copy1 : copy2;
680
+ LittleEndian::Store32(op, u);
681
+ op += offset < 2048 ? 2 : 3;
682
+ } else {
683
+ // Write 4 bytes, though we only care about 3 of them. The output buffer
684
+ // is required to have some slack, so the extra byte won't overrun it.
685
+ uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
+ LittleEndian::Store32(op, u);
687
+ op += 3;
688
+ }
689
+ return op;
690
+ }
691
+
692
+ template <bool len_less_than_12>
693
+ static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
+ assert(len_less_than_12 == (len < 12));
695
+ if (len_less_than_12) {
696
+ return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
+ } else {
698
+ // A special case for len <= 64 might help, but so far measurements suggest
699
+ // it's in the noise.
700
+
701
+ // Emit 64 byte copies but make sure to keep at least four bytes reserved.
702
+ while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
+ op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
+ len -= 64;
705
+ }
706
+
707
+ // One or two copies will now finish the job.
708
+ if (len > 64) {
709
+ op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
+ len -= 60;
711
+ }
712
+
713
+ // Emit remainder.
714
+ if (len < 12) {
715
+ op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
+ } else {
717
+ op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
+ }
719
+ return op;
720
+ }
721
+ }
722
+
723
+ bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
724
+ uint32_t v = 0;
725
+ const char* limit = start + n;
726
+ if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
727
+ *result = v;
728
+ return true;
729
+ } else {
730
+ return false;
731
+ }
732
+ }
733
+
734
+ namespace {
735
+ uint32_t CalculateTableSize(uint32_t input_size) {
736
+ static_assert(
737
+ kMaxHashTableSize >= kMinHashTableSize,
738
+ "kMaxHashTableSize should be greater or equal to kMinHashTableSize.");
739
+ if (input_size > kMaxHashTableSize) {
740
+ return kMaxHashTableSize;
741
+ }
742
+ if (input_size < kMinHashTableSize) {
743
+ return kMinHashTableSize;
744
+ }
745
+ // This is equivalent to Log2Ceiling(input_size), assuming input_size > 1.
746
+ // 2 << Log2Floor(x - 1) is equivalent to 1 << (1 + Log2Floor(x - 1)).
747
+ return 2u << Bits::Log2Floor(input_size - 1);
748
+ }
749
+ } // namespace
750
+
751
+ namespace internal {
752
+ WorkingMemory::WorkingMemory(size_t input_size) {
753
+ const size_t max_fragment_size = std::min(input_size, kBlockSize);
754
+ const size_t table_size = CalculateTableSize(max_fragment_size);
755
+ size_ = table_size * sizeof(*table_) + max_fragment_size +
756
+ MaxCompressedLength(max_fragment_size);
757
+ mem_ = std::allocator<char>().allocate(size_);
758
+ table_ = reinterpret_cast<uint16_t*>(mem_);
759
+ input_ = mem_ + table_size * sizeof(*table_);
760
+ output_ = input_ + max_fragment_size;
761
+ }
762
+
763
+ WorkingMemory::~WorkingMemory() {
764
+ std::allocator<char>().deallocate(mem_, size_);
765
+ }
766
+
767
+ uint16_t* WorkingMemory::GetHashTable(size_t fragment_size,
768
+ int* table_size) const {
769
+ const size_t htsize = CalculateTableSize(fragment_size);
770
+ memset(table_, 0, htsize * sizeof(*table_));
771
+ *table_size = htsize;
772
+ return table_;
773
+ }
774
+ } // end namespace internal
775
+
776
+ // Flat array compression that does not emit the "uncompressed length"
777
+ // prefix. Compresses "input" string to the "*op" buffer.
778
+ //
779
+ // REQUIRES: "input" is at most "kBlockSize" bytes long.
780
+ // REQUIRES: "op" points to an array of memory that is at least
781
+ // "MaxCompressedLength(input.size())" in size.
782
+ // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
783
+ // REQUIRES: "table_size" is a power of two
784
+ //
785
+ // Returns an "end" pointer into "op" buffer.
786
+ // "end - op" is the compressed size of "input".
787
+ namespace internal {
788
+ char* CompressFragment(const char* input, size_t input_size, char* op,
789
+ uint16_t* table, const int table_size) {
790
+ // "ip" is the input pointer, and "op" is the output pointer.
791
+ const char* ip = input;
792
+ assert(input_size <= kBlockSize);
793
+ assert((table_size & (table_size - 1)) == 0); // table must be power of two
794
+ const uint32_t mask = 2 * (table_size - 1);
795
+ const char* ip_end = input + input_size;
796
+ const char* base_ip = ip;
797
+
798
+ const size_t kInputMarginBytes = 15;
799
+ if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
800
+ const char* ip_limit = input + input_size - kInputMarginBytes;
801
+
802
+ for (uint32_t preload = LittleEndian::Load32(ip + 1);;) {
803
+ // Bytes in [next_emit, ip) will be emitted as literal bytes. Or
804
+ // [next_emit, ip_end) after the main loop.
805
+ const char* next_emit = ip++;
806
+ uint64_t data = LittleEndian::Load64(ip);
807
+ // The body of this loop calls EmitLiteral once and then EmitCopy one or
808
+ // more times. (The exception is that when we're close to exhausting
809
+ // the input we goto emit_remainder.)
810
+ //
811
+ // In the first iteration of this loop we're just starting, so
812
+ // there's nothing to copy, so calling EmitLiteral once is
813
+ // necessary. And we only start a new iteration when the
814
+ // current iteration has determined that a call to EmitLiteral will
815
+ // precede the next call to EmitCopy (if any).
816
+ //
817
+ // Step 1: Scan forward in the input looking for a 4-byte-long match.
818
+ // If we get close to exhausting the input then goto emit_remainder.
819
+ //
820
+ // Heuristic match skipping: If 32 bytes are scanned with no matches
821
+ // found, start looking only at every other byte. If 32 more bytes are
822
+ // scanned (or skipped), look at every third byte, etc.. When a match is
823
+ // found, immediately go back to looking at every byte. This is a small
824
+ // loss (~5% performance, ~0.1% density) for compressible data due to more
825
+ // bookkeeping, but for non-compressible data (such as JPEG) it's a huge
826
+ // win since the compressor quickly "realizes" the data is incompressible
827
+ // and doesn't bother looking for matches everywhere.
828
+ //
829
+ // The "skip" variable keeps track of how many bytes there are since the
830
+ // last match; dividing it by 32 (ie. right-shifting by five) gives the
831
+ // number of bytes to move ahead for each iteration.
832
+ uint32_t skip = 32;
833
+
834
+ const char* candidate;
835
+ if (ip_limit - ip >= 16) {
836
+ auto delta = ip - base_ip;
837
+ for (int j = 0; j < 4; ++j) {
838
+ for (int k = 0; k < 4; ++k) {
839
+ int i = 4 * j + k;
840
+ // These for-loops are meant to be unrolled. So we can freely
841
+ // special case the first iteration to use the value already
842
+ // loaded in preload.
843
+ uint32_t dword = i == 0 ? preload : static_cast<uint32_t>(data);
844
+ assert(dword == LittleEndian::Load32(ip + i));
845
+ uint16_t* table_entry = TableEntry(table, dword, mask);
846
+ candidate = base_ip + *table_entry;
847
+ assert(candidate >= base_ip);
848
+ assert(candidate < ip + i);
849
+ *table_entry = delta + i;
850
+ if (SNAPPY_PREDICT_FALSE(LittleEndian::Load32(candidate) == dword)) {
851
+ *op = LITERAL | (i << 2);
852
+ UnalignedCopy128(next_emit, op + 1);
853
+ ip += i;
854
+ op = op + i + 2;
855
+ goto emit_match;
856
+ }
857
+ data >>= 8;
858
+ }
859
+ data = LittleEndian::Load64(ip + 4 * j + 4);
860
+ }
861
+ ip += 16;
862
+ skip += 16;
863
+ }
864
+ while (true) {
865
+ assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
866
+ uint16_t* table_entry = TableEntry(table, data, mask);
867
+ uint32_t bytes_between_hash_lookups = skip >> 5;
868
+ skip += bytes_between_hash_lookups;
869
+ const char* next_ip = ip + bytes_between_hash_lookups;
870
+ if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
871
+ ip = next_emit;
872
+ goto emit_remainder;
873
+ }
874
+ candidate = base_ip + *table_entry;
875
+ assert(candidate >= base_ip);
876
+ assert(candidate < ip);
877
+
878
+ *table_entry = ip - base_ip;
879
+ if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
880
+ LittleEndian::Load32(candidate))) {
881
+ break;
882
+ }
883
+ data = LittleEndian::Load32(next_ip);
884
+ ip = next_ip;
885
+ }
886
+
887
+ // Step 2: A 4-byte match has been found. We'll later see if more
888
+ // than 4 bytes match. But, prior to the match, input
889
+ // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes."
890
+ assert(next_emit + 16 <= ip_end);
891
+ op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit, ip - next_emit);
892
+
893
+ // Step 3: Call EmitCopy, and then see if another EmitCopy could
894
+ // be our next move. Repeat until we find no match for the
895
+ // input immediately after what was consumed by the last EmitCopy call.
896
+ //
897
+ // If we exit this loop normally then we need to call EmitLiteral next,
898
+ // though we don't yet know how big the literal will be. We handle that
899
+ // by proceeding to the next iteration of the main loop. We also can exit
900
+ // this loop via goto if we get close to exhausting the input.
901
+ emit_match:
902
+ do {
903
+ // We have a 4-byte match at ip, and no need to emit any
904
+ // "literal bytes" prior to ip.
905
+ const char* base = ip;
906
+ std::pair<size_t, bool> p =
907
+ FindMatchLength(candidate + 4, ip + 4, ip_end, &data);
908
+ size_t matched = 4 + p.first;
909
+ ip += matched;
910
+ size_t offset = base - candidate;
911
+ assert(0 == memcmp(base, candidate, matched));
912
+ if (p.second) {
913
+ op = EmitCopy</*len_less_than_12=*/true>(op, offset, matched);
914
+ } else {
915
+ op = EmitCopy</*len_less_than_12=*/false>(op, offset, matched);
916
+ }
917
+ if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
918
+ goto emit_remainder;
919
+ }
920
+ // Expect 5 bytes to match
921
+ assert((data & 0xFFFFFFFFFF) ==
922
+ (LittleEndian::Load64(ip) & 0xFFFFFFFFFF));
923
+ // We are now looking for a 4-byte match again. We read
924
+ // table[Hash(ip, mask)] for that. To improve compression,
925
+ // we also update table[Hash(ip - 1, mask)] and table[Hash(ip, mask)].
926
+ *TableEntry(table, LittleEndian::Load32(ip - 1), mask) =
927
+ ip - base_ip - 1;
928
+ uint16_t* table_entry = TableEntry(table, data, mask);
929
+ candidate = base_ip + *table_entry;
930
+ *table_entry = ip - base_ip;
931
+ // Measurements on the benchmarks have shown the following probabilities
932
+ // for the loop to exit (ie. avg. number of iterations is reciprocal).
933
+ // BM_Flat/6 txt1 p = 0.3-0.4
934
+ // BM_Flat/7 txt2 p = 0.35
935
+ // BM_Flat/8 txt3 p = 0.3-0.4
936
+ // BM_Flat/9 txt3 p = 0.34-0.4
937
+ // BM_Flat/10 pb p = 0.4
938
+ // BM_Flat/11 gaviota p = 0.1
939
+ // BM_Flat/12 cp p = 0.5
940
+ // BM_Flat/13 c p = 0.3
941
+ } while (static_cast<uint32_t>(data) == LittleEndian::Load32(candidate));
942
+ // Because the least significant 5 bytes matched, we can utilize data
943
+ // for the next iteration.
944
+ preload = data >> 8;
945
+ }
946
+ }
947
+
948
+ emit_remainder:
949
+ // Emit the remaining bytes as a literal
950
+ if (ip < ip_end) {
951
+ op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
952
+ }
953
+
954
+ return op;
955
+ }
956
+
957
+ char* CompressFragmentDoubleHash(const char* input, size_t input_size, char* op,
958
+ uint16_t* table, const int table_size,
959
+ uint16_t* table2, const int table_size2) {
960
+ (void)table_size2;
961
+ assert(table_size == table_size2);
962
+ // "ip" is the input pointer, and "op" is the output pointer.
963
+ const char* ip = input;
964
+ assert(input_size <= kBlockSize);
965
+ assert((table_size & (table_size - 1)) == 0); // table must be power of two
966
+ const uint32_t mask = 2 * (table_size - 1);
967
+ const char* ip_end = input + input_size;
968
+ const char* base_ip = ip;
969
+
970
+ const size_t kInputMarginBytes = 15;
971
+ if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
972
+ const char* ip_limit = input + input_size - kInputMarginBytes;
973
+
974
+ for (;;) {
975
+ const char* next_emit = ip++;
976
+ uint64_t data = LittleEndian::Load64(ip);
977
+ uint32_t skip = 512;
978
+
979
+ const char* candidate;
980
+ uint32_t candidate_length;
981
+ while (true) {
982
+ assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
983
+ uint16_t* table_entry2 = TableEntry8ByteMatch(table2, data, mask);
984
+ uint32_t bytes_between_hash_lookups = skip >> 9;
985
+ skip++;
986
+ const char* next_ip = ip + bytes_between_hash_lookups;
987
+ if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
988
+ ip = next_emit;
989
+ goto emit_remainder;
990
+ }
991
+ candidate = base_ip + *table_entry2;
992
+ assert(candidate >= base_ip);
993
+ assert(candidate < ip);
994
+
995
+ *table_entry2 = ip - base_ip;
996
+ if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
997
+ LittleEndian::Load32(candidate))) {
998
+ candidate_length =
999
+ FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1000
+ break;
1001
+ }
1002
+
1003
+ uint16_t* table_entry = TableEntry4ByteMatch(table, data, mask);
1004
+ candidate = base_ip + *table_entry;
1005
+ assert(candidate >= base_ip);
1006
+ assert(candidate < ip);
1007
+
1008
+ *table_entry = ip - base_ip;
1009
+ if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
1010
+ LittleEndian::Load32(candidate))) {
1011
+ candidate_length =
1012
+ FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1013
+ table_entry2 =
1014
+ TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask);
1015
+ auto candidate2 = base_ip + *table_entry2;
1016
+ size_t candidate_length2 =
1017
+ FindMatchLengthPlain(candidate2, ip + 1, ip_end);
1018
+ if (candidate_length2 > candidate_length) {
1019
+ *table_entry2 = ip - base_ip;
1020
+ candidate = candidate2;
1021
+ candidate_length = candidate_length2;
1022
+ ++ip;
1023
+ }
1024
+ break;
1025
+ }
1026
+ data = LittleEndian::Load64(next_ip);
1027
+ ip = next_ip;
1028
+ }
1029
+ // Backtrack to the point it matches fully.
1030
+ while (ip > next_emit && candidate > base_ip &&
1031
+ *(ip - 1) == *(candidate - 1)) {
1032
+ --ip;
1033
+ --candidate;
1034
+ ++candidate_length;
1035
+ }
1036
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask) =
1037
+ ip - base_ip + 1;
1038
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 2), mask) =
1039
+ ip - base_ip + 2;
1040
+ *TableEntry4ByteMatch(table, LittleEndian::Load32(ip + 1), mask) =
1041
+ ip - base_ip + 1;
1042
+ // Step 2: A 4-byte or 8-byte match has been found.
1043
+ // We'll later see if more than 4 bytes match. But, prior to the match,
1044
+ // input bytes [next_emit, ip) are unmatched. Emit them as
1045
+ // "literal bytes."
1046
+ assert(next_emit + 16 <= ip_end);
1047
+ if (ip - next_emit > 0) {
1048
+ op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit,
1049
+ ip - next_emit);
1050
+ }
1051
+ // Step 3: Call EmitCopy, and then see if another EmitCopy could
1052
+ // be our next move. Repeat until we find no match for the
1053
+ // input immediately after what was consumed by the last EmitCopy call.
1054
+ //
1055
+ // If we exit this loop normally then we need to call EmitLiteral next,
1056
+ // though we don't yet know how big the literal will be. We handle that
1057
+ // by proceeding to the next iteration of the main loop. We also can exit
1058
+ // this loop via goto if we get close to exhausting the input.
1059
+ do {
1060
+ // We have a 4-byte match at ip, and no need to emit any
1061
+ // "literal bytes" prior to ip.
1062
+ const char* base = ip;
1063
+ ip += candidate_length;
1064
+ size_t offset = base - candidate;
1065
+ if (candidate_length < 12) {
1066
+ op =
1067
+ EmitCopy</*len_less_than_12=*/true>(op, offset, candidate_length);
1068
+ } else {
1069
+ op = EmitCopy</*len_less_than_12=*/false>(op, offset,
1070
+ candidate_length);
1071
+ }
1072
+ if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
1073
+ goto emit_remainder;
1074
+ }
1075
+ // We are now looking for a 4-byte match again. We read
1076
+ // table[Hash(ip, mask)] for that. To improve compression,
1077
+ // we also update several previous table entries.
1078
+ if (ip - base_ip > 7) {
1079
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 7), mask) =
1080
+ ip - base_ip - 7;
1081
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 4), mask) =
1082
+ ip - base_ip - 4;
1083
+ }
1084
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 3), mask) =
1085
+ ip - base_ip - 3;
1086
+ *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 2), mask) =
1087
+ ip - base_ip - 2;
1088
+ *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 2), mask) =
1089
+ ip - base_ip - 2;
1090
+ *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 1), mask) =
1091
+ ip - base_ip - 1;
1092
+
1093
+ uint16_t* table_entry =
1094
+ TableEntry8ByteMatch(table2, LittleEndian::Load64(ip), mask);
1095
+ candidate = base_ip + *table_entry;
1096
+ *table_entry = ip - base_ip;
1097
+ if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1098
+ candidate_length =
1099
+ FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1100
+ continue;
1101
+ }
1102
+ table_entry =
1103
+ TableEntry4ByteMatch(table, LittleEndian::Load32(ip), mask);
1104
+ candidate = base_ip + *table_entry;
1105
+ *table_entry = ip - base_ip;
1106
+ if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1107
+ candidate_length =
1108
+ FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1109
+ continue;
1110
+ }
1111
+ break;
1112
+ } while (true);
1113
+ }
1114
+ }
1115
+
1116
+ emit_remainder:
1117
+ // Emit the remaining bytes as a literal
1118
+ if (ip < ip_end) {
1119
+ op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
1120
+ }
1121
+
1122
+ return op;
1123
+ }
1124
+ } // end namespace internal
1125
+
1126
+ static inline void Report(int token, const char *algorithm, size_t
1127
+ compressed_size, size_t uncompressed_size) {
1128
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1129
+ (void)token;
1130
+ (void)algorithm;
1131
+ (void)compressed_size;
1132
+ (void)uncompressed_size;
1133
+ }
1134
+
1135
+ // Signature of output types needed by decompression code.
1136
+ // The decompression code is templatized on a type that obeys this
1137
+ // signature so that we do not pay virtual function call overhead in
1138
+ // the middle of a tight decompression loop.
1139
+ //
1140
+ // class DecompressionWriter {
1141
+ // public:
1142
+ // // Called before decompression
1143
+ // void SetExpectedLength(size_t length);
1144
+ //
1145
+ // // For performance a writer may choose to donate the cursor variable to the
1146
+ // // decompression function. The decompression will inject it in all its
1147
+ // // function calls to the writer. Keeping the important output cursor as a
1148
+ // // function local stack variable allows the compiler to keep it in
1149
+ // // register, which greatly aids performance by avoiding loads and stores of
1150
+ // // this variable in the fast path loop iterations.
1151
+ // T GetOutputPtr() const;
1152
+ //
1153
+ // // At end of decompression the loop donates the ownership of the cursor
1154
+ // // variable back to the writer by calling this function.
1155
+ // void SetOutputPtr(T op);
1156
+ //
1157
+ // // Called after decompression
1158
+ // bool CheckLength() const;
1159
+ //
1160
+ // // Called repeatedly during decompression
1161
+ // // Each function get a pointer to the op (output pointer), that the writer
1162
+ // // can use and update. Note it's important that these functions get fully
1163
+ // // inlined so that no actual address of the local variable needs to be
1164
+ // // taken.
1165
+ // bool Append(const char* ip, size_t length, T* op);
1166
+ // bool AppendFromSelf(uint32_t offset, size_t length, T* op);
1167
+ //
1168
+ // // The rules for how TryFastAppend differs from Append are somewhat
1169
+ // // convoluted:
1170
+ // //
1171
+ // // - TryFastAppend is allowed to decline (return false) at any
1172
+ // // time, for any reason -- just "return false" would be
1173
+ // // a perfectly legal implementation of TryFastAppend.
1174
+ // // The intention is for TryFastAppend to allow a fast path
1175
+ // // in the common case of a small append.
1176
+ // // - TryFastAppend is allowed to read up to <available> bytes
1177
+ // // from the input buffer, whereas Append is allowed to read
1178
+ // // <length>. However, if it returns true, it must leave
1179
+ // // at least five (kMaximumTagLength) bytes in the input buffer
1180
+ // // afterwards, so that there is always enough space to read the
1181
+ // // next tag without checking for a refill.
1182
+ // // - TryFastAppend must always return decline (return false)
1183
+ // // if <length> is 61 or more, as in this case the literal length is not
1184
+ // // decoded fully. In practice, this should not be a big problem,
1185
+ // // as it is unlikely that one would implement a fast path accepting
1186
+ // // this much data.
1187
+ // //
1188
+ // bool TryFastAppend(const char* ip, size_t available, size_t length, T* op);
1189
+ // };
1190
+
1191
+ static inline uint32_t ExtractLowBytes(const uint32_t& v, int n) {
1192
+ assert(n >= 0);
1193
+ assert(n <= 4);
1194
+ #if SNAPPY_HAVE_BMI2
1195
+ return _bzhi_u32(v, 8 * n);
1196
+ #else
1197
+ // This needs to be wider than uint32_t otherwise `mask << 32` will be
1198
+ // undefined.
1199
+ uint64_t mask = 0xffffffff;
1200
+ return v & ~(mask << (8 * n));
1201
+ #endif
1202
+ }
1203
+
1204
+ static inline bool LeftShiftOverflows(uint8_t value, uint32_t shift) {
1205
+ assert(shift < 32);
1206
+ static const uint8_t masks[] = {
1207
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
1208
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
1209
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
1210
+ 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
1211
+ return (value & masks[shift]) != 0;
1212
+ }
1213
+
1214
+ inline bool Copy64BytesWithPatternExtension(ptrdiff_t dst, size_t offset) {
1215
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1216
+ (void)dst;
1217
+ return offset != 0;
1218
+ }
1219
+
1220
+ // Copies between size bytes and 64 bytes from src to dest. size cannot exceed
1221
+ // 64. More than size bytes, but never exceeding 64, might be copied if doing
1222
+ // so gives better performance. [src, src + size) must not overlap with
1223
+ // [dst, dst + size), but [src, src + 64) may overlap with [dst, dst + 64).
1224
+ void MemCopy64(char* dst, const void* src, size_t size) {
1225
+ // Always copy this many bytes. If that's below size then copy the full 64.
1226
+ constexpr int kShortMemCopy = 32;
1227
+ (void)kShortMemCopy;
1228
+ assert(size <= 64);
1229
+ assert(std::less_equal<const void*>()(static_cast<const char*>(src) + size,
1230
+ dst) ||
1231
+ std::less_equal<const void*>()(dst + size, src));
1232
+
1233
+ // We know that src and dst are at least size bytes apart. However, because we
1234
+ // might copy more than size bytes the copy still might overlap past size.
1235
+ // E.g. if src and dst appear consecutively in memory (src + size >= dst).
1236
+ // TODO: Investigate wider copies on other platforms.
1237
+ #if defined(__x86_64__) && defined(__AVX__)
1238
+ assert(kShortMemCopy <= 32);
1239
+ __m256i data = _mm256_lddqu_si256(static_cast<const __m256i *>(src));
1240
+ _mm256_storeu_si256(reinterpret_cast<__m256i *>(dst), data);
1241
+ // Profiling shows that nearly all copies are short.
1242
+ if (SNAPPY_PREDICT_FALSE(size > kShortMemCopy)) {
1243
+ data = _mm256_lddqu_si256(static_cast<const __m256i *>(src) + 1);
1244
+ _mm256_storeu_si256(reinterpret_cast<__m256i *>(dst) + 1, data);
1245
+ }
1246
+ // RVV acceleration available on RISC-V when compiled with -march=rv64gcv
1247
+ #elif defined(__riscv) && SNAPPY_HAVE_RVV
1248
+ // Cast pointers to the type we will operate on.
1249
+ unsigned char* dst_ptr = reinterpret_cast<unsigned char*>(dst);
1250
+ const unsigned char* src_ptr = reinterpret_cast<const unsigned char*>(src);
1251
+ size_t remaining_bytes = size;
1252
+ // Loop as long as there are bytes remaining to be copied.
1253
+ while (remaining_bytes > 0) {
1254
+ // Set vector configuration: e8 (8-bit elements), m2 (LMUL=2).
1255
+ // Use e8m2 configuration to maximize throughput.
1256
+ size_t vl = VSETVL_E8M2(remaining_bytes);
1257
+ // Load data from the current source pointer.
1258
+ vuint8m2_t vec = VLE8_V_U8M2(src_ptr, vl);
1259
+ // Store data to the current destination pointer.
1260
+ VSE8_V_U8M2(dst_ptr, vec, vl);
1261
+ // Update pointers and the remaining count.
1262
+ src_ptr += vl;
1263
+ dst_ptr += vl;
1264
+ remaining_bytes -= vl;
1265
+ }
1266
+
1267
+ #else
1268
+ std::memmove(dst, src, kShortMemCopy);
1269
+ // Profiling shows that nearly all copies are short.
1270
+ if (SNAPPY_PREDICT_FALSE(size > kShortMemCopy)) {
1271
+ std::memmove(dst + kShortMemCopy,
1272
+ static_cast<const uint8_t*>(src) + kShortMemCopy,
1273
+ 64 - kShortMemCopy);
1274
+ }
1275
+ #endif
1276
+ }
1277
+
1278
+ void MemCopy64(ptrdiff_t dst, const void* src, size_t size) {
1279
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1280
+ (void)dst;
1281
+ (void)src;
1282
+ (void)size;
1283
+ }
1284
+
1285
+ void ClearDeferred(const void** deferred_src, size_t* deferred_length,
1286
+ uint8_t* safe_source) {
1287
+ *deferred_src = safe_source;
1288
+ *deferred_length = 0;
1289
+ }
1290
+
1291
+ void DeferMemCopy(const void** deferred_src, size_t* deferred_length,
1292
+ const void* src, size_t length) {
1293
+ *deferred_src = src;
1294
+ *deferred_length = length;
1295
+ }
1296
+
1297
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
1298
+ inline size_t AdvanceToNextTagARMOptimized(const uint8_t** ip_p, size_t* tag) {
1299
+ const uint8_t*& ip = *ip_p;
1300
+ // This section is crucial for the throughput of the decompression loop.
1301
+ // The latency of an iteration is fundamentally constrained by the
1302
+ // following data chain on ip.
1303
+ // ip -> c = Load(ip) -> delta1 = (c & 3) -> ip += delta1 or delta2
1304
+ // delta2 = ((c >> 2) + 1) ip++
1305
+ // This is different from X86 optimizations because ARM has conditional add
1306
+ // instruction (csinc) and it removes several register moves.
1307
+ const size_t tag_type = *tag & 3;
1308
+ const bool is_literal = (tag_type == 0);
1309
+ if (is_literal) {
1310
+ size_t next_literal_tag = (*tag >> 2) + 1;
1311
+ *tag = ip[next_literal_tag];
1312
+ ip += next_literal_tag + 1;
1313
+ } else {
1314
+ *tag = ip[tag_type];
1315
+ ip += tag_type + 1;
1316
+ }
1317
+ return tag_type;
1318
+ }
1319
+
1320
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
1321
+ inline size_t AdvanceToNextTagX86Optimized(const uint8_t** ip_p, size_t* tag) {
1322
+ const uint8_t*& ip = *ip_p;
1323
+ // This section is crucial for the throughput of the decompression loop.
1324
+ // The latency of an iteration is fundamentally constrained by the
1325
+ // following data chain on ip.
1326
+ // ip -> c = Load(ip) -> ip1 = ip + 1 + (c & 3) -> ip = ip1 or ip2
1327
+ // ip2 = ip + 2 + (c >> 2)
1328
+ // This amounts to 8 cycles.
1329
+ // 5 (load) + 1 (c & 3) + 1 (lea ip1, [ip + (c & 3) + 1]) + 1 (cmov)
1330
+ size_t literal_len = *tag >> 2;
1331
+ size_t tag_type = *tag;
1332
+ bool is_literal;
1333
+ #if defined(__GCC_ASM_FLAG_OUTPUTS__) && defined(__x86_64__)
1334
+ // TODO clang misses the fact that the (c & 3) already correctly
1335
+ // sets the zero flag.
1336
+ asm("and $3, %k[tag_type]\n\t"
1337
+ : [tag_type] "+r"(tag_type), "=@ccz"(is_literal)
1338
+ :: "cc");
1339
+ #else
1340
+ tag_type &= 3;
1341
+ is_literal = (tag_type == 0);
1342
+ #endif
1343
+ // TODO
1344
+ // This is code is subtle. Loading the values first and then cmov has less
1345
+ // latency then cmov ip and then load. However clang would move the loads
1346
+ // in an optimization phase, volatile prevents this transformation.
1347
+ // Note that we have enough slop bytes (64) that the loads are always valid.
1348
+ size_t tag_literal =
1349
+ static_cast<const volatile uint8_t*>(ip)[1 + literal_len];
1350
+ size_t tag_copy = static_cast<const volatile uint8_t*>(ip)[tag_type];
1351
+ *tag = is_literal ? tag_literal : tag_copy;
1352
+ const uint8_t* ip_copy = ip + 1 + tag_type;
1353
+ const uint8_t* ip_literal = ip + 2 + literal_len;
1354
+ ip = is_literal ? ip_literal : ip_copy;
1355
+ #if defined(__GNUC__) && defined(__x86_64__)
1356
+ // TODO Clang is "optimizing" zero-extension (a totally free
1357
+ // operation) this means that after the cmov of tag, it emits another movzb
1358
+ // tag, byte(tag). It really matters as it's on the core chain. This dummy
1359
+ // asm, persuades clang to do the zero-extension at the load (it's automatic)
1360
+ // removing the expensive movzb.
1361
+ asm("" ::"r"(tag_copy));
1362
+ #endif
1363
+ return tag_type;
1364
+ }
1365
+
1366
+ // Extract the offset for copy-1 and copy-2 returns 0 for literals or copy-4.
1367
+ inline uint32_t ExtractOffset(uint32_t val, size_t tag_type) {
1368
+ // For x86 non-static storage works better. For ARM static storage is better.
1369
+ // TODO: Once the array is recognized as a register, improve the
1370
+ // readability for x86.
1371
+ #if defined(__x86_64__)
1372
+ constexpr uint64_t kExtractMasksCombined = 0x0000FFFF00FF0000ull;
1373
+ uint16_t result;
1374
+ memcpy(&result,
1375
+ reinterpret_cast<const char*>(&kExtractMasksCombined) + 2 * tag_type,
1376
+ sizeof(result));
1377
+ return val & result;
1378
+ #elif defined(__aarch64__)
1379
+ constexpr uint64_t kExtractMasksCombined = 0x0000FFFF00FF0000ull;
1380
+ return val & static_cast<uint32_t>(
1381
+ (kExtractMasksCombined >> (tag_type * 16)) & 0xFFFF);
1382
+ #else
1383
+ static constexpr uint32_t kExtractMasks[4] = {0, 0xFF, 0xFFFF, 0};
1384
+ return val & kExtractMasks[tag_type];
1385
+ #endif
1386
+ };
1387
+
1388
+ // Core decompression loop, when there is enough data available.
1389
+ // Decompresses the input buffer [ip, ip_limit) into the output buffer
1390
+ // [op, op_limit_min_slop). Returning when either we are too close to the end
1391
+ // of the input buffer, or we exceed op_limit_min_slop or when a exceptional
1392
+ // tag is encountered (literal of length > 60) or a copy-4.
1393
+ // Returns {ip, op} at the points it stopped decoding.
1394
+ // TODO This function probably does not need to be inlined, as it
1395
+ // should decode large chunks at a time. This allows runtime dispatch to
1396
+ // implementations based on CPU capability (BMI2 / perhaps 32 / 64 byte memcpy).
1397
+ template <typename T>
1398
+ std::pair<const uint8_t*, ptrdiff_t> DecompressBranchless(
1399
+ const uint8_t* ip, const uint8_t* ip_limit, ptrdiff_t op, T op_base,
1400
+ ptrdiff_t op_limit_min_slop) {
1401
+ // If deferred_src is invalid point it here.
1402
+ uint8_t safe_source[64];
1403
+ const void* deferred_src;
1404
+ size_t deferred_length;
1405
+ ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
+
1407
+ // We unroll the inner loop twice so we need twice the spare room.
1408
+ op_limit_min_slop -= kSlopBytes;
1409
+ if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
+ const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
+ ip++;
1412
+ // ip points just past the tag and we are touching at maximum kSlopBytes
1413
+ // in an iteration.
1414
+ size_t tag = ip[-1];
1415
+ #if defined(__clang__) && defined(__aarch64__)
1416
+ // Workaround for https://bugs.llvm.org/show_bug.cgi?id=51317
1417
+ // when loading 1 byte, clang for aarch64 doesn't realize that it(ldrb)
1418
+ // comes with free zero-extension, so clang generates another
1419
+ // 'and xn, xm, 0xff' before it use that as the offset. This 'and' is
1420
+ // redundant and can be removed by adding this dummy asm, which gives
1421
+ // clang a hint that we're doing the zero-extension at the load.
1422
+ asm("" ::"r"(tag));
1423
+ #endif
1424
+ do {
1425
+ // The throughput is limited by instructions, unrolling the inner loop
1426
+ // twice reduces the amount of instructions checking limits and also
1427
+ // leads to reduced mov's.
1428
+
1429
+ SNAPPY_PREFETCH(ip + 128);
1430
+ for (int i = 0; i < 2; i++) {
1431
+ const uint8_t* old_ip = ip;
1432
+ assert(tag == ip[-1]);
1433
+ // For literals tag_type = 0, hence we will always obtain 0 from
1434
+ // ExtractLowBytes. For literals offset will thus be kLiteralOffset.
1435
+ ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
+ uint32_t next;
1437
+ #if defined(__aarch64__)
1438
+ size_t tag_type = AdvanceToNextTagARMOptimized(&ip, &tag);
1439
+ // We never need more than 16 bits. Doing a Load16 allows the compiler
1440
+ // to elide the masking operation in ExtractOffset.
1441
+ next = LittleEndian::Load16(old_ip);
1442
+ #else
1443
+ size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
+ next = LittleEndian::Load32(old_ip);
1445
+ #endif
1446
+ size_t len = len_minus_offset & 0xFF;
1447
+ ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
+ ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
+ if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
+ if (SNAPPY_PREDICT_FALSE(len & 0x80)) {
1451
+ // Exceptional case (long literal or copy 4).
1452
+ // Actually doing the copy here is negatively impacting the main
1453
+ // loop due to compiler incorrectly allocating a register for
1454
+ // this fallback. Hence we just break.
1455
+ break_loop:
1456
+ ip = old_ip;
1457
+ goto exit;
1458
+ }
1459
+ // Only copy-1 or copy-2 tags can get here.
1460
+ assert(tag_type == 1 || tag_type == 2);
1461
+ std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1462
+ // Guard against copies before the buffer start.
1463
+ // Execute any deferred MemCopy since we write to dst here.
1464
+ MemCopy64(op_base + op, deferred_src, deferred_length);
1465
+ op += deferred_length;
1466
+ ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
+ if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
+ !Copy64BytesWithPatternExtension(
1469
+ op_base + op, len - len_min_offset))) {
1470
+ goto break_loop;
1471
+ }
1472
+ // We aren't deferring this copy so add length right away.
1473
+ op += len;
1474
+ continue;
1475
+ }
1476
+ std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
+ if (SNAPPY_PREDICT_FALSE(delta < 0)) {
1478
+ // Due to the spurious offset in literals have this will trigger
1479
+ // at the start of a block when op is still smaller than 256.
1480
+ if (tag_type != 0) goto break_loop;
1481
+ MemCopy64(op_base + op, deferred_src, deferred_length);
1482
+ op += deferred_length;
1483
+ DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
+ continue;
1485
+ }
1486
+
1487
+ // For copies we need to copy from op_base + delta, for literals
1488
+ // we need to copy from ip instead of from the stream.
1489
+ const void* from =
1490
+ tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
+ MemCopy64(op_base + op, deferred_src, deferred_length);
1492
+ op += deferred_length;
1493
+ DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
+ }
1495
+ } while (ip < ip_limit_min_slop &&
1496
+ static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
+ exit:
1498
+ ip--;
1499
+ assert(ip <= ip_limit);
1500
+ }
1501
+ // If we deferred a copy then we can perform. If we are up to date then we
1502
+ // might not have enough slop bytes and could run past the end.
1503
+ if (deferred_length) {
1504
+ MemCopy64(op_base + op, deferred_src, deferred_length);
1505
+ op += deferred_length;
1506
+ ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
+ }
1508
+ return {ip, op};
1509
+ }
1510
+
1511
+ // Helper class for decompression
1512
+ class SnappyDecompressor {
1513
+ private:
1514
+ Source* reader_; // Underlying source of bytes to decompress
1515
+ const char* ip_; // Points to next buffered byte
1516
+ const char* ip_limit_; // Points just past buffered bytes
1517
+ // If ip < ip_limit_min_maxtaglen_ it's safe to read kMaxTagLength from
1518
+ // buffer.
1519
+ const char* ip_limit_min_maxtaglen_;
1520
+ uint64_t peeked_; // Bytes peeked from reader (need to skip)
1521
+ bool eof_; // Hit end of input without an error?
1522
+ char scratch_[kMaximumTagLength]; // See RefillTag().
1523
+
1524
+ // Ensure that all of the tag metadata for the next tag is available
1525
+ // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even
1526
+ // if (ip_limit_ - ip_ < 5).
1527
+ //
1528
+ // Returns true on success, false on error or end of input.
1529
+ bool RefillTag();
1530
+
1531
+ void ResetLimit(const char* ip) {
1532
+ ip_limit_min_maxtaglen_ =
1533
+ ip_limit_ - std::min<ptrdiff_t>(ip_limit_ - ip, kMaximumTagLength - 1);
1534
+ }
1535
+
1536
+ public:
1537
+ explicit SnappyDecompressor(Source* reader)
1538
+ : reader_(reader), ip_(NULL), ip_limit_(NULL), peeked_(0), eof_(false) {}
1539
+
1540
+ ~SnappyDecompressor() {
1541
+ // Advance past any bytes we peeked at from the reader
1542
+ reader_->Skip(peeked_);
1543
+ }
1544
+
1545
+ // Returns true iff we have hit the end of the input without an error.
1546
+ bool eof() const { return eof_; }
1547
+
1548
+ // Read the uncompressed length stored at the start of the compressed data.
1549
+ // On success, stores the length in *result and returns true.
1550
+ // On failure, returns false.
1551
+ bool ReadUncompressedLength(uint32_t* result) {
1552
+ assert(ip_ == NULL); // Must not have read anything yet
1553
+ // Length is encoded in 1..5 bytes
1554
+ *result = 0;
1555
+ uint32_t shift = 0;
1556
+ while (true) {
1557
+ if (shift >= 32) return false;
1558
+ size_t n;
1559
+ const char* ip = reader_->Peek(&n);
1560
+ if (n == 0) return false;
1561
+ const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
1562
+ reader_->Skip(1);
1563
+ uint32_t val = c & 0x7f;
1564
+ if (LeftShiftOverflows(static_cast<uint8_t>(val), shift)) return false;
1565
+ *result |= val << shift;
1566
+ if (c < 128) {
1567
+ break;
1568
+ }
1569
+ shift += 7;
1570
+ }
1571
+ return true;
1572
+ }
1573
+
1574
+ // Process the next item found in the input.
1575
+ // Returns true if successful, false on error or end of input.
1576
+ template <class Writer>
1577
+ #if defined(__GNUC__) && defined(__x86_64__)
1578
+ __attribute__((aligned(32)))
1579
+ #endif
1580
+ void
1581
+ DecompressAllTags(Writer* writer) {
1582
+ const char* ip = ip_;
1583
+ ResetLimit(ip);
1584
+ auto op = writer->GetOutputPtr();
1585
+ // We could have put this refill fragment only at the beginning of the loop.
1586
+ // However, duplicating it at the end of each branch gives the compiler more
1587
+ // scope to optimize the <ip_limit_ - ip> expression based on the local
1588
+ // context, which overall increases speed.
1589
+ #define MAYBE_REFILL() \
1590
+ if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
+ ip_ = ip; \
1592
+ if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit; \
1593
+ ip = ip_; \
1594
+ ResetLimit(ip); \
1595
+ } \
1596
+ preload = static_cast<uint8_t>(*ip)
1597
+
1598
+ // At the start of the for loop below the least significant byte of preload
1599
+ // contains the tag.
1600
+ uint32_t preload;
1601
+ MAYBE_REFILL();
1602
+ for (;;) {
1603
+ {
1604
+ ptrdiff_t op_limit_min_slop;
1605
+ auto op_base = writer->GetBase(&op_limit_min_slop);
1606
+ if (op_base) {
1607
+ auto res =
1608
+ DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
+ reinterpret_cast<const uint8_t*>(ip_limit_),
1610
+ op - op_base, op_base, op_limit_min_slop);
1611
+ ip = reinterpret_cast<const char*>(res.first);
1612
+ op = op_base + res.second;
1613
+ MAYBE_REFILL();
1614
+ }
1615
+ }
1616
+ const uint8_t c = static_cast<uint8_t>(preload);
1617
+ ip++;
1618
+
1619
+ // Ratio of iterations that have LITERAL vs non-LITERAL for different
1620
+ // inputs.
1621
+ //
1622
+ // input LITERAL NON_LITERAL
1623
+ // -----------------------------------
1624
+ // html|html4|cp 23% 77%
1625
+ // urls 36% 64%
1626
+ // jpg 47% 53%
1627
+ // pdf 19% 81%
1628
+ // txt[1-4] 25% 75%
1629
+ // pb 24% 76%
1630
+ // bin 24% 76%
1631
+ if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
+ size_t literal_length = (c >> 2) + 1u;
1633
+ if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
+ assert(literal_length < 61);
1635
+ ip += literal_length;
1636
+ // NOTE: There is no MAYBE_REFILL() here, as TryFastAppend()
1637
+ // will not return true unless there's already at least five spare
1638
+ // bytes in addition to the literal.
1639
+ preload = static_cast<uint8_t>(*ip);
1640
+ continue;
1641
+ }
1642
+ if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
+ // Long literal.
1644
+ const size_t literal_length_length = literal_length - 60;
1645
+ literal_length =
1646
+ ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
+ 1;
1648
+ ip += literal_length_length;
1649
+ }
1650
+
1651
+ size_t avail = ip_limit_ - ip;
1652
+ while (avail < literal_length) {
1653
+ if (!writer->Append(ip, avail, &op)) goto exit;
1654
+ literal_length -= avail;
1655
+ reader_->Skip(peeked_);
1656
+ size_t n;
1657
+ ip = reader_->Peek(&n);
1658
+ avail = n;
1659
+ peeked_ = avail;
1660
+ if (avail == 0) goto exit;
1661
+ ip_limit_ = ip + avail;
1662
+ ResetLimit(ip);
1663
+ }
1664
+ if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
+ ip += literal_length;
1666
+ MAYBE_REFILL();
1667
+ } else {
1668
+ if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
+ const size_t copy_offset = LittleEndian::Load32(ip);
1670
+ const size_t length = (c >> 2) + 1;
1671
+ ip += 4;
1672
+
1673
+ if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
+ } else {
1675
+ const ptrdiff_t entry = kLengthMinusOffset[c];
1676
+ preload = LittleEndian::Load32(ip);
1677
+ const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
+ const uint32_t length = entry & 0xff;
1679
+ assert(length > 0);
1680
+
1681
+ // copy_offset/256 is encoded in bits 8..10. By just fetching
1682
+ // those bits, we get copy_offset (since the bit-field starts at
1683
+ // bit 8).
1684
+ const uint32_t copy_offset = trailer - entry + length;
1685
+ if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
+
1687
+ ip += (c & 3);
1688
+ // By using the result of the previous load we reduce the critical
1689
+ // dependency chain of ip to 4 cycles.
1690
+ preload >>= (c & 3) * 8;
1691
+ if (ip < ip_limit_min_maxtaglen_) continue;
1692
+ }
1693
+ MAYBE_REFILL();
1694
+ }
1695
+ }
1696
+ #undef MAYBE_REFILL
1697
+ exit:
1698
+ writer->SetOutputPtr(op);
1699
+ }
1700
+ };
1701
+
1702
+ constexpr uint32_t CalculateNeeded(uint8_t tag) {
1703
+ return ((tag & 3) == 0 && tag >= (60 * 4))
1704
+ ? (tag >> 2) - 58
1705
+ : (0x05030201 >> ((tag * 8) & 31)) & 0xFF;
1706
+ }
1707
+
1708
+ #if __cplusplus >= 201402L
1709
+ constexpr bool VerifyCalculateNeeded() {
1710
+ for (int i = 0; i < 1; i++) {
1711
+ if (CalculateNeeded(i) != static_cast<uint32_t>((char_table[i] >> 11)) + 1)
1712
+ return false;
1713
+ }
1714
+ return true;
1715
+ }
1716
+
1717
+ // Make sure CalculateNeeded is correct by verifying it against the established
1718
+ // table encoding the number of added bytes needed.
1719
+ static_assert(VerifyCalculateNeeded(), "");
1720
+ #endif // c++14
1721
+
1722
+ bool SnappyDecompressor::RefillTag() {
1723
+ const char* ip = ip_;
1724
+ if (ip == ip_limit_) {
1725
+ // Fetch a new fragment from the reader
1726
+ reader_->Skip(peeked_); // All peeked bytes are used up
1727
+ size_t n;
1728
+ ip = reader_->Peek(&n);
1729
+ peeked_ = n;
1730
+ eof_ = (n == 0);
1731
+ if (eof_) return false;
1732
+ ip_limit_ = ip + n;
1733
+ }
1734
+
1735
+ // Read the tag character
1736
+ assert(ip < ip_limit_);
1737
+ const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
1738
+ // At this point make sure that the data for the next tag is consecutive.
1739
+ // For copy 1 this means the next 2 bytes (tag and 1 byte offset)
1740
+ // For copy 2 the next 3 bytes (tag and 2 byte offset)
1741
+ // For copy 4 the next 5 bytes (tag and 4 byte offset)
1742
+ // For all small literals we only need 1 byte buf for literals 60...63 the
1743
+ // length is encoded in 1...4 extra bytes.
1744
+ const uint32_t needed = CalculateNeeded(c);
1745
+ assert(needed <= sizeof(scratch_));
1746
+
1747
+ // Read more bytes from reader if needed
1748
+ uint64_t nbuf = ip_limit_ - ip;
1749
+ if (nbuf < needed) {
1750
+ // Stitch together bytes from ip and reader to form the word
1751
+ // contents. We store the needed bytes in "scratch_". They
1752
+ // will be consumed immediately by the caller since we do not
1753
+ // read more than we need.
1754
+ std::memmove(scratch_, ip, nbuf);
1755
+ reader_->Skip(peeked_); // All peeked bytes are used up
1756
+ peeked_ = 0;
1757
+ while (nbuf < needed) {
1758
+ size_t length;
1759
+ const char* src = reader_->Peek(&length);
1760
+ if (length == 0) return false;
1761
+ uint64_t to_add = std::min<uint64_t>(needed - nbuf, length);
1762
+ std::memcpy(scratch_ + nbuf, src, to_add);
1763
+ nbuf += to_add;
1764
+ reader_->Skip(to_add);
1765
+ }
1766
+ assert(nbuf == needed);
1767
+ ip_ = scratch_;
1768
+ ip_limit_ = scratch_ + needed;
1769
+ } else if (nbuf < kMaximumTagLength) {
1770
+ // Have enough bytes, but move into scratch_ so that we do not
1771
+ // read past end of input
1772
+ std::memmove(scratch_, ip, nbuf);
1773
+ reader_->Skip(peeked_); // All peeked bytes are used up
1774
+ peeked_ = 0;
1775
+ ip_ = scratch_;
1776
+ ip_limit_ = scratch_ + nbuf;
1777
+ } else {
1778
+ // Pass pointer to buffer returned by reader_.
1779
+ ip_ = ip;
1780
+ }
1781
+ return true;
1782
+ }
1783
+
1784
+ template <typename Writer>
1785
+ static bool InternalUncompress(Source* r, Writer* writer) {
1786
+ // Read the uncompressed length from the front of the compressed input
1787
+ SnappyDecompressor decompressor(r);
1788
+ uint32_t uncompressed_len = 0;
1789
+ if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
+
1791
+ return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
+ uncompressed_len);
1793
+ }
1794
+
1795
+ template <typename Writer>
1796
+ static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
1797
+ Writer* writer, uint32_t compressed_len,
1798
+ uint32_t uncompressed_len) {
1799
+ int token = 0;
1800
+ Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
+
1802
+ writer->SetExpectedLength(uncompressed_len);
1803
+
1804
+ // Process the entire input
1805
+ decompressor->DecompressAllTags(writer);
1806
+ writer->Flush();
1807
+ return (decompressor->eof() && writer->CheckLength());
1808
+ }
1809
+
1810
+ bool GetUncompressedLength(Source* source, uint32_t* result) {
1811
+ SnappyDecompressor decompressor(source);
1812
+ return decompressor.ReadUncompressedLength(result);
1813
+ }
1814
+
1815
+ size_t Compress(Source* reader, Sink* writer) {
1816
+ return Compress(reader, writer, CompressionOptions{});
1817
+ }
1818
+
1819
+ size_t Compress(Source* reader, Sink* writer, CompressionOptions options) {
1820
+ assert(options.level == 1 || options.level == 2);
1821
+ int token = 0;
1822
+ size_t written = 0;
1823
+ size_t N = reader->Available();
1824
+ assert(N <= 0xFFFFFFFFu);
1825
+ const size_t uncompressed_size = N;
1826
+ char ulength[Varint::kMax32];
1827
+ char* p = Varint::Encode32(ulength, N);
1828
+ writer->Append(ulength, p - ulength);
1829
+ written += (p - ulength);
1830
+
1831
+ internal::WorkingMemory wmem(N);
1832
+
1833
+ while (N > 0) {
1834
+ // Get next block to compress (without copying if possible)
1835
+ size_t fragment_size;
1836
+ const char* fragment = reader->Peek(&fragment_size);
1837
+ assert(fragment_size != 0); // premature end of input
1838
+ const size_t num_to_read = std::min(N, kBlockSize);
1839
+ size_t bytes_read = fragment_size;
1840
+
1841
+ size_t pending_advance = 0;
1842
+ if (bytes_read >= num_to_read) {
1843
+ // Buffer returned by reader is large enough
1844
+ pending_advance = num_to_read;
1845
+ fragment_size = num_to_read;
1846
+ } else {
1847
+ char* scratch = wmem.GetScratchInput();
1848
+ std::memcpy(scratch, fragment, bytes_read);
1849
+ reader->Skip(bytes_read);
1850
+
1851
+ while (bytes_read < num_to_read) {
1852
+ fragment = reader->Peek(&fragment_size);
1853
+ size_t n = std::min<size_t>(fragment_size, num_to_read - bytes_read);
1854
+ std::memcpy(scratch + bytes_read, fragment, n);
1855
+ bytes_read += n;
1856
+ reader->Skip(n);
1857
+ }
1858
+ assert(bytes_read == num_to_read);
1859
+ fragment = scratch;
1860
+ fragment_size = num_to_read;
1861
+ }
1862
+ assert(fragment_size == num_to_read);
1863
+
1864
+ // Get encoding table for compression
1865
+ int table_size;
1866
+ uint16_t* table = wmem.GetHashTable(num_to_read, &table_size);
1867
+
1868
+ // Compress input_fragment and append to dest
1869
+ int max_output = MaxCompressedLength(num_to_read);
1870
+
1871
+ // Since we encode kBlockSize regions followed by a region
1872
+ // which is <= kBlockSize in length, a previously allocated
1873
+ // scratch_output[] region is big enough for this iteration.
1874
+ // Need a scratch buffer for the output, in case the byte sink doesn't
1875
+ // have room for us directly.
1876
+ char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput());
1877
+ char* end = nullptr;
1878
+ if (options.level == 1) {
1879
+ end = internal::CompressFragment(fragment, fragment_size, dest, table,
1880
+ table_size);
1881
+ } else if (options.level == 2) {
1882
+ end = internal::CompressFragmentDoubleHash(
1883
+ fragment, fragment_size, dest, table, table_size >> 1,
1884
+ table + (table_size >> 1), table_size >> 1);
1885
+ }
1886
+ writer->Append(dest, end - dest);
1887
+ written += (end - dest);
1888
+
1889
+ N -= num_to_read;
1890
+ reader->Skip(pending_advance);
1891
+ }
1892
+
1893
+ Report(token, "snappy_compress", written, uncompressed_size);
1894
+ return written;
1895
+ }
1896
+
1897
+ // -----------------------------------------------------------------------
1898
+ // IOVec interfaces
1899
+ // -----------------------------------------------------------------------
1900
+
1901
+ // A `Source` implementation that yields the contents of an `iovec` array. Note
1902
+ // that `total_size` is the total number of bytes to be read from the elements
1903
+ // of `iov` (_not_ the total number of elements in `iov`).
1904
+ class SnappyIOVecReader : public Source {
1905
+ public:
1906
+ SnappyIOVecReader(const struct iovec* iov, size_t total_size)
1907
+ : curr_iov_(iov),
1908
+ curr_pos_(total_size > 0 ? reinterpret_cast<const char*>(iov->iov_base)
1909
+ : nullptr),
1910
+ curr_size_remaining_(total_size > 0 ? iov->iov_len : 0),
1911
+ total_size_remaining_(total_size) {
1912
+ // Skip empty leading `iovec`s.
1913
+ if (total_size > 0 && curr_size_remaining_ == 0) Advance();
1914
+ }
1915
+
1916
+ ~SnappyIOVecReader() override = default;
1917
+
1918
+ size_t Available() const override { return total_size_remaining_; }
1919
+
1920
+ const char* Peek(size_t* len) override {
1921
+ *len = curr_size_remaining_;
1922
+ return curr_pos_;
1923
+ }
1924
+
1925
+ void Skip(size_t n) override {
1926
+ while (n >= curr_size_remaining_ && n > 0) {
1927
+ n -= curr_size_remaining_;
1928
+ Advance();
1929
+ }
1930
+ curr_size_remaining_ -= n;
1931
+ total_size_remaining_ -= n;
1932
+ curr_pos_ += n;
1933
+ }
1934
+
1935
+ private:
1936
+ // Advances to the next nonempty `iovec` and updates related variables.
1937
+ void Advance() {
1938
+ do {
1939
+ assert(total_size_remaining_ >= curr_size_remaining_);
1940
+ total_size_remaining_ -= curr_size_remaining_;
1941
+ if (total_size_remaining_ == 0) {
1942
+ curr_pos_ = nullptr;
1943
+ curr_size_remaining_ = 0;
1944
+ return;
1945
+ }
1946
+ ++curr_iov_;
1947
+ curr_pos_ = reinterpret_cast<const char*>(curr_iov_->iov_base);
1948
+ curr_size_remaining_ = curr_iov_->iov_len;
1949
+ } while (curr_size_remaining_ == 0);
1950
+ }
1951
+
1952
+ // The `iovec` currently being read.
1953
+ const struct iovec* curr_iov_;
1954
+ // The location in `curr_iov_` currently being read.
1955
+ const char* curr_pos_;
1956
+ // The amount of unread data in `curr_iov_`.
1957
+ size_t curr_size_remaining_;
1958
+ // The amount of unread data in the entire input array.
1959
+ size_t total_size_remaining_;
1960
+ };
1961
+
1962
+ // A type that writes to an iovec.
1963
+ // Note that this is not a "ByteSink", but a type that matches the
1964
+ // Writer template argument to SnappyDecompressor::DecompressAllTags().
1965
+ class SnappyIOVecWriter {
1966
+ private:
1967
+ // output_iov_end_ is set to iov + count and used to determine when
1968
+ // the end of the iovs is reached.
1969
+ const struct iovec* output_iov_end_;
1970
+
1971
+ #if !defined(NDEBUG)
1972
+ const struct iovec* output_iov_;
1973
+ #endif // !defined(NDEBUG)
1974
+
1975
+ // Current iov that is being written into.
1976
+ const struct iovec* curr_iov_;
1977
+
1978
+ // Pointer to current iov's write location.
1979
+ char* curr_iov_output_;
1980
+
1981
+ // Remaining bytes to write into curr_iov_output.
1982
+ size_t curr_iov_remaining_;
1983
+
1984
+ // Total bytes decompressed into output_iov_ so far.
1985
+ size_t total_written_;
1986
+
1987
+ // Maximum number of bytes that will be decompressed into output_iov_.
1988
+ size_t output_limit_;
1989
+
1990
+ static inline char* GetIOVecPointer(const struct iovec* iov, size_t offset) {
1991
+ return reinterpret_cast<char*>(iov->iov_base) + offset;
1992
+ }
1993
+
1994
+ public:
1995
+ // Does not take ownership of iov. iov must be valid during the
1996
+ // entire lifetime of the SnappyIOVecWriter.
1997
+ inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count)
1998
+ : output_iov_end_(iov + iov_count),
1999
+ #if !defined(NDEBUG)
2000
+ output_iov_(iov),
2001
+ #endif // !defined(NDEBUG)
2002
+ curr_iov_(iov),
2003
+ curr_iov_output_(iov_count ? reinterpret_cast<char*>(iov->iov_base)
2004
+ : nullptr),
2005
+ curr_iov_remaining_(iov_count ? iov->iov_len : 0),
2006
+ total_written_(0),
2007
+ output_limit_(-1) {
2008
+ }
2009
+
2010
+ inline void SetExpectedLength(size_t len) { output_limit_ = len; }
2011
+
2012
+ inline bool CheckLength() const { return total_written_ == output_limit_; }
2013
+
2014
+ inline bool Append(const char* ip, size_t len, char**) {
2015
+ if (total_written_ + len > output_limit_) {
2016
+ return false;
2017
+ }
2018
+
2019
+ return AppendNoCheck(ip, len);
2020
+ }
2021
+
2022
+ char* GetOutputPtr() { return nullptr; }
2023
+ char* GetBase(ptrdiff_t*) { return nullptr; }
2024
+ void SetOutputPtr(char* op) {
2025
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2026
+ (void)op;
2027
+ }
2028
+
2029
+ inline bool AppendNoCheck(const char* ip, size_t len) {
2030
+ while (len > 0) {
2031
+ if (curr_iov_remaining_ == 0) {
2032
+ // This iovec is full. Go to the next one.
2033
+ if (curr_iov_ + 1 >= output_iov_end_) {
2034
+ return false;
2035
+ }
2036
+ ++curr_iov_;
2037
+ curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
2038
+ curr_iov_remaining_ = curr_iov_->iov_len;
2039
+ }
2040
+
2041
+ const size_t to_write = std::min(len, curr_iov_remaining_);
2042
+ std::memcpy(curr_iov_output_, ip, to_write);
2043
+ curr_iov_output_ += to_write;
2044
+ curr_iov_remaining_ -= to_write;
2045
+ total_written_ += to_write;
2046
+ ip += to_write;
2047
+ len -= to_write;
2048
+ }
2049
+
2050
+ return true;
2051
+ }
2052
+
2053
+ inline bool TryFastAppend(const char* ip, size_t available, size_t len,
2054
+ char**) {
2055
+ const size_t space_left = output_limit_ - total_written_;
2056
+ if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
2057
+ curr_iov_remaining_ >= 16) {
2058
+ // Fast path, used for the majority (about 95%) of invocations.
2059
+ UnalignedCopy128(ip, curr_iov_output_);
2060
+ curr_iov_output_ += len;
2061
+ curr_iov_remaining_ -= len;
2062
+ total_written_ += len;
2063
+ return true;
2064
+ }
2065
+
2066
+ return false;
2067
+ }
2068
+
2069
+ inline bool AppendFromSelf(size_t offset, size_t len, char**) {
2070
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
2071
+ // the "offset - 1u" trick.
2072
+ if (offset - 1u >= total_written_) {
2073
+ return false;
2074
+ }
2075
+ const size_t space_left = output_limit_ - total_written_;
2076
+ if (len > space_left) {
2077
+ return false;
2078
+ }
2079
+
2080
+ // Locate the iovec from which we need to start the copy.
2081
+ const iovec* from_iov = curr_iov_;
2082
+ size_t from_iov_offset = curr_iov_->iov_len - curr_iov_remaining_;
2083
+ while (offset > 0) {
2084
+ if (from_iov_offset >= offset) {
2085
+ from_iov_offset -= offset;
2086
+ break;
2087
+ }
2088
+
2089
+ offset -= from_iov_offset;
2090
+ --from_iov;
2091
+ #if !defined(NDEBUG)
2092
+ assert(from_iov >= output_iov_);
2093
+ #endif // !defined(NDEBUG)
2094
+ from_iov_offset = from_iov->iov_len;
2095
+ }
2096
+
2097
+ // Copy <len> bytes starting from the iovec pointed to by from_iov_index to
2098
+ // the current iovec.
2099
+ while (len > 0) {
2100
+ assert(from_iov <= curr_iov_);
2101
+ if (from_iov != curr_iov_) {
2102
+ const size_t to_copy =
2103
+ std::min(from_iov->iov_len - from_iov_offset, len);
2104
+ AppendNoCheck(GetIOVecPointer(from_iov, from_iov_offset), to_copy);
2105
+ len -= to_copy;
2106
+ if (len > 0) {
2107
+ ++from_iov;
2108
+ from_iov_offset = 0;
2109
+ }
2110
+ } else {
2111
+ size_t to_copy = curr_iov_remaining_;
2112
+ if (to_copy == 0) {
2113
+ // This iovec is full. Go to the next one.
2114
+ if (curr_iov_ + 1 >= output_iov_end_) {
2115
+ return false;
2116
+ }
2117
+ ++curr_iov_;
2118
+ curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
2119
+ curr_iov_remaining_ = curr_iov_->iov_len;
2120
+ continue;
2121
+ }
2122
+ if (to_copy > len) {
2123
+ to_copy = len;
2124
+ }
2125
+ assert(to_copy > 0);
2126
+
2127
+ IncrementalCopy(GetIOVecPointer(from_iov, from_iov_offset),
2128
+ curr_iov_output_, curr_iov_output_ + to_copy,
2129
+ curr_iov_output_ + curr_iov_remaining_);
2130
+ curr_iov_output_ += to_copy;
2131
+ curr_iov_remaining_ -= to_copy;
2132
+ from_iov_offset += to_copy;
2133
+ total_written_ += to_copy;
2134
+ len -= to_copy;
2135
+ }
2136
+ }
2137
+
2138
+ return true;
2139
+ }
2140
+
2141
+ inline void Flush() {}
2142
+ };
2143
+
2144
+ bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
2145
+ const struct iovec* iov, size_t iov_cnt) {
2146
+ ByteArraySource reader(compressed, compressed_length);
2147
+ return RawUncompressToIOVec(&reader, iov, iov_cnt);
2148
+ }
2149
+
2150
+ bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
2151
+ size_t iov_cnt) {
2152
+ SnappyIOVecWriter output(iov, iov_cnt);
2153
+ return InternalUncompress(compressed, &output);
2154
+ }
2155
+
2156
+ // -----------------------------------------------------------------------
2157
+ // Flat array interfaces
2158
+ // -----------------------------------------------------------------------
2159
+
2160
+ // A type that writes to a flat array.
2161
+ // Note that this is not a "ByteSink", but a type that matches the
2162
+ // Writer template argument to SnappyDecompressor::DecompressAllTags().
2163
+ class SnappyArrayWriter {
2164
+ private:
2165
+ char* base_;
2166
+ char* op_;
2167
+ char* op_limit_;
2168
+ // If op < op_limit_min_slop_ then it's safe to unconditionally write
2169
+ // kSlopBytes starting at op.
2170
+ char* op_limit_min_slop_;
2171
+
2172
+ public:
2173
+ inline explicit SnappyArrayWriter(char* dst)
2174
+ : base_(dst),
2175
+ op_(dst),
2176
+ op_limit_(dst),
2177
+ op_limit_min_slop_(dst) {} // Safe default see invariant.
2178
+
2179
+ inline void SetExpectedLength(size_t len) {
2180
+ op_limit_ = op_ + len;
2181
+ // Prevent pointer from being past the buffer.
2182
+ op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, len);
2183
+ }
2184
+
2185
+ inline bool CheckLength() const { return op_ == op_limit_; }
2186
+
2187
+ char* GetOutputPtr() { return op_; }
2188
+ char* GetBase(ptrdiff_t* op_limit_min_slop) {
2189
+ *op_limit_min_slop = op_limit_min_slop_ - base_;
2190
+ return base_;
2191
+ }
2192
+ void SetOutputPtr(char* op) { op_ = op; }
2193
+
2194
+ inline bool Append(const char* ip, size_t len, char** op_p) {
2195
+ char* op = *op_p;
2196
+ const size_t space_left = op_limit_ - op;
2197
+ if (space_left < len) return false;
2198
+ std::memcpy(op, ip, len);
2199
+ *op_p = op + len;
2200
+ return true;
2201
+ }
2202
+
2203
+ inline bool TryFastAppend(const char* ip, size_t available, size_t len,
2204
+ char** op_p) {
2205
+ char* op = *op_p;
2206
+ const size_t space_left = op_limit_ - op;
2207
+ if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
2208
+ // Fast path, used for the majority (about 95%) of invocations.
2209
+ UnalignedCopy128(ip, op);
2210
+ *op_p = op + len;
2211
+ return true;
2212
+ } else {
2213
+ return false;
2214
+ }
2215
+ }
2216
+
2217
+ SNAPPY_ATTRIBUTE_ALWAYS_INLINE
2218
+ inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
2219
+ assert(len > 0);
2220
+ char* const op = *op_p;
2221
+ assert(op >= base_);
2222
+ char* const op_end = op + len;
2223
+
2224
+ // Check if we try to append from before the start of the buffer.
2225
+ if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - base_) < offset))
2226
+ return false;
2227
+
2228
+ if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
2229
+ op >= op_limit_min_slop_ || offset < len)) {
2230
+ if (op_end > op_limit_ || offset == 0) return false;
2231
+ *op_p = IncrementalCopy(op - offset, op, op_end, op_limit_);
2232
+ return true;
2233
+ }
2234
+ std::memmove(op, op - offset, kSlopBytes);
2235
+ *op_p = op_end;
2236
+ return true;
2237
+ }
2238
+ inline size_t Produced() const {
2239
+ assert(op_ >= base_);
2240
+ return op_ - base_;
2241
+ }
2242
+ inline void Flush() {}
2243
+ };
2244
+
2245
+ bool RawUncompress(const char* compressed, size_t compressed_length,
2246
+ char* uncompressed) {
2247
+ ByteArraySource reader(compressed, compressed_length);
2248
+ return RawUncompress(&reader, uncompressed);
2249
+ }
2250
+
2251
+ bool RawUncompress(Source* compressed, char* uncompressed) {
2252
+ SnappyArrayWriter output(uncompressed);
2253
+ return InternalUncompress(compressed, &output);
2254
+ }
2255
+
2256
+ bool Uncompress(const char* compressed, size_t compressed_length,
2257
+ std::string* uncompressed) {
2258
+ size_t ulength;
2259
+ if (!GetUncompressedLength(compressed, compressed_length, &ulength)) {
2260
+ return false;
2261
+ }
2262
+ // On 32-bit builds: max_size() < kuint32max. Check for that instead
2263
+ // of crashing (e.g., consider externally specified compressed data).
2264
+ if (ulength > uncompressed->max_size()) {
2265
+ return false;
2266
+ }
2267
+ STLStringResizeUninitialized(uncompressed, ulength);
2268
+ return RawUncompress(compressed, compressed_length,
2269
+ string_as_array(uncompressed));
2270
+ }
2271
+
2272
+ // A Writer that drops everything on the floor and just does validation
2273
+ class SnappyDecompressionValidator {
2274
+ private:
2275
+ size_t expected_;
2276
+ size_t produced_;
2277
+
2278
+ public:
2279
+ inline SnappyDecompressionValidator() : expected_(0), produced_(0) {}
2280
+ inline void SetExpectedLength(size_t len) { expected_ = len; }
2281
+ size_t GetOutputPtr() { return produced_; }
2282
+ size_t GetBase(ptrdiff_t* op_limit_min_slop) {
2283
+ *op_limit_min_slop = std::numeric_limits<ptrdiff_t>::max() - kSlopBytes + 1;
2284
+ return 1;
2285
+ }
2286
+ void SetOutputPtr(size_t op) { produced_ = op; }
2287
+ inline bool CheckLength() const { return expected_ == produced_; }
2288
+ inline bool Append(const char* ip, size_t len, size_t* produced) {
2289
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2290
+ (void)ip;
2291
+
2292
+ *produced += len;
2293
+ return *produced <= expected_;
2294
+ }
2295
+ inline bool TryFastAppend(const char* ip, size_t available, size_t length,
2296
+ size_t* produced) {
2297
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2298
+ (void)ip;
2299
+ (void)available;
2300
+ (void)length;
2301
+ (void)produced;
2302
+
2303
+ return false;
2304
+ }
2305
+ inline bool AppendFromSelf(size_t offset, size_t len, size_t* produced) {
2306
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
2307
+ // the "offset - 1u" trick.
2308
+ if (*produced <= offset - 1u) return false;
2309
+ *produced += len;
2310
+ return *produced <= expected_;
2311
+ }
2312
+ inline void Flush() {}
2313
+ };
2314
+
2315
+ bool IsValidCompressedBuffer(const char* compressed, size_t compressed_length) {
2316
+ ByteArraySource reader(compressed, compressed_length);
2317
+ SnappyDecompressionValidator writer;
2318
+ return InternalUncompress(&reader, &writer);
2319
+ }
2320
+
2321
+ bool IsValidCompressed(Source* compressed) {
2322
+ SnappyDecompressionValidator writer;
2323
+ return InternalUncompress(compressed, &writer);
2324
+ }
2325
+
2326
+ void RawCompress(const char* input, size_t input_length, char* compressed,
2327
+ size_t* compressed_length) {
2328
+ RawCompress(input, input_length, compressed, compressed_length,
2329
+ CompressionOptions{});
2330
+ }
2331
+
2332
+ void RawCompress(const char* input, size_t input_length, char* compressed,
2333
+ size_t* compressed_length, CompressionOptions options) {
2334
+ ByteArraySource reader(input, input_length);
2335
+ UncheckedByteArraySink writer(compressed);
2336
+ Compress(&reader, &writer, options);
2337
+
2338
+ // Compute how many bytes were added
2339
+ *compressed_length = (writer.CurrentDestination() - compressed);
2340
+ }
2341
+
2342
+ void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
2343
+ char* compressed, size_t* compressed_length) {
2344
+ RawCompressFromIOVec(iov, uncompressed_length, compressed, compressed_length,
2345
+ CompressionOptions{});
2346
+ }
2347
+
2348
+ void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
2349
+ char* compressed, size_t* compressed_length,
2350
+ CompressionOptions options) {
2351
+ SnappyIOVecReader reader(iov, uncompressed_length);
2352
+ UncheckedByteArraySink writer(compressed);
2353
+ Compress(&reader, &writer, options);
2354
+
2355
+ // Compute how many bytes were added.
2356
+ *compressed_length = writer.CurrentDestination() - compressed;
2357
+ }
2358
+
2359
+ size_t Compress(const char* input, size_t input_length,
2360
+ std::string* compressed) {
2361
+ return Compress(input, input_length, compressed, CompressionOptions{});
2362
+ }
2363
+
2364
+ size_t Compress(const char* input, size_t input_length, std::string* compressed,
2365
+ CompressionOptions options) {
2366
+ // Pre-grow the buffer to the max length of the compressed output
2367
+ STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
2368
+
2369
+ size_t compressed_length;
2370
+ RawCompress(input, input_length, string_as_array(compressed),
2371
+ &compressed_length, options);
2372
+ compressed->erase(compressed_length);
2373
+ return compressed_length;
2374
+ }
2375
+
2376
+ size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
2377
+ std::string* compressed) {
2378
+ return CompressFromIOVec(iov, iov_cnt, compressed, CompressionOptions{});
2379
+ }
2380
+
2381
+ size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
2382
+ std::string* compressed, CompressionOptions options) {
2383
+ // Compute the number of bytes to be compressed.
2384
+ size_t uncompressed_length = 0;
2385
+ for (size_t i = 0; i < iov_cnt; ++i) {
2386
+ uncompressed_length += iov[i].iov_len;
2387
+ }
2388
+
2389
+ // Pre-grow the buffer to the max length of the compressed output.
2390
+ STLStringResizeUninitialized(compressed, MaxCompressedLength(
2391
+ uncompressed_length));
2392
+
2393
+ size_t compressed_length;
2394
+ RawCompressFromIOVec(iov, uncompressed_length, string_as_array(compressed),
2395
+ &compressed_length, options);
2396
+ compressed->erase(compressed_length);
2397
+ return compressed_length;
2398
+ }
2399
+
2400
+ // -----------------------------------------------------------------------
2401
+ // Sink interface
2402
+ // -----------------------------------------------------------------------
2403
+
2404
+ // A type that decompresses into a Sink. The template parameter
2405
+ // Allocator must export one method "char* Allocate(int size);", which
2406
+ // allocates a buffer of "size" and appends that to the destination.
2407
+ template <typename Allocator>
2408
+ class SnappyScatteredWriter {
2409
+ Allocator allocator_;
2410
+
2411
+ // We need random access into the data generated so far. Therefore
2412
+ // we keep track of all of the generated data as an array of blocks.
2413
+ // All of the blocks except the last have length kBlockSize.
2414
+ std::vector<char*> blocks_;
2415
+ size_t expected_;
2416
+
2417
+ // Total size of all fully generated blocks so far
2418
+ size_t full_size_;
2419
+
2420
+ // Pointer into current output block
2421
+ char* op_base_; // Base of output block
2422
+ char* op_ptr_; // Pointer to next unfilled byte in block
2423
+ char* op_limit_; // Pointer just past block
2424
+ // If op < op_limit_min_slop_ then it's safe to unconditionally write
2425
+ // kSlopBytes starting at op.
2426
+ char* op_limit_min_slop_;
2427
+
2428
+ inline size_t Size() const { return full_size_ + (op_ptr_ - op_base_); }
2429
+
2430
+ bool SlowAppend(const char* ip, size_t len);
2431
+ bool SlowAppendFromSelf(size_t offset, size_t len);
2432
+
2433
+ public:
2434
+ inline explicit SnappyScatteredWriter(const Allocator& allocator)
2435
+ : allocator_(allocator),
2436
+ full_size_(0),
2437
+ op_base_(NULL),
2438
+ op_ptr_(NULL),
2439
+ op_limit_(NULL),
2440
+ op_limit_min_slop_(NULL) {}
2441
+ char* GetOutputPtr() { return op_ptr_; }
2442
+ char* GetBase(ptrdiff_t* op_limit_min_slop) {
2443
+ *op_limit_min_slop = op_limit_min_slop_ - op_base_;
2444
+ return op_base_;
2445
+ }
2446
+ void SetOutputPtr(char* op) { op_ptr_ = op; }
2447
+
2448
+ inline void SetExpectedLength(size_t len) {
2449
+ assert(blocks_.empty());
2450
+ expected_ = len;
2451
+ }
2452
+
2453
+ inline bool CheckLength() const { return Size() == expected_; }
2454
+
2455
+ // Return the number of bytes actually uncompressed so far
2456
+ inline size_t Produced() const { return Size(); }
2457
+
2458
+ inline bool Append(const char* ip, size_t len, char** op_p) {
2459
+ char* op = *op_p;
2460
+ size_t avail = op_limit_ - op;
2461
+ if (len <= avail) {
2462
+ // Fast path
2463
+ std::memcpy(op, ip, len);
2464
+ *op_p = op + len;
2465
+ return true;
2466
+ } else {
2467
+ op_ptr_ = op;
2468
+ bool res = SlowAppend(ip, len);
2469
+ *op_p = op_ptr_;
2470
+ return res;
2471
+ }
2472
+ }
2473
+
2474
+ inline bool TryFastAppend(const char* ip, size_t available, size_t length,
2475
+ char** op_p) {
2476
+ char* op = *op_p;
2477
+ const int space_left = op_limit_ - op;
2478
+ if (length <= 16 && available >= 16 + kMaximumTagLength &&
2479
+ space_left >= 16) {
2480
+ // Fast path, used for the majority (about 95%) of invocations.
2481
+ UnalignedCopy128(ip, op);
2482
+ *op_p = op + length;
2483
+ return true;
2484
+ } else {
2485
+ return false;
2486
+ }
2487
+ }
2488
+
2489
+ inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
2490
+ char* op = *op_p;
2491
+ assert(op >= op_base_);
2492
+ // Check if we try to append from before the start of the buffer.
2493
+ if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
2494
+ static_cast<size_t>(op - op_base_) < offset ||
2495
+ op >= op_limit_min_slop_ || offset < len)) {
2496
+ if (offset == 0) return false;
2497
+ if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - op_base_) < offset ||
2498
+ op + len > op_limit_)) {
2499
+ op_ptr_ = op;
2500
+ bool res = SlowAppendFromSelf(offset, len);
2501
+ *op_p = op_ptr_;
2502
+ return res;
2503
+ }
2504
+ *op_p = IncrementalCopy(op - offset, op, op + len, op_limit_);
2505
+ return true;
2506
+ }
2507
+ // Fast path
2508
+ char* const op_end = op + len;
2509
+ std::memmove(op, op - offset, kSlopBytes);
2510
+ *op_p = op_end;
2511
+ return true;
2512
+ }
2513
+
2514
+ // Called at the end of the decompress. We ask the allocator
2515
+ // write all blocks to the sink.
2516
+ inline void Flush() { allocator_.Flush(Produced()); }
2517
+ };
2518
+
2519
+ template <typename Allocator>
2520
+ bool SnappyScatteredWriter<Allocator>::SlowAppend(const char* ip, size_t len) {
2521
+ size_t avail = op_limit_ - op_ptr_;
2522
+ while (len > avail) {
2523
+ // Completely fill this block
2524
+ std::memcpy(op_ptr_, ip, avail);
2525
+ op_ptr_ += avail;
2526
+ assert(op_limit_ - op_ptr_ == 0);
2527
+ full_size_ += (op_ptr_ - op_base_);
2528
+ len -= avail;
2529
+ ip += avail;
2530
+
2531
+ // Bounds check
2532
+ if (full_size_ + len > expected_) return false;
2533
+
2534
+ // Make new block
2535
+ size_t bsize = std::min<size_t>(kBlockSize, expected_ - full_size_);
2536
+ op_base_ = allocator_.Allocate(bsize);
2537
+ op_ptr_ = op_base_;
2538
+ op_limit_ = op_base_ + bsize;
2539
+ op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, bsize);
2540
+
2541
+ blocks_.push_back(op_base_);
2542
+ avail = bsize;
2543
+ }
2544
+
2545
+ std::memcpy(op_ptr_, ip, len);
2546
+ op_ptr_ += len;
2547
+ return true;
2548
+ }
2549
+
2550
+ template <typename Allocator>
2551
+ bool SnappyScatteredWriter<Allocator>::SlowAppendFromSelf(size_t offset,
2552
+ size_t len) {
2553
+ // Overflow check
2554
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
2555
+ // the "offset - 1u" trick.
2556
+ const size_t cur = Size();
2557
+ if (offset - 1u >= cur) return false;
2558
+ if (expected_ - cur < len) return false;
2559
+
2560
+ // Currently we shouldn't ever hit this path because Compress() chops the
2561
+ // input into blocks and does not create cross-block copies. However, it is
2562
+ // nice if we do not rely on that, since we can get better compression if we
2563
+ // allow cross-block copies and thus might want to change the compressor in
2564
+ // the future.
2565
+ // TODO Replace this with a properly optimized path. This is not
2566
+ // triggered right now. But this is so super slow, that it would regress
2567
+ // performance unacceptably if triggered.
2568
+ size_t src = cur - offset;
2569
+ char* op = op_ptr_;
2570
+ while (len-- > 0) {
2571
+ char c = blocks_[src >> kBlockLog][src & (kBlockSize - 1)];
2572
+ if (!Append(&c, 1, &op)) {
2573
+ op_ptr_ = op;
2574
+ return false;
2575
+ }
2576
+ src++;
2577
+ }
2578
+ op_ptr_ = op;
2579
+ return true;
2580
+ }
2581
+
2582
+ class SnappySinkAllocator {
2583
+ public:
2584
+ explicit SnappySinkAllocator(Sink* dest) : dest_(dest) {}
2585
+
2586
+ char* Allocate(int size) {
2587
+ Datablock block(new char[size], size);
2588
+ blocks_.push_back(block);
2589
+ return block.data;
2590
+ }
2591
+
2592
+ // We flush only at the end, because the writer wants
2593
+ // random access to the blocks and once we hand the
2594
+ // block over to the sink, we can't access it anymore.
2595
+ // Also we don't write more than has been actually written
2596
+ // to the blocks.
2597
+ void Flush(size_t size) {
2598
+ size_t size_written = 0;
2599
+ for (Datablock& block : blocks_) {
2600
+ size_t block_size = std::min<size_t>(block.size, size - size_written);
2601
+ dest_->AppendAndTakeOwnership(block.data, block_size,
2602
+ &SnappySinkAllocator::Deleter, NULL);
2603
+ size_written += block_size;
2604
+ }
2605
+ blocks_.clear();
2606
+ }
2607
+
2608
+ private:
2609
+ struct Datablock {
2610
+ char* data;
2611
+ size_t size;
2612
+ Datablock(char* p, size_t s) : data(p), size(s) {}
2613
+ };
2614
+
2615
+ static void Deleter(void* arg, const char* bytes, size_t size) {
2616
+ // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2617
+ (void)arg;
2618
+ (void)size;
2619
+
2620
+ delete[] bytes;
2621
+ }
2622
+
2623
+ Sink* dest_;
2624
+ std::vector<Datablock> blocks_;
2625
+
2626
+ // Note: copying this object is allowed
2627
+ };
2628
+
2629
+ size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) {
2630
+ SnappySinkAllocator allocator(uncompressed);
2631
+ SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
2632
+ InternalUncompress(compressed, &writer);
2633
+ return writer.Produced();
2634
+ }
2635
+
2636
+ bool Uncompress(Source* compressed, Sink* uncompressed) {
2637
+ // Read the uncompressed length from the front of the compressed input
2638
+ SnappyDecompressor decompressor(compressed);
2639
+ uint32_t uncompressed_len = 0;
2640
+ if (!decompressor.ReadUncompressedLength(&uncompressed_len)) {
2641
+ return false;
2642
+ }
2643
+
2644
+ char c;
2645
+ size_t allocated_size;
2646
+ char* buf = uncompressed->GetAppendBufferVariable(1, uncompressed_len, &c, 1,
2647
+ &allocated_size);
2648
+
2649
+ const size_t compressed_len = compressed->Available();
2650
+ // If we can get a flat buffer, then use it, otherwise do block by block
2651
+ // uncompression
2652
+ if (allocated_size >= uncompressed_len) {
2653
+ SnappyArrayWriter writer(buf);
2654
+ bool result = InternalUncompressAllTags(&decompressor, &writer,
2655
+ compressed_len, uncompressed_len);
2656
+ uncompressed->Append(buf, writer.Produced());
2657
+ return result;
2658
+ } else {
2659
+ SnappySinkAllocator allocator(uncompressed);
2660
+ SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
2661
+ return InternalUncompressAllTags(&decompressor, &writer, compressed_len,
2662
+ uncompressed_len);
2663
+ }
2664
+ }
2665
+
2666
+ } // namespace snappy