Coverage Report

Created: 2025-11-03 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/snappy/snappy.cc
Line
Count
Source
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
0
inline constexpr int16_t MakeEntry(int16_t len, int16_t offset) {
117
0
  return len - (offset << 8);
118
0
}
119
120
0
inline constexpr int16_t LengthMinusOffset(int data, int type) {
121
0
  return type == 3   ? 0xFF                    // copy-4 (or type == 3)
122
0
         : type == 2 ? MakeEntry(data + 1, 0)  // copy-2
123
0
         : type == 1 ? MakeEntry((data & 7) + 4, data >> 3)  // copy-1
124
0
         : data < 60 ? MakeEntry(data + 1, 1)  // note spurious offset.
125
0
                     : 0xFF;                   // long literal
126
0
}
127
128
0
inline constexpr int16_t LengthMinusOffset(uint8_t tag) {
129
0
  return LengthMinusOffset(tag >> 2, tag & 3);
130
0
}
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
0
constexpr std::array<int16_t, 256> MakeTable(index_sequence<seq...>) {
143
0
  return std::array<int16_t, 256>{LengthMinusOffset(seq)...};
144
0
}
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
13.0M
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
13.0M
  constexpr uint32_t kMagic = 0x1e35a7bd;
173
13.0M
  const uint32_t hash = (kMagic * bytes) >> (31 - kMaxHashTableBits);
174
13.0M
#endif
175
13.0M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
176
13.0M
                                     (hash & mask));
177
13.0M
}
178
179
inline uint16_t* TableEntry4ByteMatch(uint16_t* table, uint32_t bytes,
180
31.8M
                                      uint32_t mask) {
181
31.8M
  constexpr uint32_t kMagic = 2654435761U;
182
31.8M
  const uint32_t hash = (kMagic * bytes) >> (32 - kMaxHashTableBits);
183
31.8M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
184
31.8M
                                     (hash & mask));
185
31.8M
}
186
187
inline uint16_t* TableEntry8ByteMatch(uint16_t* table, uint64_t bytes,
188
41.4M
                                      uint32_t mask) {
189
41.4M
  constexpr uint64_t kMagic = 58295818150454627ULL;
190
41.4M
  const uint32_t hash = (kMagic * bytes) >> (64 - kMaxHashTableBits);
191
41.4M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
192
41.4M
                                     (hash & mask));
193
41.4M
}
194
195
}  // namespace
196
197
23.7k
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
23.7k
  return 32 + source_bytes + source_bytes / 6;
219
23.7k
}
220
221
namespace {
222
223
120k
void UnalignedCopy64(const void* src, void* dst) {
224
120k
  char tmp[8];
225
120k
  std::memcpy(tmp, src, 8);
226
120k
  std::memcpy(dst, tmp, 8);
227
120k
}
228
229
2.22M
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
2.22M
  char tmp[16];
234
2.22M
  std::memcpy(tmp, src, 16);
235
2.22M
  std::memcpy(dst, tmp, 16);
236
2.22M
}
237
238
template <bool use_16bytes_chunk>
239
39.9k
inline void ConditionalUnalignedCopy128(const char* src, char* dst) {
240
39.9k
  if (use_16bytes_chunk) {
241
0
    UnalignedCopy128(src, dst);
242
39.9k
  } else {
243
39.9k
    UnalignedCopy64(src, dst);
244
39.9k
    UnalignedCopy64(src + 8, dst + 8);
245
39.9k
  }
246
39.9k
}
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
1.45k
                                 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
1.45k
#ifdef __clang__
265
1.45k
#pragma clang loop unroll(disable)
266
1.45k
#endif
267
4.41k
  while (op < op_limit) {
268
2.95k
    *op++ = *src++;
269
2.95k
  }
270
1.45k
  return op_limit;
271
1.45k
}
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
1.47M
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
1.47M
  if (SNAPPY_PREDICT_TRUE(offset < 16)) {
395
1.46M
    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
24.9M
    for (int i = 0; i < 16; i++) dst[i] = (dst - offset)[i];
399
    // Find a multiple of pattern >= 16.
400
1.46M
    static std::array<uint8_t, 16> pattern_sizes = []() {
401
1
      std::array<uint8_t, 16> res;
402
16
      for (int i = 1; i < 16; i++) res[i] = (16 / i + 1) * i;
403
1
      return res;
404
1
    }();
405
1.46M
    offset = pattern_sizes[offset];
406
5.87M
    for (int i = 1; i < 4; i++) {
407
4.40M
      std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
408
4.40M
    }
409
1.46M
    return true;
410
1.46M
  }
411
9.27k
#endif  // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
412
413
  // Very rare.
414
46.3k
  for (int i = 0; i < 4; i++) {
415
37.1k
    std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
416
37.1k
  }
417
9.27k
  return true;
418
1.47M
}
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
19.6k
                             char* const buf_limit) {
425
#if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
426
  constexpr int big_pattern_size_lower_bound = 16;
427
#else
428
19.6k
  constexpr int big_pattern_size_lower_bound = 8;
429
19.6k
#endif
430
431
  // Terminology:
432
  //
433
  // slop = buf_limit - op
434
  // pat  = op - src
435
  // len  = op_limit - op
436
19.6k
  assert(src < op);
437
19.6k
  assert(op < op_limit);
438
19.6k
  assert(op_limit <= buf_limit);
439
  // NOTE: The copy tags use 3 or 6 bits to store the copy length, so len <= 64.
440
19.6k
  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
19.6k
  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
19.6k
  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
15.1k
    if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) {
545
54.2k
      while (pattern_size < 8) {
546
39.1k
        UnalignedCopy64(src, op);
547
39.1k
        op += pattern_size;
548
39.1k
        pattern_size *= 2;
549
39.1k
      }
550
15.0k
      if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
551
15.0k
    } else {
552
104
      return IncrementalCopySlow(src, op, op_limit);
553
104
    }
554
15.1k
#endif  // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
555
15.1k
  }
556
19.6k
  assert(pattern_size >= big_pattern_size_lower_bound);
557
15.2k
  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
15.2k
  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
13.4k
    ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
572
13.4k
    if (op + 16 < op_limit) {
573
8.69k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 16, op + 16);
574
8.69k
    }
575
13.4k
    if (op + 32 < op_limit) {
576
8.15k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 32, op + 32);
577
8.15k
    }
578
13.4k
    if (op + 48 < op_limit) {
579
7.81k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 48, op + 48);
580
7.81k
    }
581
13.4k
    return op_limit;
582
13.4k
  }
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
1.80k
#ifdef __clang__
591
1.80k
#pragma clang loop unroll(disable)
592
1.80k
#endif
593
3.69k
  for (char* op_end = buf_limit - 16; op < op_end; op += 16, src += 16) {
594
1.88k
    ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
595
1.88k
  }
596
1.80k
  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
1.35k
  if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) {
601
1.08k
    UnalignedCopy64(src, op);
602
1.08k
    src += 8;
603
1.08k
    op += 8;
604
1.08k
  }
605
1.35k
  return IncrementalCopySlow(src, op, op_limit);
606
1.80k
}
607
608
}  // namespace
609
610
template <bool allow_fast_path>
611
1.35M
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
1.35M
  assert(len > 0);  // Zero-length literals are disallowed
623
1.35M
  int n = len - 1;
624
1.35M
  if (allow_fast_path && len <= 16) {
625
    // Fits in tag byte
626
1.16M
    *op++ = LITERAL | (n << 2);
627
628
1.16M
    UnalignedCopy128(literal, op);
629
1.16M
    return op + len;
630
1.16M
  }
631
632
188k
  if (n < 60) {
633
    // Fits in tag byte
634
130k
    *op++ = LITERAL | (n << 2);
635
130k
  } else {
636
57.8k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
57.8k
    assert(count >= 1);
638
57.8k
    assert(count <= 4);
639
57.8k
    *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
57.8k
    LittleEndian::Store32(op, n);
645
57.8k
    op += count;
646
57.8k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
188k
  if (allow_fast_path) {
649
181k
    char* destination = op;
650
181k
    const char* source = literal;
651
181k
    const char* end = destination + len;
652
2.83M
    do {
653
2.83M
      std::memcpy(destination, source, 16);
654
2.83M
      destination += 16;
655
2.83M
      source += 16;
656
2.83M
    } while (destination < end);
657
181k
  } else {
658
6.23k
    std::memcpy(op, literal, len);
659
6.23k
  }
660
188k
  return op + len;
661
188k
}
snappy.cc:char* snappy::EmitLiteral<true>(char*, char const*, int)
Line
Count
Source
611
1.34M
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
1.34M
  assert(len > 0);  // Zero-length literals are disallowed
623
1.34M
  int n = len - 1;
624
1.34M
  if (allow_fast_path && len <= 16) {
625
    // Fits in tag byte
626
1.16M
    *op++ = LITERAL | (n << 2);
627
628
1.16M
    UnalignedCopy128(literal, op);
629
1.16M
    return op + len;
630
1.16M
  }
631
632
181k
  if (n < 60) {
633
    // Fits in tag byte
634
126k
    *op++ = LITERAL | (n << 2);
635
126k
  } else {
636
55.7k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
55.7k
    assert(count >= 1);
638
55.7k
    assert(count <= 4);
639
55.7k
    *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
55.7k
    LittleEndian::Store32(op, n);
645
55.7k
    op += count;
646
55.7k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
181k
  if (allow_fast_path) {
649
181k
    char* destination = op;
650
181k
    const char* source = literal;
651
181k
    const char* end = destination + len;
652
2.83M
    do {
653
2.83M
      std::memcpy(destination, source, 16);
654
2.83M
      destination += 16;
655
2.83M
      source += 16;
656
2.83M
    } while (destination < end);
657
181k
  } else {
658
0
    std::memcpy(op, literal, len);
659
0
  }
660
181k
  return op + len;
661
181k
}
snappy.cc:char* snappy::EmitLiteral<false>(char*, char const*, int)
Line
Count
Source
611
6.23k
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
6.23k
  assert(len > 0);  // Zero-length literals are disallowed
623
6.23k
  int n = len - 1;
624
6.23k
  if (allow_fast_path && len <= 16) {
625
    // Fits in tag byte
626
0
    *op++ = LITERAL | (n << 2);
627
628
0
    UnalignedCopy128(literal, op);
629
0
    return op + len;
630
0
  }
631
632
6.23k
  if (n < 60) {
633
    // Fits in tag byte
634
4.20k
    *op++ = LITERAL | (n << 2);
635
4.20k
  } else {
636
2.03k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
2.03k
    assert(count >= 1);
638
2.03k
    assert(count <= 4);
639
2.03k
    *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
2.03k
    LittleEndian::Store32(op, n);
645
2.03k
    op += count;
646
2.03k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
6.23k
  if (allow_fast_path) {
649
0
    char* destination = op;
650
0
    const char* source = literal;
651
0
    const char* end = destination + len;
652
0
    do {
653
0
      std::memcpy(destination, source, 16);
654
0
      destination += 16;
655
0
      source += 16;
656
0
    } while (destination < end);
657
6.23k
  } else {
658
6.23k
    std::memcpy(op, literal, len);
659
6.23k
  }
660
6.23k
  return op + len;
661
6.23k
}
662
663
template <bool len_less_than_12>
664
8.79M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
8.79M
  assert(len <= 64);
666
8.79M
  assert(len >= 4);
667
8.79M
  assert(offset < 65536);
668
8.79M
  assert(len_less_than_12 == (len < 12));
669
670
8.79M
  if (len_less_than_12) {
671
5.16M
    uint32_t u = (len << 2) + (offset << 8);
672
5.16M
    uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
5.16M
    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
5.16M
    u += offset < 2048 ? copy1 : copy2;
680
5.16M
    LittleEndian::Store32(op, u);
681
5.16M
    op += offset < 2048 ? 2 : 3;
682
5.16M
  } 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
3.62M
    uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
3.62M
    LittleEndian::Store32(op, u);
687
3.62M
    op += 3;
688
3.62M
  }
689
8.79M
  return op;
690
8.79M
}
snappy.cc:char* snappy::EmitCopyAtMost64<true>(char*, unsigned long, unsigned long)
Line
Count
Source
664
5.16M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
5.16M
  assert(len <= 64);
666
5.16M
  assert(len >= 4);
667
5.16M
  assert(offset < 65536);
668
5.16M
  assert(len_less_than_12 == (len < 12));
669
670
5.16M
  if (len_less_than_12) {
671
5.16M
    uint32_t u = (len << 2) + (offset << 8);
672
5.16M
    uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
5.16M
    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
5.16M
    u += offset < 2048 ? copy1 : copy2;
680
5.16M
    LittleEndian::Store32(op, u);
681
5.16M
    op += offset < 2048 ? 2 : 3;
682
5.16M
  } 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
0
    uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
0
    LittleEndian::Store32(op, u);
687
0
    op += 3;
688
0
  }
689
5.16M
  return op;
690
5.16M
}
snappy.cc:char* snappy::EmitCopyAtMost64<false>(char*, unsigned long, unsigned long)
Line
Count
Source
664
3.62M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
3.62M
  assert(len <= 64);
666
3.62M
  assert(len >= 4);
667
3.62M
  assert(offset < 65536);
668
3.62M
  assert(len_less_than_12 == (len < 12));
669
670
3.62M
  if (len_less_than_12) {
671
0
    uint32_t u = (len << 2) + (offset << 8);
672
0
    uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
0
    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
0
    u += offset < 2048 ? copy1 : copy2;
680
0
    LittleEndian::Store32(op, u);
681
0
    op += offset < 2048 ? 2 : 3;
682
3.62M
  } 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
3.62M
    uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
3.62M
    LittleEndian::Store32(op, u);
687
3.62M
    op += 3;
688
3.62M
  }
689
3.62M
  return op;
690
3.62M
}
691
692
template <bool len_less_than_12>
693
6.46M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
6.46M
  assert(len_less_than_12 == (len < 12));
695
6.46M
  if (len_less_than_12) {
696
5.13M
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
5.13M
  } 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
3.65M
    while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
2.32M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
2.32M
      len -= 64;
705
2.32M
    }
706
707
    // One or two copies will now finish the job.
708
1.32M
    if (len > 64) {
709
9.14k
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
9.14k
      len -= 60;
711
9.14k
    }
712
713
    // Emit remainder.
714
1.32M
    if (len < 12) {
715
31.9k
      op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
1.29M
    } else {
717
1.29M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
1.29M
    }
719
1.32M
    return op;
720
1.32M
  }
721
6.46M
}
snappy.cc:char* snappy::EmitCopy<true>(char*, unsigned long, unsigned long)
Line
Count
Source
693
5.13M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
5.13M
  assert(len_less_than_12 == (len < 12));
695
5.13M
  if (len_less_than_12) {
696
5.13M
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
5.13M
  } 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
0
    while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
0
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
0
      len -= 64;
705
0
    }
706
707
    // One or two copies will now finish the job.
708
0
    if (len > 64) {
709
0
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
0
      len -= 60;
711
0
    }
712
713
    // Emit remainder.
714
0
    if (len < 12) {
715
0
      op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
0
    } else {
717
0
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
0
    }
719
0
    return op;
720
0
  }
721
5.13M
}
snappy.cc:char* snappy::EmitCopy<false>(char*, unsigned long, unsigned long)
Line
Count
Source
693
1.32M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
1.32M
  assert(len_less_than_12 == (len < 12));
695
1.32M
  if (len_less_than_12) {
696
0
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
1.32M
  } 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
3.65M
    while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
2.32M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
2.32M
      len -= 64;
705
2.32M
    }
706
707
    // One or two copies will now finish the job.
708
1.32M
    if (len > 64) {
709
9.14k
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
9.14k
      len -= 60;
711
9.14k
    }
712
713
    // Emit remainder.
714
1.32M
    if (len < 12) {
715
31.9k
      op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
1.29M
    } else {
717
1.29M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
1.29M
    }
719
1.32M
    return op;
720
1.32M
  }
721
1.32M
}
722
723
4.83k
bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
724
4.83k
  uint32_t v = 0;
725
4.83k
  const char* limit = start + n;
726
4.83k
  if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
727
4.83k
    *result = v;
728
4.83k
    return true;
729
4.83k
  } else {
730
0
    return false;
731
0
  }
732
4.83k
}
733
734
namespace {
735
14.0k
uint32_t CalculateTableSize(uint32_t input_size) {
736
14.0k
  static_assert(
737
14.0k
      kMaxHashTableSize >= kMinHashTableSize,
738
14.0k
      "kMaxHashTableSize should be greater or equal to kMinHashTableSize.");
739
14.0k
  if (input_size > kMaxHashTableSize) {
740
5.69k
    return kMaxHashTableSize;
741
5.69k
  }
742
8.33k
  if (input_size < kMinHashTableSize) {
743
5.81k
    return kMinHashTableSize;
744
5.81k
  }
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
2.52k
  return 2u << Bits::Log2Floor(input_size - 1);
748
8.33k
}
749
}  // namespace
750
751
namespace internal {
752
4.83k
WorkingMemory::WorkingMemory(size_t input_size) {
753
4.83k
  const size_t max_fragment_size = std::min(input_size, kBlockSize);
754
4.83k
  const size_t table_size = CalculateTableSize(max_fragment_size);
755
4.83k
  size_ = table_size * sizeof(*table_) + max_fragment_size +
756
4.83k
          MaxCompressedLength(max_fragment_size);
757
4.83k
  mem_ = std::allocator<char>().allocate(size_);
758
4.83k
  table_ = reinterpret_cast<uint16_t*>(mem_);
759
4.83k
  input_ = mem_ + table_size * sizeof(*table_);
760
4.83k
  output_ = input_ + max_fragment_size;
761
4.83k
}
762
763
4.83k
WorkingMemory::~WorkingMemory() {
764
4.83k
  std::allocator<char>().deallocate(mem_, size_);
765
4.83k
}
766
767
uint16_t* WorkingMemory::GetHashTable(size_t fragment_size,
768
9.20k
                                      int* table_size) const {
769
9.20k
  const size_t htsize = CalculateTableSize(fragment_size);
770
9.20k
  memset(table_, 0, htsize * sizeof(*table_));
771
9.20k
  *table_size = htsize;
772
9.20k
  return table_;
773
9.20k
}
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
4.60k
                       uint16_t* table, const int table_size) {
790
  // "ip" is the input pointer, and "op" is the output pointer.
791
4.60k
  const char* ip = input;
792
4.60k
  assert(input_size <= kBlockSize);
793
4.60k
  assert((table_size & (table_size - 1)) == 0);  // table must be power of two
794
4.60k
  const uint32_t mask = 2 * (table_size - 1);
795
4.60k
  const char* ip_end = input + input_size;
796
4.60k
  const char* base_ip = ip;
797
798
4.60k
  const size_t kInputMarginBytes = 15;
799
4.60k
  if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
800
4.57k
    const char* ip_limit = input + input_size - kInputMarginBytes;
801
802
1.12M
    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
1.12M
      const char* next_emit = ip++;
806
1.12M
      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
1.12M
      uint32_t skip = 32;
833
834
1.12M
      const char* candidate;
835
1.12M
      if (ip_limit - ip >= 16) {
836
1.12M
        auto delta = ip - base_ip;
837
1.74M
        for (int j = 0; j < 4; ++j) {
838
5.14M
          for (int k = 0; k < 4; ++k) {
839
4.52M
            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
4.52M
            uint32_t dword = i == 0 ? preload : static_cast<uint32_t>(data);
844
4.52M
            assert(dword == LittleEndian::Load32(ip + i));
845
4.52M
            uint16_t* table_entry = TableEntry(table, dword, mask);
846
4.52M
            candidate = base_ip + *table_entry;
847
4.52M
            assert(candidate >= base_ip);
848
4.52M
            assert(candidate < ip + i);
849
4.52M
            *table_entry = delta + i;
850
4.52M
            if (SNAPPY_PREDICT_FALSE(LittleEndian::Load32(candidate) == dword)) {
851
1.05M
              *op = LITERAL | (i << 2);
852
1.05M
              UnalignedCopy128(next_emit, op + 1);
853
1.05M
              ip += i;
854
1.05M
              op = op + i + 2;
855
1.05M
              goto emit_match;
856
1.05M
            }
857
3.47M
            data >>= 8;
858
3.47M
          }
859
623k
          data = LittleEndian::Load64(ip + 4 * j + 4);
860
623k
        }
861
72.5k
        ip += 16;
862
72.5k
        skip += 16;
863
72.5k
      }
864
2.04M
      while (true) {
865
2.04M
        assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
866
2.04M
        uint16_t* table_entry = TableEntry(table, data, mask);
867
2.04M
        uint32_t bytes_between_hash_lookups = skip >> 5;
868
2.04M
        skip += bytes_between_hash_lookups;
869
2.04M
        const char* next_ip = ip + bytes_between_hash_lookups;
870
2.04M
        if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
871
1.70k
          ip = next_emit;
872
1.70k
          goto emit_remainder;
873
1.70k
        }
874
2.04M
        candidate = base_ip + *table_entry;
875
2.04M
        assert(candidate >= base_ip);
876
2.04M
        assert(candidate < ip);
877
878
2.04M
        *table_entry = ip - base_ip;
879
2.04M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
880
2.04M
                                LittleEndian::Load32(candidate))) {
881
72.7k
          break;
882
72.7k
        }
883
1.96M
        data = LittleEndian::Load32(next_ip);
884
1.96M
        ip = next_ip;
885
1.96M
      }
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
74.4k
      assert(next_emit + 16 <= ip_end);
891
72.7k
      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
1.12M
    emit_match:
902
3.25M
      do {
903
        // We have a 4-byte match at ip, and no need to emit any
904
        // "literal bytes" prior to ip.
905
3.25M
        const char* base = ip;
906
3.25M
        std::pair<size_t, bool> p =
907
3.25M
            FindMatchLength(candidate + 4, ip + 4, ip_end, &data);
908
3.25M
        size_t matched = 4 + p.first;
909
3.25M
        ip += matched;
910
3.25M
        size_t offset = base - candidate;
911
3.25M
        assert(0 == memcmp(base, candidate, matched));
912
3.25M
        if (p.second) {
913
2.63M
          op = EmitCopy</*len_less_than_12=*/true>(op, offset, matched);
914
2.63M
        } else {
915
627k
          op = EmitCopy</*len_less_than_12=*/false>(op, offset, matched);
916
627k
        }
917
3.25M
        if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
918
2.86k
          goto emit_remainder;
919
2.86k
        }
920
        // Expect 5 bytes to match
921
3.25M
        assert((data & 0xFFFFFFFFFF) ==
922
3.25M
               (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
3.25M
        *TableEntry(table, LittleEndian::Load32(ip - 1), mask) =
927
3.25M
            ip - base_ip - 1;
928
3.25M
        uint16_t* table_entry = TableEntry(table, data, mask);
929
3.25M
        candidate = base_ip + *table_entry;
930
3.25M
        *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
3.25M
      } 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
1.12M
      preload = data >> 8;
945
1.12M
    }
946
4.57k
  }
947
948
4.60k
emit_remainder:
949
  // Emit the remaining bytes as a literal
950
4.60k
  if (ip < ip_end) {
951
3.21k
    op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
952
3.21k
  }
953
954
4.60k
  return op;
955
4.60k
}
956
957
char* CompressFragmentDoubleHash(const char* input, size_t input_size, char* op,
958
                                 uint16_t* table, const int table_size,
959
4.60k
                                 uint16_t* table2, const int table_size2) {
960
4.60k
  (void)table_size2;
961
4.60k
  assert(table_size == table_size2);
962
  // "ip" is the input pointer, and "op" is the output pointer.
963
4.60k
  const char* ip = input;
964
4.60k
  assert(input_size <= kBlockSize);
965
4.60k
  assert((table_size & (table_size - 1)) == 0);  // table must be power of two
966
4.60k
  const uint32_t mask = 2 * (table_size - 1);
967
4.60k
  const char* ip_end = input + input_size;
968
4.60k
  const char* base_ip = ip;
969
970
4.60k
  const size_t kInputMarginBytes = 15;
971
4.60k
  if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
972
4.57k
    const char* ip_limit = input + input_size - kInputMarginBytes;
973
974
1.28M
    for (;;) {
975
1.28M
      const char* next_emit = ip++;
976
1.28M
      uint64_t data = LittleEndian::Load64(ip);
977
1.28M
      uint32_t skip = 512;
978
979
1.28M
      const char* candidate;
980
1.28M
      uint32_t candidate_length;
981
21.9M
      while (true) {
982
21.9M
        assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
983
21.9M
        uint16_t* table_entry2 = TableEntry8ByteMatch(table2, data, mask);
984
21.9M
        uint32_t bytes_between_hash_lookups = skip >> 9;
985
21.9M
        skip++;
986
21.9M
        const char* next_ip = ip + bytes_between_hash_lookups;
987
21.9M
        if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
988
1.40k
          ip = next_emit;
989
1.40k
          goto emit_remainder;
990
1.40k
        }
991
21.9M
        candidate = base_ip + *table_entry2;
992
21.9M
        assert(candidate >= base_ip);
993
21.9M
        assert(candidate < ip);
994
995
21.9M
        *table_entry2 = ip - base_ip;
996
21.9M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
997
21.9M
                                LittleEndian::Load32(candidate))) {
998
401k
          candidate_length =
999
401k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1000
401k
          break;
1001
401k
        }
1002
1003
21.5M
        uint16_t* table_entry = TableEntry4ByteMatch(table, data, mask);
1004
21.5M
        candidate = base_ip + *table_entry;
1005
21.5M
        assert(candidate >= base_ip);
1006
21.5M
        assert(candidate < ip);
1007
1008
21.5M
        *table_entry = ip - base_ip;
1009
21.5M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
1010
21.5M
                                LittleEndian::Load32(candidate))) {
1011
882k
          candidate_length =
1012
882k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1013
882k
          table_entry2 =
1014
882k
              TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask);
1015
882k
          auto candidate2 = base_ip + *table_entry2;
1016
882k
          size_t candidate_length2 =
1017
882k
              FindMatchLengthPlain(candidate2, ip + 1, ip_end);
1018
882k
          if (candidate_length2 > candidate_length) {
1019
33.0k
            *table_entry2 = ip - base_ip;
1020
33.0k
            candidate = candidate2;
1021
33.0k
            candidate_length = candidate_length2;
1022
33.0k
            ++ip;
1023
33.0k
          }
1024
882k
          break;
1025
882k
        }
1026
20.6M
        data = LittleEndian::Load64(next_ip);
1027
20.6M
        ip = next_ip;
1028
20.6M
      }
1029
      // Backtrack to the point it matches fully.
1030
1.40M
      while (ip > next_emit && candidate > base_ip &&
1031
1.38M
             *(ip - 1) == *(candidate - 1)) {
1032
123k
        --ip;
1033
123k
        --candidate;
1034
123k
        ++candidate_length;
1035
123k
      }
1036
1.28M
      *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask) =
1037
1.28M
          ip - base_ip + 1;
1038
1.28M
      *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 2), mask) =
1039
1.28M
          ip - base_ip + 2;
1040
1.28M
      *TableEntry4ByteMatch(table, LittleEndian::Load32(ip + 1), mask) =
1041
1.28M
          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
1.28M
      assert(next_emit + 16 <= ip_end);
1047
1.28M
      if (ip - next_emit > 0) {
1048
1.27M
        op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit,
1049
1.27M
                                                   ip - next_emit);
1050
1.27M
      }
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
3.20M
      do {
1060
        // We have a 4-byte match at ip, and no need to emit any
1061
        // "literal bytes" prior to ip.
1062
3.20M
        const char* base = ip;
1063
3.20M
        ip += candidate_length;
1064
3.20M
        size_t offset = base - candidate;
1065
3.20M
        if (candidate_length < 12) {
1066
2.50M
          op =
1067
2.50M
              EmitCopy</*len_less_than_12=*/true>(op, offset, candidate_length);
1068
2.50M
        } else {
1069
698k
          op = EmitCopy</*len_less_than_12=*/false>(op, offset,
1070
698k
                                                    candidate_length);
1071
698k
        }
1072
3.20M
        if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
1073
3.16k
          goto emit_remainder;
1074
3.16k
        }
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
3.20M
        if (ip - base_ip > 7) {
1079
3.19M
          *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 7), mask) =
1080
3.19M
              ip - base_ip - 7;
1081
3.19M
          *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 4), mask) =
1082
3.19M
              ip - base_ip - 4;
1083
3.19M
        }
1084
3.20M
        *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 3), mask) =
1085
3.20M
            ip - base_ip - 3;
1086
3.20M
        *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 2), mask) =
1087
3.20M
            ip - base_ip - 2;
1088
3.20M
        *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 2), mask) =
1089
3.20M
            ip - base_ip - 2;
1090
3.20M
        *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 1), mask) =
1091
3.20M
            ip - base_ip - 1;
1092
1093
3.20M
        uint16_t* table_entry =
1094
3.20M
            TableEntry8ByteMatch(table2, LittleEndian::Load64(ip), mask);
1095
3.20M
        candidate = base_ip + *table_entry;
1096
3.20M
        *table_entry = ip - base_ip;
1097
3.20M
        if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1098
555k
          candidate_length =
1099
555k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1100
555k
          continue;
1101
555k
        }
1102
2.64M
        table_entry =
1103
2.64M
            TableEntry4ByteMatch(table, LittleEndian::Load32(ip), mask);
1104
2.64M
        candidate = base_ip + *table_entry;
1105
2.64M
        *table_entry = ip - base_ip;
1106
2.64M
        if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1107
1.36M
          candidate_length =
1108
1.36M
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1109
1.36M
          continue;
1110
1.36M
        }
1111
1.28M
        break;
1112
2.64M
      } while (true);
1113
1.28M
    }
1114
4.57k
  }
1115
1116
4.60k
emit_remainder:
1117
  // Emit the remaining bytes as a literal
1118
4.60k
  if (ip < ip_end) {
1119
3.02k
    op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
1120
3.02k
  }
1121
1122
4.60k
  return op;
1123
4.60k
}
1124
}  // end namespace internal
1125
1126
static inline void Report(int token, const char *algorithm, size_t
1127
14.4k
compressed_size, size_t uncompressed_size) {
1128
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1129
14.4k
  (void)token;
1130
14.4k
  (void)algorithm;
1131
14.4k
  (void)compressed_size;
1132
14.4k
  (void)uncompressed_size;
1133
14.4k
}
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
204k
static inline uint32_t ExtractLowBytes(const uint32_t& v, int n) {
1192
204k
  assert(n >= 0);
1193
204k
  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
204k
  uint64_t mask = 0xffffffff;
1200
204k
  return v & ~(mask << (8 * n));
1201
204k
#endif
1202
204k
}
1203
1204
16.7k
static inline bool LeftShiftOverflows(uint8_t value, uint32_t shift) {
1205
16.7k
  assert(shift < 32);
1206
16.7k
  static const uint8_t masks[] = {
1207
16.7k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1208
16.7k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1209
16.7k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1210
16.7k
      0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
1211
16.7k
  return (value & masks[shift]) != 0;
1212
16.7k
}
1213
1214
1.47M
inline bool Copy64BytesWithPatternExtension(ptrdiff_t dst, size_t offset) {
1215
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1216
1.47M
  (void)dst;
1217
1.47M
  return offset != 0;
1218
1.47M
}
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
11.1M
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
11.1M
  constexpr int kShortMemCopy = 32;
1227
11.1M
  (void)kShortMemCopy;
1228
11.1M
  assert(size <= 64);
1229
11.1M
  assert(std::less_equal<const void*>()(static_cast<const char*>(src) + size,
1230
11.1M
                                        dst) ||
1231
11.1M
         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
11.1M
  std::memmove(dst, src, kShortMemCopy);
1269
  // Profiling shows that nearly all copies are short.
1270
11.1M
  if (SNAPPY_PREDICT_FALSE(size > kShortMemCopy)) {
1271
1.99M
    std::memmove(dst + kShortMemCopy,
1272
1.99M
                 static_cast<const uint8_t*>(src) + kShortMemCopy,
1273
1.99M
                 64 - kShortMemCopy);
1274
1.99M
  }
1275
11.1M
#endif
1276
11.1M
}
1277
1278
11.1M
void MemCopy64(ptrdiff_t dst, const void* src, size_t size) {
1279
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1280
11.1M
  (void)dst;
1281
11.1M
  (void)src;
1282
11.1M
  (void)size;
1283
11.1M
}
1284
1285
void ClearDeferred(const void** deferred_src, size_t* deferred_length,
1286
3.30M
                   uint8_t* safe_source) {
1287
3.30M
  *deferred_src = safe_source;
1288
3.30M
  *deferred_length = 0;
1289
3.30M
}
1290
1291
void DeferMemCopy(const void** deferred_src, size_t* deferred_length,
1292
19.2M
                  const void* src, size_t length) {
1293
19.2M
  *deferred_src = src;
1294
19.2M
  *deferred_length = length;
1295
19.2M
}
1296
1297
SNAPPY_ATTRIBUTE_ALWAYS_INLINE
1298
0
inline size_t AdvanceToNextTagARMOptimized(const uint8_t** ip_p, size_t* tag) {
1299
0
  const uint8_t*& ip = *ip_p;
1300
0
  // This section is crucial for the throughput of the decompression loop.
1301
0
  // The latency of an iteration is fundamentally constrained by the
1302
0
  // following data chain on ip.
1303
0
  // ip -> c = Load(ip) -> delta1 = (c & 3)        -> ip += delta1 or delta2
1304
0
  //                       delta2 = ((c >> 2) + 1)    ip++
1305
0
  // This is different from X86 optimizations because ARM has conditional add
1306
0
  // instruction (csinc) and it removes several register moves.
1307
0
  const size_t tag_type = *tag & 3;
1308
0
  const bool is_literal = (tag_type == 0);
1309
0
  if (is_literal) {
1310
0
    size_t next_literal_tag = (*tag >> 2) + 1;
1311
0
    *tag = ip[next_literal_tag];
1312
0
    ip += next_literal_tag + 1;
1313
0
  } else {
1314
0
    *tag = ip[tag_type];
1315
0
    ip += tag_type + 1;
1316
0
  }
1317
0
  return tag_type;
1318
0
}
1319
1320
SNAPPY_ATTRIBUTE_ALWAYS_INLINE
1321
22.2M
inline size_t AdvanceToNextTagX86Optimized(const uint8_t** ip_p, size_t* tag) {
1322
22.2M
  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
22.2M
  size_t literal_len = *tag >> 2;
1331
22.2M
  size_t tag_type = *tag;
1332
22.2M
  bool is_literal;
1333
22.2M
#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
22.2M
  asm("and $3, %k[tag_type]\n\t"
1337
22.2M
      : [tag_type] "+r"(tag_type), "=@ccz"(is_literal)
1338
22.2M
      :: "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
22.2M
  size_t tag_literal =
1349
22.2M
      static_cast<const volatile uint8_t*>(ip)[1 + literal_len];
1350
22.2M
  size_t tag_copy = static_cast<const volatile uint8_t*>(ip)[tag_type];
1351
22.2M
  *tag = is_literal ? tag_literal : tag_copy;
1352
22.2M
  const uint8_t* ip_copy = ip + 1 + tag_type;
1353
22.2M
  const uint8_t* ip_literal = ip + 2 + literal_len;
1354
22.2M
  ip = is_literal ? ip_literal : ip_copy;
1355
22.2M
#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
22.2M
  asm("" ::"r"(tag_copy));
1362
22.2M
#endif
1363
22.2M
  return tag_type;
1364
22.2M
}
1365
1366
// Extract the offset for copy-1 and copy-2 returns 0 for literals or copy-4.
1367
22.2M
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
22.2M
#if defined(__x86_64__)
1372
22.2M
  constexpr uint64_t kExtractMasksCombined = 0x0000FFFF00FF0000ull;
1373
22.2M
  uint16_t result;
1374
22.2M
  memcpy(&result,
1375
22.2M
         reinterpret_cast<const char*>(&kExtractMasksCombined) + 2 * tag_type,
1376
22.2M
         sizeof(result));
1377
22.2M
  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
22.2M
};
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
236k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
236k
  uint8_t safe_source[64];
1403
236k
  const void* deferred_src;
1404
236k
  size_t deferred_length;
1405
236k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
236k
  op_limit_min_slop -= kSlopBytes;
1409
236k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
123k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
123k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
123k
    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
11.1M
    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
11.1M
      SNAPPY_PREFETCH(ip + 128);
1430
33.3M
      for (int i = 0; i < 2; i++) {
1431
22.2M
        const uint8_t* old_ip = ip;
1432
22.2M
        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
22.2M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
22.2M
        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
22.2M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
22.2M
        next = LittleEndian::Load32(old_ip);
1445
22.2M
#endif
1446
22.2M
        size_t len = len_minus_offset & 0xFF;
1447
22.2M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
22.2M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
22.2M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
3.07M
          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
120k
          break_loop:
1456
120k
            ip = old_ip;
1457
120k
            goto exit;
1458
114k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
3.07M
          assert(tag_type == 1 || tag_type == 2);
1461
2.95M
          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
2.95M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
2.95M
          op += deferred_length;
1466
2.95M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
2.95M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
2.95M
                                  !Copy64BytesWithPatternExtension(
1469
2.95M
                                      op_base + op, len - len_min_offset))) {
1470
666
            goto break_loop;
1471
666
          }
1472
          // We aren't deferring this copy so add length right away.
1473
2.95M
          op += len;
1474
2.95M
          continue;
1475
2.95M
        }
1476
19.2M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
19.2M
        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
38.1k
          if (tag_type != 0) goto break_loop;
1481
33.0k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
33.0k
          op += deferred_length;
1483
33.0k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
33.0k
          continue;
1485
38.1k
        }
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
19.1M
        const void* from =
1490
19.1M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
19.1M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
19.1M
        op += deferred_length;
1493
19.1M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
19.1M
      }
1495
11.1M
    } while (ip < ip_limit_min_slop &&
1496
11.0M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
123k
  exit:
1498
123k
    ip--;
1499
123k
    assert(ip <= ip_limit);
1500
123k
  }
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
236k
  if (deferred_length) {
1504
108k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
108k
    op += deferred_length;
1506
108k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
108k
  }
1508
236k
  return {ip, op};
1509
236k
}
std::__1::pair<unsigned char const*, long> snappy::DecompressBranchless<char*>(unsigned char const*, unsigned char const*, long, char*, long)
Line
Count
Source
1400
115k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
115k
  uint8_t safe_source[64];
1403
115k
  const void* deferred_src;
1404
115k
  size_t deferred_length;
1405
115k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
115k
  op_limit_min_slop -= kSlopBytes;
1409
115k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
58.8k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
58.8k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
58.8k
    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
5.57M
    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
5.57M
      SNAPPY_PREFETCH(ip + 128);
1430
16.6M
      for (int i = 0; i < 2; i++) {
1431
11.1M
        const uint8_t* old_ip = ip;
1432
11.1M
        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
11.1M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
11.1M
        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
11.1M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
11.1M
        next = LittleEndian::Load32(old_ip);
1445
11.1M
#endif
1446
11.1M
        size_t len = len_minus_offset & 0xFF;
1447
11.1M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
11.1M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
11.1M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
1.53M
          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
57.2k
          break_loop:
1456
57.2k
            ip = old_ip;
1457
57.2k
            goto exit;
1458
57.2k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
1.53M
          assert(tag_type == 1 || tag_type == 2);
1461
1.47M
          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
1.47M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
1.47M
          op += deferred_length;
1466
1.47M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
1.47M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
1.47M
                                  !Copy64BytesWithPatternExtension(
1469
1.47M
                                      op_base + op, len - len_min_offset))) {
1470
0
            goto break_loop;
1471
0
          }
1472
          // We aren't deferring this copy so add length right away.
1473
1.47M
          op += len;
1474
1.47M
          continue;
1475
1.47M
        }
1476
9.60M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
9.60M
        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
16.4k
          if (tag_type != 0) goto break_loop;
1481
16.4k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
16.4k
          op += deferred_length;
1483
16.4k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
16.4k
          continue;
1485
16.4k
        }
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
9.58M
        const void* from =
1490
9.58M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
9.58M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
9.58M
        op += deferred_length;
1493
9.58M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
9.58M
      }
1495
5.57M
    } while (ip < ip_limit_min_slop &&
1496
5.52M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
58.8k
  exit:
1498
58.8k
    ip--;
1499
58.8k
    assert(ip <= ip_limit);
1500
58.8k
  }
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
115k
  if (deferred_length) {
1504
52.1k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
52.1k
    op += deferred_length;
1506
52.1k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
52.1k
  }
1508
115k
  return {ip, op};
1509
115k
}
std::__1::pair<unsigned char const*, long> snappy::DecompressBranchless<unsigned long>(unsigned char const*, unsigned char const*, long, unsigned long, long)
Line
Count
Source
1400
121k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
121k
  uint8_t safe_source[64];
1403
121k
  const void* deferred_src;
1404
121k
  size_t deferred_length;
1405
121k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
121k
  op_limit_min_slop -= kSlopBytes;
1409
121k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
64.5k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
64.5k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
64.5k
    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
5.58M
    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
5.58M
      SNAPPY_PREFETCH(ip + 128);
1430
16.6M
      for (int i = 0; i < 2; i++) {
1431
11.1M
        const uint8_t* old_ip = ip;
1432
11.1M
        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
11.1M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
11.1M
        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
11.1M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
11.1M
        next = LittleEndian::Load32(old_ip);
1445
11.1M
#endif
1446
11.1M
        size_t len = len_minus_offset & 0xFF;
1447
11.1M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
11.1M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
11.1M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
1.53M
          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
62.9k
          break_loop:
1456
62.9k
            ip = old_ip;
1457
62.9k
            goto exit;
1458
57.2k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
1.53M
          assert(tag_type == 1 || tag_type == 2);
1461
1.47M
          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
1.47M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
1.47M
          op += deferred_length;
1466
1.47M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
1.47M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
1.47M
                                  !Copy64BytesWithPatternExtension(
1469
1.47M
                                      op_base + op, len - len_min_offset))) {
1470
666
            goto break_loop;
1471
666
          }
1472
          // We aren't deferring this copy so add length right away.
1473
1.47M
          op += len;
1474
1.47M
          continue;
1475
1.47M
        }
1476
9.60M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
9.60M
        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
21.6k
          if (tag_type != 0) goto break_loop;
1481
16.5k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
16.5k
          op += deferred_length;
1483
16.5k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
16.5k
          continue;
1485
21.6k
        }
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
9.58M
        const void* from =
1490
9.58M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
9.58M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
9.58M
        op += deferred_length;
1493
9.58M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
9.58M
      }
1495
5.58M
    } while (ip < ip_limit_min_slop &&
1496
5.51M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
64.5k
  exit:
1498
64.5k
    ip--;
1499
64.5k
    assert(ip <= ip_limit);
1500
64.5k
  }
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
121k
  if (deferred_length) {
1504
56.5k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
56.5k
    op += deferred_length;
1506
56.5k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
56.5k
  }
1508
121k
  return {ip, op};
1509
121k
}
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
22.8k
  void ResetLimit(const char* ip) {
1532
22.8k
    ip_limit_min_maxtaglen_ =
1533
22.8k
        ip_limit_ - std::min<ptrdiff_t>(ip_limit_ - ip, kMaximumTagLength - 1);
1534
22.8k
  }
1535
1536
 public:
1537
  explicit SnappyDecompressor(Source* reader)
1538
9.66k
      : reader_(reader), ip_(NULL), ip_limit_(NULL), peeked_(0), eof_(false) {}
1539
1540
9.66k
  ~SnappyDecompressor() {
1541
    // Advance past any bytes we peeked at from the reader
1542
9.66k
    reader_->Skip(peeked_);
1543
9.66k
  }
1544
1545
  // Returns true iff we have hit the end of the input without an error.
1546
9.66k
  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
9.66k
  bool ReadUncompressedLength(uint32_t* result) {
1552
9.66k
    assert(ip_ == NULL);  // Must not have read anything yet
1553
    // Length is encoded in 1..5 bytes
1554
9.66k
    *result = 0;
1555
9.66k
    uint32_t shift = 0;
1556
16.7k
    while (true) {
1557
16.7k
      if (shift >= 32) return false;
1558
16.7k
      size_t n;
1559
16.7k
      const char* ip = reader_->Peek(&n);
1560
16.7k
      if (n == 0) return false;
1561
16.7k
      const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
1562
16.7k
      reader_->Skip(1);
1563
16.7k
      uint32_t val = c & 0x7f;
1564
16.7k
      if (LeftShiftOverflows(static_cast<uint8_t>(val), shift)) return false;
1565
16.7k
      *result |= val << shift;
1566
16.7k
      if (c < 128) {
1567
9.66k
        break;
1568
9.66k
      }
1569
7.12k
      shift += 7;
1570
7.12k
    }
1571
9.66k
    return true;
1572
9.66k
  }
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
9.66k
  DecompressAllTags(Writer* writer) {
1582
9.66k
    const char* ip = ip_;
1583
9.66k
    ResetLimit(ip);
1584
9.66k
    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
9.66k
#define MAYBE_REFILL()                                      \
1590
387k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
22.8k
    ip_ = ip;                                               \
1592
22.8k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
22.8k
    ip = ip_;                                               \
1594
13.1k
    ResetLimit(ip);                                         \
1595
13.1k
  }                                                         \
1596
387k
  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
9.66k
    uint32_t preload;
1601
9.66k
    MAYBE_REFILL();
1602
236k
    for (;;) {
1603
236k
      {
1604
236k
        ptrdiff_t op_limit_min_slop;
1605
236k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
236k
        if (op_base) {
1607
236k
          auto res =
1608
236k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
236k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
236k
                                   op - op_base, op_base, op_limit_min_slop);
1611
236k
          ip = reinterpret_cast<const char*>(res.first);
1612
236k
          op = op_base + res.second;
1613
236k
          MAYBE_REFILL();
1614
236k
        }
1615
236k
      }
1616
236k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
236k
      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
236k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
148k
        size_t literal_length = (c >> 2) + 1u;
1633
148k
        if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
9.46k
          assert(literal_length < 61);
1635
9.46k
          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
9.46k
          preload = static_cast<uint8_t>(*ip);
1640
9.46k
          continue;
1641
9.46k
        }
1642
138k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
115k
          const size_t literal_length_length = literal_length - 60;
1645
115k
          literal_length =
1646
115k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
115k
              1;
1648
115k
          ip += literal_length_length;
1649
115k
        }
1650
1651
138k
        size_t avail = ip_limit_ - ip;
1652
138k
        while (avail < literal_length) {
1653
0
          if (!writer->Append(ip, avail, &op)) goto exit;
1654
0
          literal_length -= avail;
1655
0
          reader_->Skip(peeked_);
1656
0
          size_t n;
1657
0
          ip = reader_->Peek(&n);
1658
0
          avail = n;
1659
0
          peeked_ = avail;
1660
0
          if (avail == 0) goto exit;
1661
0
          ip_limit_ = ip + avail;
1662
0
          ResetLimit(ip);
1663
0
        }
1664
138k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
138k
        ip += literal_length;
1666
138k
        MAYBE_REFILL();
1667
130k
      } else {
1668
88.6k
        if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
0
          const size_t copy_offset = LittleEndian::Load32(ip);
1670
0
          const size_t length = (c >> 2) + 1;
1671
0
          ip += 4;
1672
1673
0
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
88.6k
        } else {
1675
88.6k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
88.6k
          preload = LittleEndian::Load32(ip);
1677
88.6k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
88.6k
          const uint32_t length = entry & 0xff;
1679
88.6k
          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
88.6k
          const uint32_t copy_offset = trailer - entry + length;
1685
88.6k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
1687
88.6k
          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
88.6k
          preload >>= (c & 3) * 8;
1691
88.6k
          if (ip < ip_limit_min_maxtaglen_) continue;
1692
88.6k
        }
1693
4.10k
        MAYBE_REFILL();
1694
4.10k
      }
1695
236k
    }
1696
0
#undef MAYBE_REFILL
1697
9.66k
  exit:
1698
9.66k
    writer->SetOutputPtr(op);
1699
9.66k
  }
Unexecuted instantiation: void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyIOVecWriter>(snappy::SnappyIOVecWriter*)
void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyDecompressionValidator>(snappy::SnappyDecompressionValidator*)
Line
Count
Source
1581
4.83k
  DecompressAllTags(Writer* writer) {
1582
4.83k
    const char* ip = ip_;
1583
4.83k
    ResetLimit(ip);
1584
4.83k
    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
4.83k
#define MAYBE_REFILL()                                      \
1590
4.83k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
4.83k
    ip_ = ip;                                               \
1592
4.83k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
4.83k
    ip = ip_;                                               \
1594
4.83k
    ResetLimit(ip);                                         \
1595
4.83k
  }                                                         \
1596
4.83k
  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
4.83k
    uint32_t preload;
1601
4.83k
    MAYBE_REFILL();
1602
121k
    for (;;) {
1603
121k
      {
1604
121k
        ptrdiff_t op_limit_min_slop;
1605
121k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
121k
        if (op_base) {
1607
121k
          auto res =
1608
121k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
121k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
121k
                                   op - op_base, op_base, op_limit_min_slop);
1611
121k
          ip = reinterpret_cast<const char*>(res.first);
1612
121k
          op = op_base + res.second;
1613
121k
          MAYBE_REFILL();
1614
121k
        }
1615
121k
      }
1616
121k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
121k
      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
121k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
74.0k
        size_t literal_length = (c >> 2) + 1u;
1633
74.0k
        if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
0
          assert(literal_length < 61);
1635
0
          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
0
          preload = static_cast<uint8_t>(*ip);
1640
0
          continue;
1641
0
        }
1642
74.0k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
57.8k
          const size_t literal_length_length = literal_length - 60;
1645
57.8k
          literal_length =
1646
57.8k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
57.8k
              1;
1648
57.8k
          ip += literal_length_length;
1649
57.8k
        }
1650
1651
74.0k
        size_t avail = ip_limit_ - ip;
1652
74.0k
        while (avail < literal_length) {
1653
0
          if (!writer->Append(ip, avail, &op)) goto exit;
1654
0
          literal_length -= avail;
1655
0
          reader_->Skip(peeked_);
1656
0
          size_t n;
1657
0
          ip = reader_->Peek(&n);
1658
0
          avail = n;
1659
0
          peeked_ = avail;
1660
0
          if (avail == 0) goto exit;
1661
0
          ip_limit_ = ip + avail;
1662
0
          ResetLimit(ip);
1663
0
        }
1664
74.0k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
74.0k
        ip += literal_length;
1666
74.0k
        MAYBE_REFILL();
1667
69.8k
      } else {
1668
47.2k
        if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
0
          const size_t copy_offset = LittleEndian::Load32(ip);
1670
0
          const size_t length = (c >> 2) + 1;
1671
0
          ip += 4;
1672
1673
0
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
47.2k
        } else {
1675
47.2k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
47.2k
          preload = LittleEndian::Load32(ip);
1677
47.2k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
47.2k
          const uint32_t length = entry & 0xff;
1679
47.2k
          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
47.2k
          const uint32_t copy_offset = trailer - entry + length;
1685
47.2k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
1687
47.2k
          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
47.2k
          preload >>= (c & 3) * 8;
1691
47.2k
          if (ip < ip_limit_min_maxtaglen_) continue;
1692
47.2k
        }
1693
2.05k
        MAYBE_REFILL();
1694
2.05k
      }
1695
121k
    }
1696
0
#undef MAYBE_REFILL
1697
4.83k
  exit:
1698
4.83k
    writer->SetOutputPtr(op);
1699
4.83k
  }
void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyArrayWriter>(snappy::SnappyArrayWriter*)
Line
Count
Source
1581
4.83k
  DecompressAllTags(Writer* writer) {
1582
4.83k
    const char* ip = ip_;
1583
4.83k
    ResetLimit(ip);
1584
4.83k
    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
4.83k
#define MAYBE_REFILL()                                      \
1590
4.83k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
4.83k
    ip_ = ip;                                               \
1592
4.83k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
4.83k
    ip = ip_;                                               \
1594
4.83k
    ResetLimit(ip);                                         \
1595
4.83k
  }                                                         \
1596
4.83k
  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
4.83k
    uint32_t preload;
1601
4.83k
    MAYBE_REFILL();
1602
115k
    for (;;) {
1603
115k
      {
1604
115k
        ptrdiff_t op_limit_min_slop;
1605
115k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
115k
        if (op_base) {
1607
115k
          auto res =
1608
115k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
115k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
115k
                                   op - op_base, op_base, op_limit_min_slop);
1611
115k
          ip = reinterpret_cast<const char*>(res.first);
1612
115k
          op = op_base + res.second;
1613
115k
          MAYBE_REFILL();
1614
115k
        }
1615
115k
      }
1616
115k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
115k
      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
115k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
74.0k
        size_t literal_length = (c >> 2) + 1u;
1633
74.0k
        if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
9.46k
          assert(literal_length < 61);
1635
9.46k
          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
9.46k
          preload = static_cast<uint8_t>(*ip);
1640
9.46k
          continue;
1641
9.46k
        }
1642
64.5k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
57.8k
          const size_t literal_length_length = literal_length - 60;
1645
57.8k
          literal_length =
1646
57.8k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
57.8k
              1;
1648
57.8k
          ip += literal_length_length;
1649
57.8k
        }
1650
1651
64.5k
        size_t avail = ip_limit_ - ip;
1652
64.5k
        while (avail < literal_length) {
1653
0
          if (!writer->Append(ip, avail, &op)) goto exit;
1654
0
          literal_length -= avail;
1655
0
          reader_->Skip(peeked_);
1656
0
          size_t n;
1657
0
          ip = reader_->Peek(&n);
1658
0
          avail = n;
1659
0
          peeked_ = avail;
1660
0
          if (avail == 0) goto exit;
1661
0
          ip_limit_ = ip + avail;
1662
0
          ResetLimit(ip);
1663
0
        }
1664
64.5k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
64.5k
        ip += literal_length;
1666
64.5k
        MAYBE_REFILL();
1667
60.3k
      } else {
1668
41.4k
        if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
0
          const size_t copy_offset = LittleEndian::Load32(ip);
1670
0
          const size_t length = (c >> 2) + 1;
1671
0
          ip += 4;
1672
1673
0
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
41.4k
        } else {
1675
41.4k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
41.4k
          preload = LittleEndian::Load32(ip);
1677
41.4k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
41.4k
          const uint32_t length = entry & 0xff;
1679
41.4k
          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
41.4k
          const uint32_t copy_offset = trailer - entry + length;
1685
41.4k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
1687
41.4k
          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
41.4k
          preload >>= (c & 3) * 8;
1691
41.4k
          if (ip < ip_limit_min_maxtaglen_) continue;
1692
41.4k
        }
1693
2.05k
        MAYBE_REFILL();
1694
2.05k
      }
1695
115k
    }
1696
0
#undef MAYBE_REFILL
1697
4.83k
  exit:
1698
4.83k
    writer->SetOutputPtr(op);
1699
4.83k
  }
Unexecuted instantiation: void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator> >(snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator>*)
1700
};
1701
1702
13.1k
constexpr uint32_t CalculateNeeded(uint8_t tag) {
1703
13.1k
  return ((tag & 3) == 0 && tag >= (60 * 4))
1704
13.1k
             ? (tag >> 2) - 58
1705
13.1k
             : (0x05030201 >> ((tag * 8) & 31)) & 0xFF;
1706
13.1k
}
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
22.8k
bool SnappyDecompressor::RefillTag() {
1723
22.8k
  const char* ip = ip_;
1724
22.8k
  if (ip == ip_limit_) {
1725
    // Fetch a new fragment from the reader
1726
19.3k
    reader_->Skip(peeked_);  // All peeked bytes are used up
1727
19.3k
    size_t n;
1728
19.3k
    ip = reader_->Peek(&n);
1729
19.3k
    peeked_ = n;
1730
19.3k
    eof_ = (n == 0);
1731
19.3k
    if (eof_) return false;
1732
9.66k
    ip_limit_ = ip + n;
1733
9.66k
  }
1734
1735
  // Read the tag character
1736
22.8k
  assert(ip < ip_limit_);
1737
13.1k
  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
13.1k
  const uint32_t needed = CalculateNeeded(c);
1745
13.1k
  assert(needed <= sizeof(scratch_));
1746
1747
  // Read more bytes from reader if needed
1748
13.1k
  uint64_t nbuf = ip_limit_ - ip;
1749
13.1k
  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
0
    std::memmove(scratch_, ip, nbuf);
1755
0
    reader_->Skip(peeked_);  // All peeked bytes are used up
1756
0
    peeked_ = 0;
1757
0
    while (nbuf < needed) {
1758
0
      size_t length;
1759
0
      const char* src = reader_->Peek(&length);
1760
0
      if (length == 0) return false;
1761
0
      uint64_t to_add = std::min<uint64_t>(needed - nbuf, length);
1762
0
      std::memcpy(scratch_ + nbuf, src, to_add);
1763
0
      nbuf += to_add;
1764
0
      reader_->Skip(to_add);
1765
0
    }
1766
0
    assert(nbuf == needed);
1767
0
    ip_ = scratch_;
1768
0
    ip_limit_ = scratch_ + needed;
1769
13.1k
  } else if (nbuf < kMaximumTagLength) {
1770
    // Have enough bytes, but move into scratch_ so that we do not
1771
    // read past end of input
1772
3.53k
    std::memmove(scratch_, ip, nbuf);
1773
3.53k
    reader_->Skip(peeked_);  // All peeked bytes are used up
1774
3.53k
    peeked_ = 0;
1775
3.53k
    ip_ = scratch_;
1776
3.53k
    ip_limit_ = scratch_ + nbuf;
1777
9.65k
  } else {
1778
    // Pass pointer to buffer returned by reader_.
1779
9.65k
    ip_ = ip;
1780
9.65k
  }
1781
13.1k
  return true;
1782
13.1k
}
1783
1784
template <typename Writer>
1785
9.66k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
9.66k
  SnappyDecompressor decompressor(r);
1788
9.66k
  uint32_t uncompressed_len = 0;
1789
9.66k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
9.66k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
9.66k
                                   uncompressed_len);
1793
9.66k
}
Unexecuted instantiation: snappy.cc:bool snappy::InternalUncompress<snappy::SnappyIOVecWriter>(snappy::Source*, snappy::SnappyIOVecWriter*)
snappy.cc:bool snappy::InternalUncompress<snappy::SnappyArrayWriter>(snappy::Source*, snappy::SnappyArrayWriter*)
Line
Count
Source
1785
4.83k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
4.83k
  SnappyDecompressor decompressor(r);
1788
4.83k
  uint32_t uncompressed_len = 0;
1789
4.83k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
4.83k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
4.83k
                                   uncompressed_len);
1793
4.83k
}
snappy.cc:bool snappy::InternalUncompress<snappy::SnappyDecompressionValidator>(snappy::Source*, snappy::SnappyDecompressionValidator*)
Line
Count
Source
1785
4.83k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
4.83k
  SnappyDecompressor decompressor(r);
1788
4.83k
  uint32_t uncompressed_len = 0;
1789
4.83k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
4.83k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
4.83k
                                   uncompressed_len);
1793
4.83k
}
Unexecuted instantiation: snappy.cc:bool snappy::InternalUncompress<snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator> >(snappy::Source*, snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator>*)
1794
1795
template <typename Writer>
1796
static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
1797
                                      Writer* writer, uint32_t compressed_len,
1798
9.66k
                                      uint32_t uncompressed_len) {
1799
9.66k
    int token = 0;
1800
9.66k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
9.66k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
9.66k
  decompressor->DecompressAllTags(writer);
1806
9.66k
  writer->Flush();
1807
9.66k
  return (decompressor->eof() && writer->CheckLength());
1808
9.66k
}
Unexecuted instantiation: snappy.cc:bool snappy::InternalUncompressAllTags<snappy::SnappyIOVecWriter>(snappy::SnappyDecompressor*, snappy::SnappyIOVecWriter*, unsigned int, unsigned int)
snappy.cc:bool snappy::InternalUncompressAllTags<snappy::SnappyDecompressionValidator>(snappy::SnappyDecompressor*, snappy::SnappyDecompressionValidator*, unsigned int, unsigned int)
Line
Count
Source
1798
4.83k
                                      uint32_t uncompressed_len) {
1799
4.83k
    int token = 0;
1800
4.83k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
4.83k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
4.83k
  decompressor->DecompressAllTags(writer);
1806
4.83k
  writer->Flush();
1807
4.83k
  return (decompressor->eof() && writer->CheckLength());
1808
4.83k
}
snappy.cc:bool snappy::InternalUncompressAllTags<snappy::SnappyArrayWriter>(snappy::SnappyDecompressor*, snappy::SnappyArrayWriter*, unsigned int, unsigned int)
Line
Count
Source
1798
4.83k
                                      uint32_t uncompressed_len) {
1799
4.83k
    int token = 0;
1800
4.83k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
4.83k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
4.83k
  decompressor->DecompressAllTags(writer);
1806
4.83k
  writer->Flush();
1807
4.83k
  return (decompressor->eof() && writer->CheckLength());
1808
4.83k
}
Unexecuted instantiation: snappy.cc:bool snappy::InternalUncompressAllTags<snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator> >(snappy::SnappyDecompressor*, snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator>*, unsigned int, unsigned int)
1809
1810
0
bool GetUncompressedLength(Source* source, uint32_t* result) {
1811
0
  SnappyDecompressor decompressor(source);
1812
0
  return decompressor.ReadUncompressedLength(result);
1813
0
}
1814
1815
0
size_t Compress(Source* reader, Sink* writer) {
1816
0
  return Compress(reader, writer, CompressionOptions{});
1817
0
}
1818
1819
4.83k
size_t Compress(Source* reader, Sink* writer, CompressionOptions options) {
1820
4.83k
  assert(options.level == 1 || options.level == 2);
1821
4.83k
  int token = 0;
1822
4.83k
  size_t written = 0;
1823
4.83k
  size_t N = reader->Available();
1824
4.83k
  assert(N <= 0xFFFFFFFFu);
1825
4.83k
  const size_t uncompressed_size = N;
1826
4.83k
  char ulength[Varint::kMax32];
1827
4.83k
  char* p = Varint::Encode32(ulength, N);
1828
4.83k
  writer->Append(ulength, p - ulength);
1829
4.83k
  written += (p - ulength);
1830
1831
4.83k
  internal::WorkingMemory wmem(N);
1832
1833
14.0k
  while (N > 0) {
1834
    // Get next block to compress (without copying if possible)
1835
9.20k
    size_t fragment_size;
1836
9.20k
    const char* fragment = reader->Peek(&fragment_size);
1837
9.20k
    assert(fragment_size != 0);  // premature end of input
1838
9.20k
    const size_t num_to_read = std::min(N, kBlockSize);
1839
9.20k
    size_t bytes_read = fragment_size;
1840
1841
9.20k
    size_t pending_advance = 0;
1842
9.20k
    if (bytes_read >= num_to_read) {
1843
      // Buffer returned by reader is large enough
1844
9.20k
      pending_advance = num_to_read;
1845
9.20k
      fragment_size = num_to_read;
1846
9.20k
    } else {
1847
0
      char* scratch = wmem.GetScratchInput();
1848
0
      std::memcpy(scratch, fragment, bytes_read);
1849
0
      reader->Skip(bytes_read);
1850
1851
0
      while (bytes_read < num_to_read) {
1852
0
        fragment = reader->Peek(&fragment_size);
1853
0
        size_t n = std::min<size_t>(fragment_size, num_to_read - bytes_read);
1854
0
        std::memcpy(scratch + bytes_read, fragment, n);
1855
0
        bytes_read += n;
1856
0
        reader->Skip(n);
1857
0
      }
1858
0
      assert(bytes_read == num_to_read);
1859
0
      fragment = scratch;
1860
0
      fragment_size = num_to_read;
1861
0
    }
1862
9.20k
    assert(fragment_size == num_to_read);
1863
1864
    // Get encoding table for compression
1865
9.20k
    int table_size;
1866
9.20k
    uint16_t* table = wmem.GetHashTable(num_to_read, &table_size);
1867
1868
    // Compress input_fragment and append to dest
1869
9.20k
    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
9.20k
    char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput());
1877
9.20k
    char* end = nullptr;
1878
9.20k
    if (options.level == 1) {
1879
4.60k
      end = internal::CompressFragment(fragment, fragment_size, dest, table,
1880
4.60k
                                       table_size);
1881
4.60k
    } else if (options.level == 2) {
1882
4.60k
      end = internal::CompressFragmentDoubleHash(
1883
4.60k
          fragment, fragment_size, dest, table, table_size >> 1,
1884
4.60k
          table + (table_size >> 1), table_size >> 1);
1885
4.60k
    }
1886
9.20k
    writer->Append(dest, end - dest);
1887
9.20k
    written += (end - dest);
1888
1889
9.20k
    N -= num_to_read;
1890
9.20k
    reader->Skip(pending_advance);
1891
9.20k
  }
1892
1893
4.83k
  Report(token, "snappy_compress", written, uncompressed_size);
1894
4.83k
  return written;
1895
4.83k
}
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
0
      : curr_iov_(iov),
1908
0
        curr_pos_(total_size > 0 ? reinterpret_cast<const char*>(iov->iov_base)
1909
0
                                 : nullptr),
1910
0
        curr_size_remaining_(total_size > 0 ? iov->iov_len : 0),
1911
0
        total_size_remaining_(total_size) {
1912
    // Skip empty leading `iovec`s.
1913
0
    if (total_size > 0 && curr_size_remaining_ == 0) Advance();
1914
0
  }
1915
1916
  ~SnappyIOVecReader() override = default;
1917
1918
0
  size_t Available() const override { return total_size_remaining_; }
1919
1920
0
  const char* Peek(size_t* len) override {
1921
0
    *len = curr_size_remaining_;
1922
0
    return curr_pos_;
1923
0
  }
1924
1925
0
  void Skip(size_t n) override {
1926
0
    while (n >= curr_size_remaining_ && n > 0) {
1927
0
      n -= curr_size_remaining_;
1928
0
      Advance();
1929
0
    }
1930
0
    curr_size_remaining_ -= n;
1931
0
    total_size_remaining_ -= n;
1932
0
    curr_pos_ += n;
1933
0
  }
1934
1935
 private:
1936
  // Advances to the next nonempty `iovec` and updates related variables.
1937
0
  void Advance() {
1938
0
    do {
1939
0
      assert(total_size_remaining_ >= curr_size_remaining_);
1940
0
      total_size_remaining_ -= curr_size_remaining_;
1941
0
      if (total_size_remaining_ == 0) {
1942
0
        curr_pos_ = nullptr;
1943
0
        curr_size_remaining_ = 0;
1944
0
        return;
1945
0
      }
1946
0
      ++curr_iov_;
1947
0
      curr_pos_ = reinterpret_cast<const char*>(curr_iov_->iov_base);
1948
0
      curr_size_remaining_ = curr_iov_->iov_len;
1949
0
    } while (curr_size_remaining_ == 0);
1950
0
  }
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
0
  static inline char* GetIOVecPointer(const struct iovec* iov, size_t offset) {
1991
0
    return reinterpret_cast<char*>(iov->iov_base) + offset;
1992
0
  }
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
0
      : output_iov_end_(iov + iov_count),
1999
#if !defined(NDEBUG)
2000
0
        output_iov_(iov),
2001
#endif  // !defined(NDEBUG)
2002
0
        curr_iov_(iov),
2003
0
        curr_iov_output_(iov_count ? reinterpret_cast<char*>(iov->iov_base)
2004
0
                                   : nullptr),
2005
0
        curr_iov_remaining_(iov_count ? iov->iov_len : 0),
2006
0
        total_written_(0),
2007
0
        output_limit_(-1) {
2008
0
  }
2009
2010
0
  inline void SetExpectedLength(size_t len) { output_limit_ = len; }
2011
2012
0
  inline bool CheckLength() const { return total_written_ == output_limit_; }
2013
2014
0
  inline bool Append(const char* ip, size_t len, char**) {
2015
0
    if (total_written_ + len > output_limit_) {
2016
0
      return false;
2017
0
    }
2018
2019
0
    return AppendNoCheck(ip, len);
2020
0
  }
2021
2022
0
  char* GetOutputPtr() { return nullptr; }
2023
0
  char* GetBase(ptrdiff_t*) { return nullptr; }
2024
0
  void SetOutputPtr(char* op) {
2025
    // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2026
0
    (void)op;
2027
0
  }
2028
2029
0
  inline bool AppendNoCheck(const char* ip, size_t len) {
2030
0
    while (len > 0) {
2031
0
      if (curr_iov_remaining_ == 0) {
2032
        // This iovec is full. Go to the next one.
2033
0
        if (curr_iov_ + 1 >= output_iov_end_) {
2034
0
          return false;
2035
0
        }
2036
0
        ++curr_iov_;
2037
0
        curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
2038
0
        curr_iov_remaining_ = curr_iov_->iov_len;
2039
0
      }
2040
2041
0
      const size_t to_write = std::min(len, curr_iov_remaining_);
2042
0
      std::memcpy(curr_iov_output_, ip, to_write);
2043
0
      curr_iov_output_ += to_write;
2044
0
      curr_iov_remaining_ -= to_write;
2045
0
      total_written_ += to_write;
2046
0
      ip += to_write;
2047
0
      len -= to_write;
2048
0
    }
2049
2050
0
    return true;
2051
0
  }
2052
2053
  inline bool TryFastAppend(const char* ip, size_t available, size_t len,
2054
0
                            char**) {
2055
0
    const size_t space_left = output_limit_ - total_written_;
2056
0
    if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
2057
0
        curr_iov_remaining_ >= 16) {
2058
      // Fast path, used for the majority (about 95%) of invocations.
2059
0
      UnalignedCopy128(ip, curr_iov_output_);
2060
0
      curr_iov_output_ += len;
2061
0
      curr_iov_remaining_ -= len;
2062
0
      total_written_ += len;
2063
0
      return true;
2064
0
    }
2065
2066
0
    return false;
2067
0
  }
2068
2069
0
  inline bool AppendFromSelf(size_t offset, size_t len, char**) {
2070
    // See SnappyArrayWriter::AppendFromSelf for an explanation of
2071
    // the "offset - 1u" trick.
2072
0
    if (offset - 1u >= total_written_) {
2073
0
      return false;
2074
0
    }
2075
0
    const size_t space_left = output_limit_ - total_written_;
2076
0
    if (len > space_left) {
2077
0
      return false;
2078
0
    }
2079
2080
    // Locate the iovec from which we need to start the copy.
2081
0
    const iovec* from_iov = curr_iov_;
2082
0
    size_t from_iov_offset = curr_iov_->iov_len - curr_iov_remaining_;
2083
0
    while (offset > 0) {
2084
0
      if (from_iov_offset >= offset) {
2085
0
        from_iov_offset -= offset;
2086
0
        break;
2087
0
      }
2088
2089
0
      offset -= from_iov_offset;
2090
0
      --from_iov;
2091
0
#if !defined(NDEBUG)
2092
0
      assert(from_iov >= output_iov_);
2093
0
#endif  // !defined(NDEBUG)
2094
0
      from_iov_offset = from_iov->iov_len;
2095
0
    }
2096
2097
    // Copy <len> bytes starting from the iovec pointed to by from_iov_index to
2098
    // the current iovec.
2099
0
    while (len > 0) {
2100
0
      assert(from_iov <= curr_iov_);
2101
0
      if (from_iov != curr_iov_) {
2102
0
        const size_t to_copy =
2103
0
            std::min(from_iov->iov_len - from_iov_offset, len);
2104
0
        AppendNoCheck(GetIOVecPointer(from_iov, from_iov_offset), to_copy);
2105
0
        len -= to_copy;
2106
0
        if (len > 0) {
2107
0
          ++from_iov;
2108
0
          from_iov_offset = 0;
2109
0
        }
2110
0
      } else {
2111
0
        size_t to_copy = curr_iov_remaining_;
2112
0
        if (to_copy == 0) {
2113
          // This iovec is full. Go to the next one.
2114
0
          if (curr_iov_ + 1 >= output_iov_end_) {
2115
0
            return false;
2116
0
          }
2117
0
          ++curr_iov_;
2118
0
          curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
2119
0
          curr_iov_remaining_ = curr_iov_->iov_len;
2120
0
          continue;
2121
0
        }
2122
0
        if (to_copy > len) {
2123
0
          to_copy = len;
2124
0
        }
2125
0
        assert(to_copy > 0);
2126
2127
0
        IncrementalCopy(GetIOVecPointer(from_iov, from_iov_offset),
2128
0
                        curr_iov_output_, curr_iov_output_ + to_copy,
2129
0
                        curr_iov_output_ + curr_iov_remaining_);
2130
0
        curr_iov_output_ += to_copy;
2131
0
        curr_iov_remaining_ -= to_copy;
2132
0
        from_iov_offset += to_copy;
2133
0
        total_written_ += to_copy;
2134
0
        len -= to_copy;
2135
0
      }
2136
0
    }
2137
2138
0
    return true;
2139
0
  }
2140
2141
0
  inline void Flush() {}
2142
};
2143
2144
bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
2145
0
                          const struct iovec* iov, size_t iov_cnt) {
2146
0
  ByteArraySource reader(compressed, compressed_length);
2147
0
  return RawUncompressToIOVec(&reader, iov, iov_cnt);
2148
0
}
2149
2150
bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
2151
0
                          size_t iov_cnt) {
2152
0
  SnappyIOVecWriter output(iov, iov_cnt);
2153
0
  return InternalUncompress(compressed, &output);
2154
0
}
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
4.83k
      : base_(dst),
2175
4.83k
        op_(dst),
2176
4.83k
        op_limit_(dst),
2177
4.83k
        op_limit_min_slop_(dst) {}  // Safe default see invariant.
2178
2179
4.83k
  inline void SetExpectedLength(size_t len) {
2180
4.83k
    op_limit_ = op_ + len;
2181
    // Prevent pointer from being past the buffer.
2182
4.83k
    op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, len);
2183
4.83k
  }
2184
2185
4.83k
  inline bool CheckLength() const { return op_ == op_limit_; }
2186
2187
4.83k
  char* GetOutputPtr() { return op_; }
2188
115k
  char* GetBase(ptrdiff_t* op_limit_min_slop) {
2189
115k
    *op_limit_min_slop = op_limit_min_slop_ - base_;
2190
115k
    return base_;
2191
115k
  }
2192
4.83k
  void SetOutputPtr(char* op) { op_ = op; }
2193
2194
64.5k
  inline bool Append(const char* ip, size_t len, char** op_p) {
2195
64.5k
    char* op = *op_p;
2196
64.5k
    const size_t space_left = op_limit_ - op;
2197
64.5k
    if (space_left < len) return false;
2198
64.5k
    std::memcpy(op, ip, len);
2199
64.5k
    *op_p = op + len;
2200
64.5k
    return true;
2201
64.5k
  }
2202
2203
  inline bool TryFastAppend(const char* ip, size_t available, size_t len,
2204
74.0k
                            char** op_p) {
2205
74.0k
    char* op = *op_p;
2206
74.0k
    const size_t space_left = op_limit_ - op;
2207
74.0k
    if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
2208
      // Fast path, used for the majority (about 95%) of invocations.
2209
9.46k
      UnalignedCopy128(ip, op);
2210
9.46k
      *op_p = op + len;
2211
9.46k
      return true;
2212
64.5k
    } else {
2213
64.5k
      return false;
2214
64.5k
    }
2215
74.0k
  }
2216
2217
  SNAPPY_ATTRIBUTE_ALWAYS_INLINE
2218
41.4k
  inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
2219
41.4k
    assert(len > 0);
2220
41.4k
    char* const op = *op_p;
2221
41.4k
    assert(op >= base_);
2222
41.4k
    char* const op_end = op + len;
2223
2224
    // Check if we try to append from before the start of the buffer.
2225
41.4k
    if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - base_) < offset))
2226
0
      return false;
2227
2228
41.4k
    if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
2229
41.4k
                            op >= op_limit_min_slop_ || offset < len)) {
2230
19.6k
      if (op_end > op_limit_ || offset == 0) return false;
2231
19.6k
      *op_p = IncrementalCopy(op - offset, op, op_end, op_limit_);
2232
19.6k
      return true;
2233
19.6k
    }
2234
21.8k
    std::memmove(op, op - offset, kSlopBytes);
2235
21.8k
    *op_p = op_end;
2236
21.8k
    return true;
2237
41.4k
  }
2238
0
  inline size_t Produced() const {
2239
0
    assert(op_ >= base_);
2240
0
    return op_ - base_;
2241
0
  }
2242
4.83k
  inline void Flush() {}
2243
};
2244
2245
bool RawUncompress(const char* compressed, size_t compressed_length,
2246
4.83k
                   char* uncompressed) {
2247
4.83k
  ByteArraySource reader(compressed, compressed_length);
2248
4.83k
  return RawUncompress(&reader, uncompressed);
2249
4.83k
}
2250
2251
4.83k
bool RawUncompress(Source* compressed, char* uncompressed) {
2252
4.83k
  SnappyArrayWriter output(uncompressed);
2253
4.83k
  return InternalUncompress(compressed, &output);
2254
4.83k
}
2255
2256
bool Uncompress(const char* compressed, size_t compressed_length,
2257
4.83k
                std::string* uncompressed) {
2258
4.83k
  size_t ulength;
2259
4.83k
  if (!GetUncompressedLength(compressed, compressed_length, &ulength)) {
2260
0
    return false;
2261
0
  }
2262
  // On 32-bit builds: max_size() < kuint32max.  Check for that instead
2263
  // of crashing (e.g., consider externally specified compressed data).
2264
4.83k
  if (ulength > uncompressed->max_size()) {
2265
0
    return false;
2266
0
  }
2267
4.83k
  STLStringResizeUninitialized(uncompressed, ulength);
2268
4.83k
  return RawUncompress(compressed, compressed_length,
2269
4.83k
                       string_as_array(uncompressed));
2270
4.83k
}
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
4.83k
  inline SnappyDecompressionValidator() : expected_(0), produced_(0) {}
2280
4.83k
  inline void SetExpectedLength(size_t len) { expected_ = len; }
2281
4.83k
  size_t GetOutputPtr() { return produced_; }
2282
121k
  size_t GetBase(ptrdiff_t* op_limit_min_slop) {
2283
121k
    *op_limit_min_slop = std::numeric_limits<ptrdiff_t>::max() - kSlopBytes + 1;
2284
121k
    return 1;
2285
121k
  }
2286
4.83k
  void SetOutputPtr(size_t op) { produced_ = op; }
2287
4.83k
  inline bool CheckLength() const { return expected_ == produced_; }
2288
74.0k
  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
74.0k
    (void)ip;
2291
2292
74.0k
    *produced += len;
2293
74.0k
    return *produced <= expected_;
2294
74.0k
  }
2295
  inline bool TryFastAppend(const char* ip, size_t available, size_t length,
2296
74.0k
                            size_t* produced) {
2297
    // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2298
74.0k
    (void)ip;
2299
74.0k
    (void)available;
2300
74.0k
    (void)length;
2301
74.0k
    (void)produced;
2302
2303
74.0k
    return false;
2304
74.0k
  }
2305
47.2k
  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
47.2k
    if (*produced <= offset - 1u) return false;
2309
47.2k
    *produced += len;
2310
47.2k
    return *produced <= expected_;
2311
47.2k
  }
2312
4.83k
  inline void Flush() {}
2313
};
2314
2315
4.83k
bool IsValidCompressedBuffer(const char* compressed, size_t compressed_length) {
2316
4.83k
  ByteArraySource reader(compressed, compressed_length);
2317
4.83k
  SnappyDecompressionValidator writer;
2318
4.83k
  return InternalUncompress(&reader, &writer);
2319
4.83k
}
2320
2321
0
bool IsValidCompressed(Source* compressed) {
2322
0
  SnappyDecompressionValidator writer;
2323
0
  return InternalUncompress(compressed, &writer);
2324
0
}
2325
2326
void RawCompress(const char* input, size_t input_length, char* compressed,
2327
0
                 size_t* compressed_length) {
2328
0
  RawCompress(input, input_length, compressed, compressed_length,
2329
0
              CompressionOptions{});
2330
0
}
2331
2332
void RawCompress(const char* input, size_t input_length, char* compressed,
2333
4.83k
                 size_t* compressed_length, CompressionOptions options) {
2334
4.83k
  ByteArraySource reader(input, input_length);
2335
4.83k
  UncheckedByteArraySink writer(compressed);
2336
4.83k
  Compress(&reader, &writer, options);
2337
2338
  // Compute how many bytes were added
2339
4.83k
  *compressed_length = (writer.CurrentDestination() - compressed);
2340
4.83k
}
2341
2342
void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
2343
0
                          char* compressed, size_t* compressed_length) {
2344
0
  RawCompressFromIOVec(iov, uncompressed_length, compressed, compressed_length,
2345
0
                       CompressionOptions{});
2346
0
}
2347
2348
void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
2349
                          char* compressed, size_t* compressed_length,
2350
0
                          CompressionOptions options) {
2351
0
  SnappyIOVecReader reader(iov, uncompressed_length);
2352
0
  UncheckedByteArraySink writer(compressed);
2353
0
  Compress(&reader, &writer, options);
2354
2355
  // Compute how many bytes were added.
2356
0
  *compressed_length = writer.CurrentDestination() - compressed;
2357
0
}
2358
2359
size_t Compress(const char* input, size_t input_length,
2360
0
                std::string* compressed) {
2361
0
  return Compress(input, input_length, compressed, CompressionOptions{});
2362
0
}
2363
2364
size_t Compress(const char* input, size_t input_length, std::string* compressed,
2365
4.83k
                CompressionOptions options) {
2366
  // Pre-grow the buffer to the max length of the compressed output
2367
4.83k
  STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
2368
2369
4.83k
  size_t compressed_length;
2370
4.83k
  RawCompress(input, input_length, string_as_array(compressed),
2371
4.83k
              &compressed_length, options);
2372
4.83k
  compressed->erase(compressed_length);
2373
4.83k
  return compressed_length;
2374
4.83k
}
2375
2376
size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
2377
0
                         std::string* compressed) {
2378
0
  return CompressFromIOVec(iov, iov_cnt, compressed, CompressionOptions{});
2379
0
}
2380
2381
size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
2382
0
                         std::string* compressed, CompressionOptions options) {
2383
  // Compute the number of bytes to be compressed.
2384
0
  size_t uncompressed_length = 0;
2385
0
  for (size_t i = 0; i < iov_cnt; ++i) {
2386
0
    uncompressed_length += iov[i].iov_len;
2387
0
  }
2388
2389
  // Pre-grow the buffer to the max length of the compressed output.
2390
0
  STLStringResizeUninitialized(compressed, MaxCompressedLength(
2391
0
      uncompressed_length));
2392
2393
0
  size_t compressed_length;
2394
0
  RawCompressFromIOVec(iov, uncompressed_length, string_as_array(compressed),
2395
0
                       &compressed_length, options);
2396
0
  compressed->erase(compressed_length);
2397
0
  return compressed_length;
2398
0
}
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
0
  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
0
      : allocator_(allocator),
2436
0
        full_size_(0),
2437
0
        op_base_(NULL),
2438
0
        op_ptr_(NULL),
2439
0
        op_limit_(NULL),
2440
0
        op_limit_min_slop_(NULL) {}
2441
0
  char* GetOutputPtr() { return op_ptr_; }
2442
0
  char* GetBase(ptrdiff_t* op_limit_min_slop) {
2443
0
    *op_limit_min_slop = op_limit_min_slop_ - op_base_;
2444
0
    return op_base_;
2445
0
  }
2446
0
  void SetOutputPtr(char* op) { op_ptr_ = op; }
2447
2448
0
  inline void SetExpectedLength(size_t len) {
2449
0
    assert(blocks_.empty());
2450
0
    expected_ = len;
2451
0
  }
2452
2453
0
  inline bool CheckLength() const { return Size() == expected_; }
2454
2455
  // Return the number of bytes actually uncompressed so far
2456
0
  inline size_t Produced() const { return Size(); }
2457
2458
0
  inline bool Append(const char* ip, size_t len, char** op_p) {
2459
0
    char* op = *op_p;
2460
0
    size_t avail = op_limit_ - op;
2461
0
    if (len <= avail) {
2462
      // Fast path
2463
0
      std::memcpy(op, ip, len);
2464
0
      *op_p = op + len;
2465
0
      return true;
2466
0
    } else {
2467
0
      op_ptr_ = op;
2468
0
      bool res = SlowAppend(ip, len);
2469
0
      *op_p = op_ptr_;
2470
0
      return res;
2471
0
    }
2472
0
  }
2473
2474
  inline bool TryFastAppend(const char* ip, size_t available, size_t length,
2475
0
                            char** op_p) {
2476
0
    char* op = *op_p;
2477
0
    const int space_left = op_limit_ - op;
2478
0
    if (length <= 16 && available >= 16 + kMaximumTagLength &&
2479
0
        space_left >= 16) {
2480
      // Fast path, used for the majority (about 95%) of invocations.
2481
0
      UnalignedCopy128(ip, op);
2482
0
      *op_p = op + length;
2483
0
      return true;
2484
0
    } else {
2485
0
      return false;
2486
0
    }
2487
0
  }
2488
2489
0
  inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
2490
0
    char* op = *op_p;
2491
0
    assert(op >= op_base_);
2492
    // Check if we try to append from before the start of the buffer.
2493
0
    if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
2494
0
                            static_cast<size_t>(op - op_base_) < offset ||
2495
0
                            op >= op_limit_min_slop_ || offset < len)) {
2496
0
      if (offset == 0) return false;
2497
0
      if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - op_base_) < offset ||
2498
0
                              op + len > op_limit_)) {
2499
0
        op_ptr_ = op;
2500
0
        bool res = SlowAppendFromSelf(offset, len);
2501
0
        *op_p = op_ptr_;
2502
0
        return res;
2503
0
      }
2504
0
      *op_p = IncrementalCopy(op - offset, op, op + len, op_limit_);
2505
0
      return true;
2506
0
    }
2507
    // Fast path
2508
0
    char* const op_end = op + len;
2509
0
    std::memmove(op, op - offset, kSlopBytes);
2510
0
    *op_p = op_end;
2511
0
    return true;
2512
0
  }
2513
2514
  // Called at the end of the decompress. We ask the allocator
2515
  // write all blocks to the sink.
2516
0
  inline void Flush() { allocator_.Flush(Produced()); }
2517
};
2518
2519
template <typename Allocator>
2520
0
bool SnappyScatteredWriter<Allocator>::SlowAppend(const char* ip, size_t len) {
2521
0
  size_t avail = op_limit_ - op_ptr_;
2522
0
  while (len > avail) {
2523
    // Completely fill this block
2524
0
    std::memcpy(op_ptr_, ip, avail);
2525
0
    op_ptr_ += avail;
2526
0
    assert(op_limit_ - op_ptr_ == 0);
2527
0
    full_size_ += (op_ptr_ - op_base_);
2528
0
    len -= avail;
2529
0
    ip += avail;
2530
2531
    // Bounds check
2532
0
    if (full_size_ + len > expected_) return false;
2533
2534
    // Make new block
2535
0
    size_t bsize = std::min<size_t>(kBlockSize, expected_ - full_size_);
2536
0
    op_base_ = allocator_.Allocate(bsize);
2537
0
    op_ptr_ = op_base_;
2538
0
    op_limit_ = op_base_ + bsize;
2539
0
    op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, bsize);
2540
2541
0
    blocks_.push_back(op_base_);
2542
0
    avail = bsize;
2543
0
  }
2544
2545
0
  std::memcpy(op_ptr_, ip, len);
2546
0
  op_ptr_ += len;
2547
0
  return true;
2548
0
}
2549
2550
template <typename Allocator>
2551
bool SnappyScatteredWriter<Allocator>::SlowAppendFromSelf(size_t offset,
2552
0
                                                         size_t len) {
2553
  // Overflow check
2554
  // See SnappyArrayWriter::AppendFromSelf for an explanation of
2555
  // the "offset - 1u" trick.
2556
0
  const size_t cur = Size();
2557
0
  if (offset - 1u >= cur) return false;
2558
0
  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
0
  size_t src = cur - offset;
2569
0
  char* op = op_ptr_;
2570
0
  while (len-- > 0) {
2571
0
    char c = blocks_[src >> kBlockLog][src & (kBlockSize - 1)];
2572
0
    if (!Append(&c, 1, &op)) {
2573
0
      op_ptr_ = op;
2574
0
      return false;
2575
0
    }
2576
0
    src++;
2577
0
  }
2578
0
  op_ptr_ = op;
2579
0
  return true;
2580
0
}
2581
2582
class SnappySinkAllocator {
2583
 public:
2584
0
  explicit SnappySinkAllocator(Sink* dest) : dest_(dest) {}
2585
2586
0
  char* Allocate(int size) {
2587
0
    Datablock block(new char[size], size);
2588
0
    blocks_.push_back(block);
2589
0
    return block.data;
2590
0
  }
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
0
  void Flush(size_t size) {
2598
0
    size_t size_written = 0;
2599
0
    for (Datablock& block : blocks_) {
2600
0
      size_t block_size = std::min<size_t>(block.size, size - size_written);
2601
0
      dest_->AppendAndTakeOwnership(block.data, block_size,
2602
0
                                    &SnappySinkAllocator::Deleter, NULL);
2603
0
      size_written += block_size;
2604
0
    }
2605
0
    blocks_.clear();
2606
0
  }
2607
2608
 private:
2609
  struct Datablock {
2610
    char* data;
2611
    size_t size;
2612
0
    Datablock(char* p, size_t s) : data(p), size(s) {}
2613
  };
2614
2615
0
  static void Deleter(void* arg, const char* bytes, size_t size) {
2616
    // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2617
0
    (void)arg;
2618
0
    (void)size;
2619
2620
0
    delete[] bytes;
2621
0
  }
2622
2623
  Sink* dest_;
2624
  std::vector<Datablock> blocks_;
2625
2626
  // Note: copying this object is allowed
2627
};
2628
2629
0
size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) {
2630
0
  SnappySinkAllocator allocator(uncompressed);
2631
0
  SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
2632
0
  InternalUncompress(compressed, &writer);
2633
0
  return writer.Produced();
2634
0
}
2635
2636
0
bool Uncompress(Source* compressed, Sink* uncompressed) {
2637
  // Read the uncompressed length from the front of the compressed input
2638
0
  SnappyDecompressor decompressor(compressed);
2639
0
  uint32_t uncompressed_len = 0;
2640
0
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) {
2641
0
    return false;
2642
0
  }
2643
2644
0
  char c;
2645
0
  size_t allocated_size;
2646
0
  char* buf = uncompressed->GetAppendBufferVariable(1, uncompressed_len, &c, 1,
2647
0
                                                    &allocated_size);
2648
2649
0
  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
0
  if (allocated_size >= uncompressed_len) {
2653
0
    SnappyArrayWriter writer(buf);
2654
0
    bool result = InternalUncompressAllTags(&decompressor, &writer,
2655
0
                                            compressed_len, uncompressed_len);
2656
0
    uncompressed->Append(buf, writer.Produced());
2657
0
    return result;
2658
0
  } else {
2659
0
    SnappySinkAllocator allocator(uncompressed);
2660
0
    SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
2661
0
    return InternalUncompressAllTags(&decompressor, &writer, compressed_len,
2662
0
                                     uncompressed_len);
2663
0
  }
2664
0
}
2665
2666
}  // namespace snappy