Coverage Report

Created: 2026-02-26 06:26

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
12.5M
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
12.5M
  constexpr uint32_t kMagic = 0x1e35a7bd;
173
12.5M
  const uint32_t hash = (kMagic * bytes) >> (31 - kMaxHashTableBits);
174
12.5M
#endif
175
12.5M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
176
12.5M
                                     (hash & mask));
177
12.5M
}
178
179
inline uint16_t* TableEntry4ByteMatch(uint16_t* table, uint32_t bytes,
180
33.1M
                                      uint32_t mask) {
181
33.1M
  constexpr uint32_t kMagic = 2654435761U;
182
33.1M
  const uint32_t hash = (kMagic * bytes) >> (32 - kMaxHashTableBits);
183
33.1M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
184
33.1M
                                     (hash & mask));
185
33.1M
}
186
187
inline uint16_t* TableEntry8ByteMatch(uint16_t* table, uint64_t bytes,
188
42.3M
                                      uint32_t mask) {
189
42.3M
  constexpr uint64_t kMagic = 58295818150454627ULL;
190
42.3M
  const uint32_t hash = (kMagic * bytes) >> (64 - kMaxHashTableBits);
191
42.3M
  return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(table) +
192
42.3M
                                     (hash & mask));
193
42.3M
}
194
195
}  // namespace
196
197
26.8k
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
26.8k
  return 32 + source_bytes + source_bytes / 6;
219
26.8k
}
220
221
namespace {
222
223
173k
void UnalignedCopy64(const void* src, void* dst) {
224
173k
  char tmp[8];
225
173k
  std::memcpy(tmp, src, 8);
226
173k
  std::memcpy(dst, tmp, 8);
227
173k
}
228
229
2.02M
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.02M
  char tmp[16];
234
2.02M
  std::memcpy(tmp, src, 16);
235
2.02M
  std::memcpy(dst, tmp, 16);
236
2.02M
}
237
238
template <bool use_16bytes_chunk>
239
57.2k
inline void ConditionalUnalignedCopy128(const char* src, char* dst) {
240
57.2k
  if (use_16bytes_chunk) {
241
0
    UnalignedCopy128(src, dst);
242
57.2k
  } else {
243
57.2k
    UnalignedCopy64(src, dst);
244
57.2k
    UnalignedCopy64(src + 8, dst + 8);
245
57.2k
  }
246
57.2k
}
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.96k
                                 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.96k
#ifdef __clang__
265
1.96k
#pragma clang loop unroll(disable)
266
1.96k
#endif
267
6.03k
  while (op < op_limit) {
268
4.06k
    *op++ = *src++;
269
4.06k
  }
270
1.96k
  return op_limit;
271
1.96k
}
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.62M
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.62M
  if (SNAPPY_PREDICT_TRUE(offset < 16)) {
395
1.58M
    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
26.9M
    for (int i = 0; i < 16; i++) dst[i] = (dst - offset)[i];
399
    // Find a multiple of pattern >= 16.
400
1.58M
    static std::array<uint8_t, 16> pattern_sizes = []() {
401
2
      std::array<uint8_t, 16> res;
402
32
      for (int i = 1; i < 16; i++) res[i] = (16 / i + 1) * i;
403
2
      return res;
404
2
    }();
405
1.58M
    offset = pattern_sizes[offset];
406
6.34M
    for (int i = 1; i < 4; i++) {
407
4.75M
      std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
408
4.75M
    }
409
1.58M
    return true;
410
1.58M
  }
411
34.7k
#endif  // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
412
413
  // Very rare.
414
173k
  for (int i = 0; i < 4; i++) {
415
138k
    std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
416
138k
  }
417
34.7k
  return true;
418
1.62M
}
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
26.9k
                             char* const buf_limit) {
425
#if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
426
  constexpr int big_pattern_size_lower_bound = 16;
427
#else
428
26.9k
  constexpr int big_pattern_size_lower_bound = 8;
429
26.9k
#endif
430
431
  // Terminology:
432
  //
433
  // slop = buf_limit - op
434
  // pat  = op - src
435
  // len  = op_limit - op
436
26.9k
  assert(src < op);
437
26.9k
  assert(op < op_limit);
438
26.9k
  assert(op_limit <= buf_limit);
439
  // NOTE: The copy tags use 3 or 6 bits to store the copy length, so len <= 64.
440
26.9k
  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
26.9k
  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
26.9k
  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
21.7k
    if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) {
545
78.8k
      while (pattern_size < 8) {
546
57.3k
        UnalignedCopy64(src, op);
547
57.3k
        op += pattern_size;
548
57.3k
        pattern_size *= 2;
549
57.3k
      }
550
21.5k
      if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
551
21.5k
    } else {
552
199
      return IncrementalCopySlow(src, op, op_limit);
553
199
    }
554
21.7k
#endif  // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
555
21.7k
  }
556
26.9k
  assert(pattern_size >= big_pattern_size_lower_bound);
557
20.4k
  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
20.4k
  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
18.2k
    ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
572
18.2k
    if (op + 16 < op_limit) {
573
12.9k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 16, op + 16);
574
12.9k
    }
575
18.2k
    if (op + 32 < op_limit) {
576
12.2k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 32, op + 32);
577
12.2k
    }
578
18.2k
    if (op + 48 < op_limit) {
579
11.9k
      ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 48, op + 48);
580
11.9k
    }
581
18.2k
    return op_limit;
582
18.2k
  }
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
2.16k
#ifdef __clang__
591
2.16k
#pragma clang loop unroll(disable)
592
2.16k
#endif
593
4.01k
  for (char* op_end = buf_limit - 16; op < op_end; op += 16, src += 16) {
594
1.85k
    ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
595
1.85k
  }
596
2.16k
  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.76k
  if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) {
601
1.34k
    UnalignedCopy64(src, op);
602
1.34k
    src += 8;
603
1.34k
    op += 8;
604
1.34k
  }
605
1.76k
  return IncrementalCopySlow(src, op, op_limit);
606
2.16k
}
607
608
}  // namespace
609
610
template <bool allow_fast_path>
611
1.24M
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.24M
  assert(len > 0);  // Zero-length literals are disallowed
623
1.24M
  int n = len - 1;
624
1.24M
  if (allow_fast_path && len <= 16) {
625
    // Fits in tag byte
626
1.06M
    *op++ = LITERAL | (n << 2);
627
628
1.06M
    UnalignedCopy128(literal, op);
629
1.06M
    return op + len;
630
1.06M
  }
631
632
185k
  if (n < 60) {
633
    // Fits in tag byte
634
119k
    *op++ = LITERAL | (n << 2);
635
119k
  } else {
636
66.0k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
66.0k
    assert(count >= 1);
638
66.0k
    assert(count <= 4);
639
66.0k
    *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
66.0k
    LittleEndian::Store32(op, n);
645
66.0k
    op += count;
646
66.0k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
185k
  if (allow_fast_path) {
649
177k
    char* destination = op;
650
177k
    const char* source = literal;
651
177k
    const char* end = destination + len;
652
3.14M
    do {
653
3.14M
      std::memcpy(destination, source, 16);
654
3.14M
      destination += 16;
655
3.14M
      source += 16;
656
3.14M
    } while (destination < end);
657
177k
  } else {
658
7.17k
    std::memcpy(op, literal, len);
659
7.17k
  }
660
185k
  return op + len;
661
185k
}
snappy.cc:char* snappy::EmitLiteral<true>(char*, char const*, int)
Line
Count
Source
611
1.24M
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.24M
  assert(len > 0);  // Zero-length literals are disallowed
623
1.24M
  int n = len - 1;
624
1.24M
  if (allow_fast_path && len <= 16) {
625
    // Fits in tag byte
626
1.06M
    *op++ = LITERAL | (n << 2);
627
628
1.06M
    UnalignedCopy128(literal, op);
629
1.06M
    return op + len;
630
1.06M
  }
631
632
177k
  if (n < 60) {
633
    // Fits in tag byte
634
114k
    *op++ = LITERAL | (n << 2);
635
114k
  } else {
636
63.2k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
63.2k
    assert(count >= 1);
638
63.2k
    assert(count <= 4);
639
63.2k
    *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
63.2k
    LittleEndian::Store32(op, n);
645
63.2k
    op += count;
646
63.2k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
177k
  if (allow_fast_path) {
649
177k
    char* destination = op;
650
177k
    const char* source = literal;
651
177k
    const char* end = destination + len;
652
3.14M
    do {
653
3.14M
      std::memcpy(destination, source, 16);
654
3.14M
      destination += 16;
655
3.14M
      source += 16;
656
3.14M
    } while (destination < end);
657
177k
  } else {
658
0
    std::memcpy(op, literal, len);
659
0
  }
660
177k
  return op + len;
661
177k
}
snappy.cc:char* snappy::EmitLiteral<false>(char*, char const*, int)
Line
Count
Source
611
7.17k
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
7.17k
  assert(len > 0);  // Zero-length literals are disallowed
623
7.17k
  int n = len - 1;
624
7.17k
  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
7.17k
  if (n < 60) {
633
    // Fits in tag byte
634
4.44k
    *op++ = LITERAL | (n << 2);
635
4.44k
  } else {
636
2.73k
    int count = (Bits::Log2Floor(n) >> 3) + 1;
637
2.73k
    assert(count >= 1);
638
2.73k
    assert(count <= 4);
639
2.73k
    *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.73k
    LittleEndian::Store32(op, n);
645
2.73k
    op += count;
646
2.73k
  }
647
  // When allow_fast_path is true, we can overwrite up to 16 bytes.
648
7.17k
  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
7.17k
  } else {
658
7.17k
    std::memcpy(op, literal, len);
659
7.17k
  }
660
7.17k
  return op + len;
661
7.17k
}
662
663
template <bool len_less_than_12>
664
8.58M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
8.58M
  assert(len <= 64);
666
8.58M
  assert(len >= 4);
667
8.58M
  assert(offset < 65536);
668
8.58M
  assert(len_less_than_12 == (len < 12));
669
670
8.58M
  if (len_less_than_12) {
671
4.83M
    uint32_t u = (len << 2) + (offset << 8);
672
4.83M
    uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
4.83M
    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
4.83M
    u += offset < 2048 ? copy1 : copy2;
680
4.83M
    LittleEndian::Store32(op, u);
681
4.83M
    op += offset < 2048 ? 2 : 3;
682
4.83M
  } 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.74M
    uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
3.74M
    LittleEndian::Store32(op, u);
687
3.74M
    op += 3;
688
3.74M
  }
689
8.58M
  return op;
690
8.58M
}
snappy.cc:char* snappy::EmitCopyAtMost64<true>(char*, unsigned long, unsigned long)
Line
Count
Source
664
4.83M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
4.83M
  assert(len <= 64);
666
4.83M
  assert(len >= 4);
667
4.83M
  assert(offset < 65536);
668
4.83M
  assert(len_less_than_12 == (len < 12));
669
670
4.83M
  if (len_less_than_12) {
671
4.83M
    uint32_t u = (len << 2) + (offset << 8);
672
4.83M
    uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
673
4.83M
    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
4.83M
    u += offset < 2048 ? copy1 : copy2;
680
4.83M
    LittleEndian::Store32(op, u);
681
4.83M
    op += offset < 2048 ? 2 : 3;
682
4.83M
  } 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
4.83M
  return op;
690
4.83M
}
snappy.cc:char* snappy::EmitCopyAtMost64<false>(char*, unsigned long, unsigned long)
Line
Count
Source
664
3.74M
static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
665
3.74M
  assert(len <= 64);
666
3.74M
  assert(len >= 4);
667
3.74M
  assert(offset < 65536);
668
3.74M
  assert(len_less_than_12 == (len < 12));
669
670
3.74M
  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.74M
  } 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.74M
    uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
686
3.74M
    LittleEndian::Store32(op, u);
687
3.74M
    op += 3;
688
3.74M
  }
689
3.74M
  return op;
690
3.74M
}
691
692
template <bool len_less_than_12>
693
6.35M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
6.35M
  assert(len_less_than_12 == (len < 12));
695
6.35M
  if (len_less_than_12) {
696
4.80M
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
4.80M
  } 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.77M
    while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
2.22M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
2.22M
      len -= 64;
705
2.22M
    }
706
707
    // One or two copies will now finish the job.
708
1.54M
    if (len > 64) {
709
8.64k
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
8.64k
      len -= 60;
711
8.64k
    }
712
713
    // Emit remainder.
714
1.54M
    if (len < 12) {
715
30.4k
      op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
1.51M
    } else {
717
1.51M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
1.51M
    }
719
1.54M
    return op;
720
1.54M
  }
721
6.35M
}
snappy.cc:char* snappy::EmitCopy<true>(char*, unsigned long, unsigned long)
Line
Count
Source
693
4.80M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
4.80M
  assert(len_less_than_12 == (len < 12));
695
4.80M
  if (len_less_than_12) {
696
4.80M
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
4.80M
  } 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
4.80M
}
snappy.cc:char* snappy::EmitCopy<false>(char*, unsigned long, unsigned long)
Line
Count
Source
693
1.54M
static inline char* EmitCopy(char* op, size_t offset, size_t len) {
694
1.54M
  assert(len_less_than_12 == (len < 12));
695
1.54M
  if (len_less_than_12) {
696
0
    return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
697
1.54M
  } 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.77M
    while (SNAPPY_PREDICT_FALSE(len >= 68)) {
703
2.22M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
704
2.22M
      len -= 64;
705
2.22M
    }
706
707
    // One or two copies will now finish the job.
708
1.54M
    if (len > 64) {
709
8.64k
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
710
8.64k
      len -= 60;
711
8.64k
    }
712
713
    // Emit remainder.
714
1.54M
    if (len < 12) {
715
30.4k
      op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
716
1.51M
    } else {
717
1.51M
      op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
718
1.51M
    }
719
1.54M
    return op;
720
1.54M
  }
721
1.54M
}
722
723
7.97k
bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
724
7.97k
  uint32_t v = 0;
725
7.97k
  const char* limit = start + n;
726
7.97k
  if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
727
7.93k
    *result = v;
728
7.93k
    return true;
729
7.93k
  } else {
730
44
    return false;
731
44
  }
732
7.97k
}
733
734
namespace {
735
15.7k
uint32_t CalculateTableSize(uint32_t input_size) {
736
15.7k
  static_assert(
737
15.7k
      kMaxHashTableSize >= kMinHashTableSize,
738
15.7k
      "kMaxHashTableSize should be greater or equal to kMinHashTableSize.");
739
15.7k
  if (input_size > kMaxHashTableSize) {
740
6.11k
    return kMaxHashTableSize;
741
6.11k
  }
742
9.63k
  if (input_size < kMinHashTableSize) {
743
6.75k
    return kMinHashTableSize;
744
6.75k
  }
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.88k
  return 2u << Bits::Log2Floor(input_size - 1);
748
9.63k
}
749
}  // namespace
750
751
namespace internal {
752
5.56k
WorkingMemory::WorkingMemory(size_t input_size) {
753
5.56k
  const size_t max_fragment_size = std::min(input_size, kBlockSize);
754
5.56k
  const size_t table_size = CalculateTableSize(max_fragment_size);
755
5.56k
  size_ = table_size * sizeof(*table_) + max_fragment_size +
756
5.56k
          MaxCompressedLength(max_fragment_size);
757
5.56k
  mem_ = std::allocator<char>().allocate(size_);
758
5.56k
  table_ = reinterpret_cast<uint16_t*>(mem_);
759
5.56k
  input_ = mem_ + table_size * sizeof(*table_);
760
5.56k
  output_ = input_ + max_fragment_size;
761
5.56k
}
762
763
5.56k
WorkingMemory::~WorkingMemory() {
764
5.56k
  std::allocator<char>().deallocate(mem_, size_);
765
5.56k
}
766
767
uint16_t* WorkingMemory::GetHashTable(size_t fragment_size,
768
10.1k
                                      int* table_size) const {
769
10.1k
  const size_t htsize = CalculateTableSize(fragment_size);
770
10.1k
  memset(table_, 0, htsize * sizeof(*table_));
771
10.1k
  *table_size = htsize;
772
10.1k
  return table_;
773
10.1k
}
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
5.09k
                       uint16_t* table, const int table_size) {
790
  // "ip" is the input pointer, and "op" is the output pointer.
791
5.09k
  const char* ip = input;
792
5.09k
  assert(input_size <= kBlockSize);
793
5.09k
  assert((table_size & (table_size - 1)) == 0);  // table must be power of two
794
5.09k
  const uint32_t mask = 2 * (table_size - 1);
795
5.09k
  const char* ip_end = input + input_size;
796
5.09k
  const char* base_ip = ip;
797
798
5.09k
  const size_t kInputMarginBytes = 15;
799
5.09k
  if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
800
5.05k
    const char* ip_limit = input + input_size - kInputMarginBytes;
801
802
1.01M
    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.01M
      const char* next_emit = ip++;
806
1.01M
      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.01M
      uint32_t skip = 32;
833
834
1.01M
      const char* candidate;
835
1.01M
      if (ip_limit - ip >= 16) {
836
1.01M
        auto delta = ip - base_ip;
837
1.55M
        for (int j = 0; j < 4; ++j) {
838
4.41M
          for (int k = 0; k < 4; ++k) {
839
3.87M
            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
3.87M
            uint32_t dword = i == 0 ? preload : static_cast<uint32_t>(data);
844
3.87M
            assert(dword == LittleEndian::Load32(ip + i));
845
3.87M
            uint16_t* table_entry = TableEntry(table, dword, mask);
846
3.87M
            candidate = base_ip + *table_entry;
847
3.87M
            assert(candidate >= base_ip);
848
3.87M
            assert(candidate < ip + i);
849
3.87M
            *table_entry = delta + i;
850
3.87M
            if (SNAPPY_PREDICT_FALSE(LittleEndian::Load32(candidate) == dword)) {
851
946k
              *op = LITERAL | (i << 2);
852
946k
              UnalignedCopy128(next_emit, op + 1);
853
946k
              ip += i;
854
946k
              op = op + i + 2;
855
946k
              goto emit_match;
856
946k
            }
857
2.93M
            data >>= 8;
858
2.93M
          }
859
534k
          data = LittleEndian::Load64(ip + 4 * j + 4);
860
534k
        }
861
70.8k
        ip += 16;
862
70.8k
        skip += 16;
863
70.8k
      }
864
2.26M
      while (true) {
865
2.26M
        assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
866
2.26M
        uint16_t* table_entry = TableEntry(table, data, mask);
867
2.26M
        uint32_t bytes_between_hash_lookups = skip >> 5;
868
2.26M
        skip += bytes_between_hash_lookups;
869
2.26M
        const char* next_ip = ip + bytes_between_hash_lookups;
870
2.26M
        if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
871
2.07k
          ip = next_emit;
872
2.07k
          goto emit_remainder;
873
2.07k
        }
874
2.26M
        candidate = base_ip + *table_entry;
875
2.26M
        assert(candidate >= base_ip);
876
2.26M
        assert(candidate < ip);
877
878
2.26M
        *table_entry = ip - base_ip;
879
2.26M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
880
2.26M
                                LittleEndian::Load32(candidate))) {
881
70.7k
          break;
882
70.7k
        }
883
2.18M
        data = LittleEndian::Load32(next_ip);
884
2.18M
        ip = next_ip;
885
2.18M
      }
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
72.8k
      assert(next_emit + 16 <= ip_end);
891
70.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.01M
    emit_match:
902
3.19M
      do {
903
        // We have a 4-byte match at ip, and no need to emit any
904
        // "literal bytes" prior to ip.
905
3.19M
        const char* base = ip;
906
3.19M
        std::pair<size_t, bool> p =
907
3.19M
            FindMatchLength(candidate + 4, ip + 4, ip_end, &data);
908
3.19M
        size_t matched = 4 + p.first;
909
3.19M
        ip += matched;
910
3.19M
        size_t offset = base - candidate;
911
3.19M
        assert(0 == memcmp(base, candidate, matched));
912
3.19M
        if (p.second) {
913
2.46M
          op = EmitCopy</*len_less_than_12=*/true>(op, offset, matched);
914
2.46M
        } else {
915
733k
          op = EmitCopy</*len_less_than_12=*/false>(op, offset, matched);
916
733k
        }
917
3.19M
        if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
918
2.98k
          goto emit_remainder;
919
2.98k
        }
920
        // Expect 5 bytes to match
921
3.19M
        assert((data & 0xFFFFFFFFFF) ==
922
3.19M
               (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.19M
        *TableEntry(table, LittleEndian::Load32(ip - 1), mask) =
927
3.19M
            ip - base_ip - 1;
928
3.19M
        uint16_t* table_entry = TableEntry(table, data, mask);
929
3.19M
        candidate = base_ip + *table_entry;
930
3.19M
        *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.19M
      } 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.01M
      preload = data >> 8;
945
1.01M
    }
946
5.05k
  }
947
948
5.09k
emit_remainder:
949
  // Emit the remaining bytes as a literal
950
5.09k
  if (ip < ip_end) {
951
3.67k
    op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
952
3.67k
  }
953
954
5.09k
  return op;
955
5.09k
}
956
957
char* CompressFragmentDoubleHash(const char* input, size_t input_size, char* op,
958
                                 uint16_t* table, const int table_size,
959
5.09k
                                 uint16_t* table2, const int table_size2) {
960
5.09k
  (void)table_size2;
961
5.09k
  assert(table_size == table_size2);
962
  // "ip" is the input pointer, and "op" is the output pointer.
963
5.09k
  const char* ip = input;
964
5.09k
  assert(input_size <= kBlockSize);
965
5.09k
  assert((table_size & (table_size - 1)) == 0);  // table must be power of two
966
5.09k
  const uint32_t mask = 2 * (table_size - 1);
967
5.09k
  const char* ip_end = input + input_size;
968
5.09k
  const char* base_ip = ip;
969
970
5.09k
  const size_t kInputMarginBytes = 15;
971
5.09k
  if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
972
5.05k
    const char* ip_limit = input + input_size - kInputMarginBytes;
973
974
1.18M
    for (;;) {
975
1.18M
      const char* next_emit = ip++;
976
1.18M
      uint64_t data = LittleEndian::Load64(ip);
977
1.18M
      uint32_t skip = 512;
978
979
1.18M
      const char* candidate;
980
1.18M
      uint32_t candidate_length;
981
23.5M
      while (true) {
982
23.5M
        assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
983
23.5M
        uint16_t* table_entry2 = TableEntry8ByteMatch(table2, data, mask);
984
23.5M
        uint32_t bytes_between_hash_lookups = skip >> 9;
985
23.5M
        skip++;
986
23.5M
        const char* next_ip = ip + bytes_between_hash_lookups;
987
23.5M
        if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
988
1.75k
          ip = next_emit;
989
1.75k
          goto emit_remainder;
990
1.75k
        }
991
23.5M
        candidate = base_ip + *table_entry2;
992
23.5M
        assert(candidate >= base_ip);
993
23.5M
        assert(candidate < ip);
994
995
23.5M
        *table_entry2 = ip - base_ip;
996
23.5M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
997
23.5M
                                LittleEndian::Load32(candidate))) {
998
454k
          candidate_length =
999
454k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1000
454k
          break;
1001
454k
        }
1002
1003
23.0M
        uint16_t* table_entry = TableEntry4ByteMatch(table, data, mask);
1004
23.0M
        candidate = base_ip + *table_entry;
1005
23.0M
        assert(candidate >= base_ip);
1006
23.0M
        assert(candidate < ip);
1007
1008
23.0M
        *table_entry = ip - base_ip;
1009
23.0M
        if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
1010
23.0M
                                LittleEndian::Load32(candidate))) {
1011
726k
          candidate_length =
1012
726k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1013
726k
          table_entry2 =
1014
726k
              TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask);
1015
726k
          auto candidate2 = base_ip + *table_entry2;
1016
726k
          size_t candidate_length2 =
1017
726k
              FindMatchLengthPlain(candidate2, ip + 1, ip_end);
1018
726k
          if (candidate_length2 > candidate_length) {
1019
25.7k
            *table_entry2 = ip - base_ip;
1020
25.7k
            candidate = candidate2;
1021
25.7k
            candidate_length = candidate_length2;
1022
25.7k
            ++ip;
1023
25.7k
          }
1024
726k
          break;
1025
726k
        }
1026
22.3M
        data = LittleEndian::Load64(next_ip);
1027
22.3M
        ip = next_ip;
1028
22.3M
      }
1029
      // Backtrack to the point it matches fully.
1030
1.31M
      while (ip > next_emit && candidate > base_ip &&
1031
1.29M
             *(ip - 1) == *(candidate - 1)) {
1032
133k
        --ip;
1033
133k
        --candidate;
1034
133k
        ++candidate_length;
1035
133k
      }
1036
1.18M
      *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 1), mask) =
1037
1.18M
          ip - base_ip + 1;
1038
1.18M
      *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip + 2), mask) =
1039
1.18M
          ip - base_ip + 2;
1040
1.18M
      *TableEntry4ByteMatch(table, LittleEndian::Load32(ip + 1), mask) =
1041
1.18M
          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.18M
      assert(next_emit + 16 <= ip_end);
1047
1.18M
      if (ip - next_emit > 0) {
1048
1.17M
        op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit,
1049
1.17M
                                                   ip - next_emit);
1050
1.17M
      }
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.15M
      do {
1060
        // We have a 4-byte match at ip, and no need to emit any
1061
        // "literal bytes" prior to ip.
1062
3.15M
        const char* base = ip;
1063
3.15M
        ip += candidate_length;
1064
3.15M
        size_t offset = base - candidate;
1065
3.15M
        if (candidate_length < 12) {
1066
2.34M
          op =
1067
2.34M
              EmitCopy</*len_less_than_12=*/true>(op, offset, candidate_length);
1068
2.34M
        } else {
1069
809k
          op = EmitCopy</*len_less_than_12=*/false>(op, offset,
1070
809k
                                                    candidate_length);
1071
809k
        }
1072
3.15M
        if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
1073
3.30k
          goto emit_remainder;
1074
3.30k
        }
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.15M
        if (ip - base_ip > 7) {
1079
3.15M
          *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 7), mask) =
1080
3.15M
              ip - base_ip - 7;
1081
3.15M
          *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 4), mask) =
1082
3.15M
              ip - base_ip - 4;
1083
3.15M
        }
1084
3.15M
        *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 3), mask) =
1085
3.15M
            ip - base_ip - 3;
1086
3.15M
        *TableEntry8ByteMatch(table2, LittleEndian::Load64(ip - 2), mask) =
1087
3.15M
            ip - base_ip - 2;
1088
3.15M
        *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 2), mask) =
1089
3.15M
            ip - base_ip - 2;
1090
3.15M
        *TableEntry4ByteMatch(table, LittleEndian::Load32(ip - 1), mask) =
1091
3.15M
            ip - base_ip - 1;
1092
1093
3.15M
        uint16_t* table_entry =
1094
3.15M
            TableEntry8ByteMatch(table2, LittleEndian::Load64(ip), mask);
1095
3.15M
        candidate = base_ip + *table_entry;
1096
3.15M
        *table_entry = ip - base_ip;
1097
3.15M
        if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1098
591k
          candidate_length =
1099
591k
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1100
591k
          continue;
1101
591k
        }
1102
2.56M
        table_entry =
1103
2.56M
            TableEntry4ByteMatch(table, LittleEndian::Load32(ip), mask);
1104
2.56M
        candidate = base_ip + *table_entry;
1105
2.56M
        *table_entry = ip - base_ip;
1106
2.56M
        if (LittleEndian::Load32(ip) == LittleEndian::Load32(candidate)) {
1107
1.38M
          candidate_length =
1108
1.38M
              FindMatchLengthPlain(candidate + 4, ip + 4, ip_end) + 4;
1109
1.38M
          continue;
1110
1.38M
        }
1111
1.17M
        break;
1112
2.56M
      } while (true);
1113
1.18M
    }
1114
5.05k
  }
1115
1116
5.09k
emit_remainder:
1117
  // Emit the remaining bytes as a literal
1118
5.09k
  if (ip < ip_end) {
1119
3.50k
    op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
1120
3.50k
  }
1121
1122
5.09k
  return op;
1123
5.09k
}
1124
}  // end namespace internal
1125
1126
static inline void Report(int token, const char *algorithm, size_t
1127
17.8k
compressed_size, size_t uncompressed_size) {
1128
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1129
17.8k
  (void)token;
1130
17.8k
  (void)algorithm;
1131
17.8k
  (void)compressed_size;
1132
17.8k
  (void)uncompressed_size;
1133
17.8k
}
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
229k
static inline uint32_t ExtractLowBytes(const uint32_t& v, int n) {
1192
229k
  assert(n >= 0);
1193
229k
  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
229k
  uint64_t mask = 0xffffffff;
1200
229k
  return v & ~(mask << (8 * n));
1201
229k
#endif
1202
229k
}
1203
1204
21.5k
static inline bool LeftShiftOverflows(uint8_t value, uint32_t shift) {
1205
21.5k
  assert(shift < 32);
1206
21.5k
  static const uint8_t masks[] = {
1207
21.5k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1208
21.5k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1209
21.5k
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  //
1210
21.5k
      0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
1211
21.5k
  return (value & masks[shift]) != 0;
1212
21.5k
}
1213
1214
1.42M
inline bool Copy64BytesWithPatternExtension(ptrdiff_t dst, size_t offset) {
1215
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1216
1.42M
  (void)dst;
1217
1.42M
  return offset != 0;
1218
1.42M
}
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
10.9M
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
10.9M
  constexpr int kShortMemCopy = 32;
1227
10.9M
  (void)kShortMemCopy;
1228
10.9M
  assert(size <= 64);
1229
10.9M
  assert(std::less_equal<const void*>()(static_cast<const char*>(src) + size,
1230
10.9M
                                        dst) ||
1231
10.9M
         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
10.9M
  std::memmove(dst, src, kShortMemCopy);
1269
  // Profiling shows that nearly all copies are short.
1270
10.9M
  if (SNAPPY_PREDICT_FALSE(size > kShortMemCopy)) {
1271
2.09M
    std::memmove(dst + kShortMemCopy,
1272
2.09M
                 static_cast<const uint8_t*>(src) + kShortMemCopy,
1273
2.09M
                 64 - kShortMemCopy);
1274
2.09M
  }
1275
10.9M
#endif
1276
10.9M
}
1277
1278
10.7M
void MemCopy64(ptrdiff_t dst, const void* src, size_t size) {
1279
  // TODO: Switch to [[maybe_unused]] when we can assume C++17.
1280
10.7M
  (void)dst;
1281
10.7M
  (void)src;
1282
10.7M
  (void)size;
1283
10.7M
}
1284
1285
void ClearDeferred(const void** deferred_src, size_t* deferred_length,
1286
3.44M
                   uint8_t* safe_source) {
1287
3.44M
  *deferred_src = safe_source;
1288
3.44M
  *deferred_length = 0;
1289
3.44M
}
1290
1291
void DeferMemCopy(const void** deferred_src, size_t* deferred_length,
1292
18.4M
                  const void* src, size_t length) {
1293
18.4M
  *deferred_src = src;
1294
18.4M
  *deferred_length = length;
1295
18.4M
}
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
21.6M
inline size_t AdvanceToNextTagX86Optimized(const uint8_t** ip_p, size_t* tag) {
1322
21.6M
  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
21.6M
  size_t literal_len = *tag >> 2;
1331
21.6M
  size_t tag_type = *tag;
1332
21.6M
  bool is_literal;
1333
21.6M
#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
21.6M
  asm("and $3, %k[tag_type]\n\t"
1337
21.6M
      : [tag_type] "+r"(tag_type), "=@ccz"(is_literal)
1338
21.6M
      :: "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
21.6M
  size_t tag_literal =
1349
21.6M
      static_cast<const volatile uint8_t*>(ip)[1 + literal_len];
1350
21.6M
  size_t tag_copy = static_cast<const volatile uint8_t*>(ip)[tag_type];
1351
21.6M
  *tag = is_literal ? tag_literal : tag_copy;
1352
21.6M
  const uint8_t* ip_copy = ip + 1 + tag_type;
1353
21.6M
  const uint8_t* ip_literal = ip + 2 + literal_len;
1354
21.6M
  ip = is_literal ? ip_literal : ip_copy;
1355
21.6M
#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
21.6M
  asm("" ::"r"(tag_copy));
1362
21.6M
#endif
1363
21.6M
  return tag_type;
1364
21.6M
}
1365
1366
// Extract the offset for copy-1 and copy-2 returns 0 for literals or copy-4.
1367
21.6M
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
21.6M
#if defined(__x86_64__)
1372
21.6M
  constexpr uint64_t kExtractMasksCombined = 0x0000FFFF00FF0000ull;
1373
21.6M
  uint16_t result;
1374
21.6M
  memcpy(&result,
1375
21.6M
         reinterpret_cast<const char*>(&kExtractMasksCombined) + 2 * tag_type,
1376
21.6M
         sizeof(result));
1377
21.6M
  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
21.6M
};
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
268k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
268k
  uint8_t safe_source[64];
1403
268k
  const void* deferred_src;
1404
268k
  size_t deferred_length;
1405
268k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
268k
  op_limit_min_slop -= kSlopBytes;
1409
268k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
142k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
142k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
142k
    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
10.8M
    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
10.8M
      SNAPPY_PREFETCH(ip + 128);
1430
32.3M
      for (int i = 0; i < 2; i++) {
1431
21.6M
        const uint8_t* old_ip = ip;
1432
21.6M
        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
21.6M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
21.6M
        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
21.6M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
21.6M
        next = LittleEndian::Load32(old_ip);
1445
21.6M
#endif
1446
21.6M
        size_t len = len_minus_offset & 0xFF;
1447
21.6M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
21.6M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
21.6M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
3.18M
          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
138k
          break_loop:
1456
138k
            ip = old_ip;
1457
138k
            goto exit;
1458
132k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
3.18M
          assert(tag_type == 1 || tag_type == 2);
1461
3.05M
          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
3.05M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
3.05M
          op += deferred_length;
1466
3.05M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
3.05M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
3.05M
                                  !Copy64BytesWithPatternExtension(
1469
3.05M
                                      op_base + op, len - len_min_offset))) {
1470
668
            goto break_loop;
1471
668
          }
1472
          // We aren't deferring this copy so add length right away.
1473
3.05M
          op += len;
1474
3.05M
          continue;
1475
3.05M
        }
1476
18.4M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
18.4M
        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
37.3k
          if (tag_type != 0) goto break_loop;
1481
31.6k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
31.6k
          op += deferred_length;
1483
31.6k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
31.6k
          continue;
1485
37.3k
        }
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
18.4M
        const void* from =
1490
18.4M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
18.4M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
18.4M
        op += deferred_length;
1493
18.4M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
18.4M
      }
1495
10.8M
    } while (ip < ip_limit_min_slop &&
1496
10.7M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
142k
  exit:
1498
142k
    ip--;
1499
142k
    assert(ip <= ip_limit);
1500
142k
  }
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
268k
  if (deferred_length) {
1504
120k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
120k
    op += deferred_length;
1506
120k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
120k
  }
1508
268k
  return {ip, op};
1509
268k
}
std::__1::pair<unsigned char const*, long> snappy::DecompressBranchless<char*>(unsigned char const*, unsigned char const*, long, char*, long)
Line
Count
Source
1400
137k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
137k
  uint8_t safe_source[64];
1403
137k
  const void* deferred_src;
1404
137k
  size_t deferred_length;
1405
137k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
137k
  op_limit_min_slop -= kSlopBytes;
1409
137k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
69.1k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
69.1k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
69.1k
    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.48M
    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.48M
      SNAPPY_PREFETCH(ip + 128);
1430
16.3M
      for (int i = 0; i < 2; i++) {
1431
10.9M
        const uint8_t* old_ip = ip;
1432
10.9M
        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
10.9M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
10.9M
        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
10.9M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
10.9M
        next = LittleEndian::Load32(old_ip);
1445
10.9M
#endif
1446
10.9M
        size_t len = len_minus_offset & 0xFF;
1447
10.9M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
10.9M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
10.9M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
1.68M
          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
67.2k
          break_loop:
1456
67.2k
            ip = old_ip;
1457
67.2k
            goto exit;
1458
67.1k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
1.68M
          assert(tag_type == 1 || tag_type == 2);
1461
1.62M
          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.62M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
1.62M
          op += deferred_length;
1466
1.62M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
1.62M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
1.62M
                                  !Copy64BytesWithPatternExtension(
1469
1.62M
                                      op_base + op, len - len_min_offset))) {
1470
39
            goto break_loop;
1471
39
          }
1472
          // We aren't deferring this copy so add length right away.
1473
1.62M
          op += len;
1474
1.62M
          continue;
1475
1.62M
        }
1476
9.26M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
9.26M
        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
17.0k
          if (tag_type != 0) goto break_loop;
1481
17.0k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
17.0k
          op += deferred_length;
1483
17.0k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
17.0k
          continue;
1485
17.0k
        }
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.24M
        const void* from =
1490
9.24M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
9.24M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
9.24M
        op += deferred_length;
1493
9.24M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
9.24M
      }
1495
5.48M
    } while (ip < ip_limit_min_slop &&
1496
5.41M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
69.1k
  exit:
1498
69.1k
    ip--;
1499
69.1k
    assert(ip <= ip_limit);
1500
69.1k
  }
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
137k
  if (deferred_length) {
1504
58.4k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
58.4k
    op += deferred_length;
1506
58.4k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
58.4k
  }
1508
137k
  return {ip, op};
1509
137k
}
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
131k
    ptrdiff_t op_limit_min_slop) {
1401
  // If deferred_src is invalid point it here.
1402
131k
  uint8_t safe_source[64];
1403
131k
  const void* deferred_src;
1404
131k
  size_t deferred_length;
1405
131k
  ClearDeferred(&deferred_src, &deferred_length, safe_source);
1406
1407
  // We unroll the inner loop twice so we need twice the spare room.
1408
131k
  op_limit_min_slop -= kSlopBytes;
1409
131k
  if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
1410
73.0k
    const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
1411
73.0k
    ip++;
1412
    // ip points just past the tag and we are touching at maximum kSlopBytes
1413
    // in an iteration.
1414
73.0k
    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.37M
    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.37M
      SNAPPY_PREFETCH(ip + 128);
1430
16.0M
      for (int i = 0; i < 2; i++) {
1431
10.7M
        const uint8_t* old_ip = ip;
1432
10.7M
        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
10.7M
        ptrdiff_t len_minus_offset = kLengthMinusOffset[tag];
1436
10.7M
        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
10.7M
        size_t tag_type = AdvanceToNextTagX86Optimized(&ip, &tag);
1444
10.7M
        next = LittleEndian::Load32(old_ip);
1445
10.7M
#endif
1446
10.7M
        size_t len = len_minus_offset & 0xFF;
1447
10.7M
        ptrdiff_t extracted = ExtractOffset(next, tag_type);
1448
10.7M
        ptrdiff_t len_min_offset = len_minus_offset - extracted;
1449
10.7M
        if (SNAPPY_PREDICT_FALSE(len_minus_offset > extracted)) {
1450
1.49M
          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
71.4k
          break_loop:
1456
71.4k
            ip = old_ip;
1457
71.4k
            goto exit;
1458
65.2k
          }
1459
          // Only copy-1 or copy-2 tags can get here.
1460
1.49M
          assert(tag_type == 1 || tag_type == 2);
1461
1.43M
          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.43M
          MemCopy64(op_base + op, deferred_src, deferred_length);
1465
1.43M
          op += deferred_length;
1466
1.43M
          ClearDeferred(&deferred_src, &deferred_length, safe_source);
1467
1.43M
          if (SNAPPY_PREDICT_FALSE(delta < 0 ||
1468
1.43M
                                  !Copy64BytesWithPatternExtension(
1469
1.43M
                                      op_base + op, len - len_min_offset))) {
1470
629
            goto break_loop;
1471
629
          }
1472
          // We aren't deferring this copy so add length right away.
1473
1.42M
          op += len;
1474
1.42M
          continue;
1475
1.43M
        }
1476
9.22M
        std::ptrdiff_t delta = (op + deferred_length) + len_min_offset - len;
1477
9.22M
        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
20.2k
          if (tag_type != 0) goto break_loop;
1481
14.6k
          MemCopy64(op_base + op, deferred_src, deferred_length);
1482
14.6k
          op += deferred_length;
1483
14.6k
          DeferMemCopy(&deferred_src, &deferred_length, old_ip, len);
1484
14.6k
          continue;
1485
20.2k
        }
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.20M
        const void* from =
1490
9.20M
            tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
1491
9.20M
        MemCopy64(op_base + op, deferred_src, deferred_length);
1492
9.20M
        op += deferred_length;
1493
9.20M
        DeferMemCopy(&deferred_src, &deferred_length, from, len);
1494
9.20M
      }
1495
5.37M
    } while (ip < ip_limit_min_slop &&
1496
5.30M
             static_cast<ptrdiff_t>(op + deferred_length) < op_limit_min_slop);
1497
73.0k
  exit:
1498
73.0k
    ip--;
1499
73.0k
    assert(ip <= ip_limit);
1500
73.0k
  }
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
131k
  if (deferred_length) {
1504
62.2k
    MemCopy64(op_base + op, deferred_src, deferred_length);
1505
62.2k
    op += deferred_length;
1506
62.2k
    ClearDeferred(&deferred_src, &deferred_length, safe_source);
1507
62.2k
  }
1508
131k
  return {ip, op};
1509
131k
}
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
29.5k
  void ResetLimit(const char* ip) {
1532
29.5k
    ip_limit_min_maxtaglen_ =
1533
29.5k
        ip_limit_ - std::min<ptrdiff_t>(ip_limit_ - ip, kMaximumTagLength - 1);
1534
29.5k
  }
1535
1536
 public:
1537
  explicit SnappyDecompressor(Source* reader)
1538
12.3k
      : reader_(reader), ip_(NULL), ip_limit_(NULL), peeked_(0), eof_(false) {}
1539
1540
12.3k
  ~SnappyDecompressor() {
1541
    // Advance past any bytes we peeked at from the reader
1542
12.3k
    reader_->Skip(peeked_);
1543
12.3k
  }
1544
1545
  // Returns true iff we have hit the end of the input without an error.
1546
12.3k
  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
12.3k
  bool ReadUncompressedLength(uint32_t* result) {
1552
12.3k
    assert(ip_ == NULL);  // Must not have read anything yet
1553
    // Length is encoded in 1..5 bytes
1554
12.3k
    *result = 0;
1555
12.3k
    uint32_t shift = 0;
1556
21.5k
    while (true) {
1557
21.5k
      if (shift >= 32) return false;
1558
21.5k
      size_t n;
1559
21.5k
      const char* ip = reader_->Peek(&n);
1560
21.5k
      if (n == 0) return false;
1561
21.5k
      const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
1562
21.5k
      reader_->Skip(1);
1563
21.5k
      uint32_t val = c & 0x7f;
1564
21.5k
      if (LeftShiftOverflows(static_cast<uint8_t>(val), shift)) return false;
1565
21.5k
      *result |= val << shift;
1566
21.5k
      if (c < 128) {
1567
12.3k
        break;
1568
12.3k
      }
1569
9.23k
      shift += 7;
1570
9.23k
    }
1571
12.3k
    return true;
1572
12.3k
  }
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
12.3k
  DecompressAllTags(Writer* writer) {
1582
12.3k
    const char* ip = ip_;
1583
12.3k
    ResetLimit(ip);
1584
12.3k
    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
12.3k
#define MAYBE_REFILL()                                      \
1590
445k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
28.7k
    ip_ = ip;                                               \
1592
28.7k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
28.7k
    ip = ip_;                                               \
1594
17.2k
    ResetLimit(ip);                                         \
1595
17.2k
  }                                                         \
1596
445k
  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
12.3k
    uint32_t preload;
1601
12.3k
    MAYBE_REFILL();
1602
269k
    for (;;) {
1603
269k
      {
1604
269k
        ptrdiff_t op_limit_min_slop;
1605
269k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
269k
        if (op_base) {
1607
268k
          auto res =
1608
268k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
268k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
268k
                                   op - op_base, op_base, op_limit_min_slop);
1611
268k
          ip = reinterpret_cast<const char*>(res.first);
1612
268k
          op = op_base + res.second;
1613
268k
          MAYBE_REFILL();
1614
268k
        }
1615
269k
      }
1616
269k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
269k
      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
269k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
172k
        size_t literal_length = (c >> 2) + 1u;
1633
172k
        if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
12.1k
          assert(literal_length < 61);
1635
12.1k
          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
12.1k
          preload = static_cast<uint8_t>(*ip);
1640
12.1k
          continue;
1641
12.1k
        }
1642
160k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
133k
          const size_t literal_length_length = literal_length - 60;
1645
133k
          literal_length =
1646
133k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
133k
              1;
1648
133k
          ip += literal_length_length;
1649
133k
        }
1650
1651
160k
        size_t avail = ip_limit_ - ip;
1652
160k
        while (avail < literal_length) {
1653
155
          if (!writer->Append(ip, avail, &op)) goto exit;
1654
142
          literal_length -= avail;
1655
142
          reader_->Skip(peeked_);
1656
142
          size_t n;
1657
142
          ip = reader_->Peek(&n);
1658
142
          avail = n;
1659
142
          peeked_ = avail;
1660
142
          if (avail == 0) goto exit;
1661
0
          ip_limit_ = ip + avail;
1662
0
          ResetLimit(ip);
1663
0
        }
1664
159k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
159k
        ip += literal_length;
1666
159k
        MAYBE_REFILL();
1667
150k
      } else {
1668
96.9k
        if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
1.46k
          const size_t copy_offset = LittleEndian::Load32(ip);
1670
1.46k
          const size_t length = (c >> 2) + 1;
1671
1.46k
          ip += 4;
1672
1673
1.46k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
95.4k
        } else {
1675
95.4k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
95.4k
          preload = LittleEndian::Load32(ip);
1677
95.4k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
95.4k
          const uint32_t length = entry & 0xff;
1679
95.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
95.4k
          const uint32_t copy_offset = trailer - entry + length;
1685
95.4k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
1687
95.0k
          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
95.0k
          preload >>= (c & 3) * 8;
1691
95.0k
          if (ip < ip_limit_min_maxtaglen_) continue;
1692
95.0k
        }
1693
7.70k
        MAYBE_REFILL();
1694
7.70k
      }
1695
269k
    }
1696
0
#undef MAYBE_REFILL
1697
12.3k
  exit:
1698
12.3k
    writer->SetOutputPtr(op);
1699
12.3k
  }
Unexecuted instantiation: void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyIOVecWriter>(snappy::SnappyIOVecWriter*)
void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyDecompressionValidator>(snappy::SnappyDecompressionValidator*)
Line
Count
Source
1581
5.56k
  DecompressAllTags(Writer* writer) {
1582
5.56k
    const char* ip = ip_;
1583
5.56k
    ResetLimit(ip);
1584
5.56k
    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
5.56k
#define MAYBE_REFILL()                                      \
1590
5.56k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
5.56k
    ip_ = ip;                                               \
1592
5.56k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
5.56k
    ip = ip_;                                               \
1594
5.56k
    ResetLimit(ip);                                         \
1595
5.56k
  }                                                         \
1596
5.56k
  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
5.56k
    uint32_t preload;
1601
5.56k
    MAYBE_REFILL();
1602
131k
    for (;;) {
1603
131k
      {
1604
131k
        ptrdiff_t op_limit_min_slop;
1605
131k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
131k
        if (op_base) {
1607
131k
          auto res =
1608
131k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
131k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
131k
                                   op - op_base, op_base, op_limit_min_slop);
1611
131k
          ip = reinterpret_cast<const char*>(res.first);
1612
131k
          op = op_base + res.second;
1613
131k
          MAYBE_REFILL();
1614
131k
        }
1615
131k
      }
1616
131k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
131k
      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
131k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
83.4k
        size_t literal_length = (c >> 2) + 1u;
1633
83.4k
        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
83.4k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
66.0k
          const size_t literal_length_length = literal_length - 60;
1645
66.0k
          literal_length =
1646
66.0k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
66.0k
              1;
1648
66.0k
          ip += literal_length_length;
1649
66.0k
        }
1650
1651
83.4k
        size_t avail = ip_limit_ - ip;
1652
83.4k
        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
83.4k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
83.4k
        ip += literal_length;
1666
83.4k
        MAYBE_REFILL();
1667
78.6k
      } else {
1668
47.8k
        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.8k
        } else {
1675
47.8k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
47.8k
          preload = LittleEndian::Load32(ip);
1677
47.8k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
47.8k
          const uint32_t length = entry & 0xff;
1679
47.8k
          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.8k
          const uint32_t copy_offset = trailer - entry + length;
1685
47.8k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1686
1687
47.8k
          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.8k
          preload >>= (c & 3) * 8;
1691
47.8k
          if (ip < ip_limit_min_maxtaglen_) continue;
1692
47.8k
        }
1693
2.38k
        MAYBE_REFILL();
1694
2.38k
      }
1695
131k
    }
1696
0
#undef MAYBE_REFILL
1697
5.56k
  exit:
1698
5.56k
    writer->SetOutputPtr(op);
1699
5.56k
  }
void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyArrayWriter>(snappy::SnappyArrayWriter*)
Line
Count
Source
1581
6.74k
  DecompressAllTags(Writer* writer) {
1582
6.74k
    const char* ip = ip_;
1583
6.74k
    ResetLimit(ip);
1584
6.74k
    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
6.74k
#define MAYBE_REFILL()                                      \
1590
6.74k
  if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
1591
6.74k
    ip_ = ip;                                               \
1592
6.74k
    if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit;       \
1593
6.74k
    ip = ip_;                                               \
1594
6.74k
    ResetLimit(ip);                                         \
1595
6.74k
  }                                                         \
1596
6.74k
  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
6.74k
    uint32_t preload;
1601
6.74k
    MAYBE_REFILL();
1602
137k
    for (;;) {
1603
137k
      {
1604
137k
        ptrdiff_t op_limit_min_slop;
1605
137k
        auto op_base = writer->GetBase(&op_limit_min_slop);
1606
137k
        if (op_base) {
1607
137k
          auto res =
1608
137k
              DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
1609
137k
                                   reinterpret_cast<const uint8_t*>(ip_limit_),
1610
137k
                                   op - op_base, op_base, op_limit_min_slop);
1611
137k
          ip = reinterpret_cast<const char*>(res.first);
1612
137k
          op = op_base + res.second;
1613
137k
          MAYBE_REFILL();
1614
137k
        }
1615
137k
      }
1616
137k
      const uint8_t c = static_cast<uint8_t>(preload);
1617
137k
      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
137k
      if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
1632
88.8k
        size_t literal_length = (c >> 2) + 1u;
1633
88.8k
        if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
1634
12.1k
          assert(literal_length < 61);
1635
12.1k
          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
12.1k
          preload = static_cast<uint8_t>(*ip);
1640
12.1k
          continue;
1641
12.1k
        }
1642
76.6k
        if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
1643
          // Long literal.
1644
67.9k
          const size_t literal_length_length = literal_length - 60;
1645
67.9k
          literal_length =
1646
67.9k
              ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
1647
67.9k
              1;
1648
67.9k
          ip += literal_length_length;
1649
67.9k
        }
1650
1651
76.6k
        size_t avail = ip_limit_ - ip;
1652
76.6k
        while (avail < literal_length) {
1653
155
          if (!writer->Append(ip, avail, &op)) goto exit;
1654
142
          literal_length -= avail;
1655
142
          reader_->Skip(peeked_);
1656
142
          size_t n;
1657
142
          ip = reader_->Peek(&n);
1658
142
          avail = n;
1659
142
          peeked_ = avail;
1660
142
          if (avail == 0) goto exit;
1661
0
          ip_limit_ = ip + avail;
1662
0
          ResetLimit(ip);
1663
0
        }
1664
76.5k
        if (!writer->Append(ip, literal_length, &op)) goto exit;
1665
76.4k
        ip += literal_length;
1666
76.4k
        MAYBE_REFILL();
1667
71.6k
      } else {
1668
49.1k
        if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
1669
1.46k
          const size_t copy_offset = LittleEndian::Load32(ip);
1670
1.46k
          const size_t length = (c >> 2) + 1;
1671
1.46k
          ip += 4;
1672
1673
1.46k
          if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
1674
47.6k
        } else {
1675
47.6k
          const ptrdiff_t entry = kLengthMinusOffset[c];
1676
47.6k
          preload = LittleEndian::Load32(ip);
1677
47.6k
          const uint32_t trailer = ExtractLowBytes(preload, c & 3);
1678
47.6k
          const uint32_t length = entry & 0xff;
1679
47.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
47.6k
          const uint32_t copy_offset = trailer - entry + length;
1685
47.6k
          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
5.31k
        MAYBE_REFILL();
1694
5.31k
      }
1695
137k
    }
1696
0
#undef MAYBE_REFILL
1697
6.74k
  exit:
1698
6.74k
    writer->SetOutputPtr(op);
1699
6.74k
  }
Unexecuted instantiation: void snappy::SnappyDecompressor::DecompressAllTags<snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator> >(snappy::SnappyScatteredWriter<snappy::SnappySinkAllocator>*)
1700
};
1701
1702
17.2k
constexpr uint32_t CalculateNeeded(uint8_t tag) {
1703
17.2k
  return ((tag & 3) == 0 && tag >= (60 * 4))
1704
17.2k
             ? (tag >> 2) - 58
1705
17.2k
             : (0x05030201 >> ((tag * 8) & 31)) & 0xFF;
1706
17.2k
}
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
28.7k
bool SnappyDecompressor::RefillTag() {
1723
28.7k
  const char* ip = ip_;
1724
28.7k
  if (ip == ip_limit_) {
1725
    // Fetch a new fragment from the reader
1726
23.7k
    reader_->Skip(peeked_);  // All peeked bytes are used up
1727
23.7k
    size_t n;
1728
23.7k
    ip = reader_->Peek(&n);
1729
23.7k
    peeked_ = n;
1730
23.7k
    eof_ = (n == 0);
1731
23.7k
    if (eof_) return false;
1732
12.2k
    ip_limit_ = ip + n;
1733
12.2k
  }
1734
1735
  // Read the tag character
1736
28.7k
  assert(ip < ip_limit_);
1737
17.2k
  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
17.2k
  const uint32_t needed = CalculateNeeded(c);
1745
17.2k
  assert(needed <= sizeof(scratch_));
1746
1747
  // Read more bytes from reader if needed
1748
17.2k
  uint64_t nbuf = ip_limit_ - ip;
1749
17.2k
  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
35
    std::memmove(scratch_, ip, nbuf);
1755
35
    reader_->Skip(peeked_);  // All peeked bytes are used up
1756
35
    peeked_ = 0;
1757
35
    while (nbuf < needed) {
1758
35
      size_t length;
1759
35
      const char* src = reader_->Peek(&length);
1760
35
      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
35
    assert(nbuf == needed);
1767
0
    ip_ = scratch_;
1768
0
    ip_limit_ = scratch_ + needed;
1769
17.2k
  } else if (nbuf < kMaximumTagLength) {
1770
    // Have enough bytes, but move into scratch_ so that we do not
1771
    // read past end of input
1772
5.15k
    std::memmove(scratch_, ip, nbuf);
1773
5.15k
    reader_->Skip(peeked_);  // All peeked bytes are used up
1774
5.15k
    peeked_ = 0;
1775
5.15k
    ip_ = scratch_;
1776
5.15k
    ip_limit_ = scratch_ + nbuf;
1777
12.0k
  } else {
1778
    // Pass pointer to buffer returned by reader_.
1779
12.0k
    ip_ = ip;
1780
12.0k
  }
1781
17.2k
  return true;
1782
17.2k
}
1783
1784
template <typename Writer>
1785
12.3k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
12.3k
  SnappyDecompressor decompressor(r);
1788
12.3k
  uint32_t uncompressed_len = 0;
1789
12.3k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
12.3k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
12.3k
                                   uncompressed_len);
1793
12.3k
}
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
6.74k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
6.74k
  SnappyDecompressor decompressor(r);
1788
6.74k
  uint32_t uncompressed_len = 0;
1789
6.74k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
6.74k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
6.74k
                                   uncompressed_len);
1793
6.74k
}
snappy.cc:bool snappy::InternalUncompress<snappy::SnappyDecompressionValidator>(snappy::Source*, snappy::SnappyDecompressionValidator*)
Line
Count
Source
1785
5.56k
static bool InternalUncompress(Source* r, Writer* writer) {
1786
  // Read the uncompressed length from the front of the compressed input
1787
5.56k
  SnappyDecompressor decompressor(r);
1788
5.56k
  uint32_t uncompressed_len = 0;
1789
5.56k
  if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
1790
1791
5.56k
  return InternalUncompressAllTags(&decompressor, writer, r->Available(),
1792
5.56k
                                   uncompressed_len);
1793
5.56k
}
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
12.3k
                                      uint32_t uncompressed_len) {
1799
12.3k
    int token = 0;
1800
12.3k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
12.3k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
12.3k
  decompressor->DecompressAllTags(writer);
1806
12.3k
  writer->Flush();
1807
12.3k
  return (decompressor->eof() && writer->CheckLength());
1808
12.3k
}
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
5.56k
                                      uint32_t uncompressed_len) {
1799
5.56k
    int token = 0;
1800
5.56k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
5.56k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
5.56k
  decompressor->DecompressAllTags(writer);
1806
5.56k
  writer->Flush();
1807
5.56k
  return (decompressor->eof() && writer->CheckLength());
1808
5.56k
}
snappy.cc:bool snappy::InternalUncompressAllTags<snappy::SnappyArrayWriter>(snappy::SnappyDecompressor*, snappy::SnappyArrayWriter*, unsigned int, unsigned int)
Line
Count
Source
1798
6.74k
                                      uint32_t uncompressed_len) {
1799
6.74k
    int token = 0;
1800
6.74k
  Report(token, "snappy_uncompress", compressed_len, uncompressed_len);
1801
1802
6.74k
  writer->SetExpectedLength(uncompressed_len);
1803
1804
  // Process the entire input
1805
6.74k
  decompressor->DecompressAllTags(writer);
1806
6.74k
  writer->Flush();
1807
6.74k
  return (decompressor->eof() && writer->CheckLength());
1808
6.74k
}
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
5.56k
size_t Compress(Source* reader, Sink* writer, CompressionOptions options) {
1820
5.56k
  assert(options.level == 1 || options.level == 2);
1821
5.56k
  int token = 0;
1822
5.56k
  size_t written = 0;
1823
5.56k
  size_t N = reader->Available();
1824
5.56k
  assert(N <= 0xFFFFFFFFu);
1825
5.56k
  const size_t uncompressed_size = N;
1826
5.56k
  char ulength[Varint::kMax32];
1827
5.56k
  char* p = Varint::Encode32(ulength, N);
1828
5.56k
  writer->Append(ulength, p - ulength);
1829
5.56k
  written += (p - ulength);
1830
1831
5.56k
  internal::WorkingMemory wmem(N);
1832
1833
15.7k
  while (N > 0) {
1834
    // Get next block to compress (without copying if possible)
1835
10.1k
    size_t fragment_size;
1836
10.1k
    const char* fragment = reader->Peek(&fragment_size);
1837
10.1k
    assert(fragment_size != 0);  // premature end of input
1838
10.1k
    const size_t num_to_read = std::min(N, kBlockSize);
1839
10.1k
    size_t bytes_read = fragment_size;
1840
1841
10.1k
    size_t pending_advance = 0;
1842
10.1k
    if (bytes_read >= num_to_read) {
1843
      // Buffer returned by reader is large enough
1844
10.1k
      pending_advance = num_to_read;
1845
10.1k
      fragment_size = num_to_read;
1846
10.1k
    } 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
10.1k
    assert(fragment_size == num_to_read);
1863
1864
    // Get encoding table for compression
1865
10.1k
    int table_size;
1866
10.1k
    uint16_t* table = wmem.GetHashTable(num_to_read, &table_size);
1867
1868
    // Compress input_fragment and append to dest
1869
10.1k
    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
10.1k
    char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput());
1877
10.1k
    char* end = nullptr;
1878
10.1k
    if (options.level == 1) {
1879
5.09k
      end = internal::CompressFragment(fragment, fragment_size, dest, table,
1880
5.09k
                                       table_size);
1881
5.09k
    } else if (options.level == 2) {
1882
5.09k
      end = internal::CompressFragmentDoubleHash(
1883
5.09k
          fragment, fragment_size, dest, table, table_size >> 1,
1884
5.09k
          table + (table_size >> 1), table_size >> 1);
1885
5.09k
    }
1886
10.1k
    writer->Append(dest, end - dest);
1887
10.1k
    written += (end - dest);
1888
1889
10.1k
    N -= num_to_read;
1890
10.1k
    reader->Skip(pending_advance);
1891
10.1k
  }
1892
1893
5.56k
  Report(token, "snappy_compress", written, uncompressed_size);
1894
5.56k
  return written;
1895
5.56k
}
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
6.74k
      : base_(dst),
2175
6.74k
        op_(dst),
2176
6.74k
        op_limit_(dst),
2177
6.74k
        op_limit_min_slop_(dst) {}  // Safe default see invariant.
2178
2179
6.74k
  inline void SetExpectedLength(size_t len) {
2180
6.74k
    op_limit_ = op_ + len;
2181
    // Prevent pointer from being past the buffer.
2182
6.74k
    op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, len);
2183
6.74k
  }
2184
2185
5.90k
  inline bool CheckLength() const { return op_ == op_limit_; }
2186
2187
6.74k
  char* GetOutputPtr() { return op_; }
2188
137k
  char* GetBase(ptrdiff_t* op_limit_min_slop) {
2189
137k
    *op_limit_min_slop = op_limit_min_slop_ - base_;
2190
137k
    return base_;
2191
137k
  }
2192
6.74k
  void SetOutputPtr(char* op) { op_ = op; }
2193
2194
76.6k
  inline bool Append(const char* ip, size_t len, char** op_p) {
2195
76.6k
    char* op = *op_p;
2196
76.6k
    const size_t space_left = op_limit_ - op;
2197
76.6k
    if (space_left < len) return false;
2198
76.6k
    std::memcpy(op, ip, len);
2199
76.6k
    *op_p = op + len;
2200
76.6k
    return true;
2201
76.6k
  }
2202
2203
  inline bool TryFastAppend(const char* ip, size_t available, size_t len,
2204
88.8k
                            char** op_p) {
2205
88.8k
    char* op = *op_p;
2206
88.8k
    const size_t space_left = op_limit_ - op;
2207
88.8k
    if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
2208
      // Fast path, used for the majority (about 95%) of invocations.
2209
12.1k
      UnalignedCopy128(ip, op);
2210
12.1k
      *op_p = op + len;
2211
12.1k
      return true;
2212
76.6k
    } else {
2213
76.6k
      return false;
2214
76.6k
    }
2215
88.8k
  }
2216
2217
  SNAPPY_ATTRIBUTE_ALWAYS_INLINE
2218
49.1k
  inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
2219
49.1k
    assert(len > 0);
2220
49.1k
    char* const op = *op_p;
2221
49.1k
    assert(op >= base_);
2222
49.1k
    char* const op_end = op + len;
2223
2224
    // Check if we try to append from before the start of the buffer.
2225
49.1k
    if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - base_) < offset))
2226
448
      return false;
2227
2228
48.6k
    if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
2229
48.6k
                            op >= op_limit_min_slop_ || offset < len)) {
2230
27.1k
      if (op_end > op_limit_ || offset == 0) return false;
2231
26.9k
      *op_p = IncrementalCopy(op - offset, op, op_end, op_limit_);
2232
26.9k
      return true;
2233
27.1k
    }
2234
21.5k
    std::memmove(op, op - offset, kSlopBytes);
2235
21.5k
    *op_p = op_end;
2236
21.5k
    return true;
2237
48.6k
  }
2238
0
  inline size_t Produced() const {
2239
0
    assert(op_ >= base_);
2240
0
    return op_ - base_;
2241
0
  }
2242
6.74k
  inline void Flush() {}
2243
};
2244
2245
bool RawUncompress(const char* compressed, size_t compressed_length,
2246
6.74k
                   char* uncompressed) {
2247
6.74k
  ByteArraySource reader(compressed, compressed_length);
2248
6.74k
  return RawUncompress(&reader, uncompressed);
2249
6.74k
}
2250
2251
6.74k
bool RawUncompress(Source* compressed, char* uncompressed) {
2252
6.74k
  SnappyArrayWriter output(uncompressed);
2253
6.74k
  return InternalUncompress(compressed, &output);
2254
6.74k
}
2255
2256
bool Uncompress(const char* compressed, size_t compressed_length,
2257
6.74k
                std::string* uncompressed) {
2258
6.74k
  size_t ulength;
2259
6.74k
  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
6.74k
  if (ulength > uncompressed->max_size()) {
2265
0
    return false;
2266
0
  }
2267
6.74k
  STLStringResizeUninitialized(uncompressed, ulength);
2268
6.74k
  return RawUncompress(compressed, compressed_length,
2269
6.74k
                       string_as_array(uncompressed));
2270
6.74k
}
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
5.56k
  inline SnappyDecompressionValidator() : expected_(0), produced_(0) {}
2280
5.56k
  inline void SetExpectedLength(size_t len) { expected_ = len; }
2281
5.56k
  size_t GetOutputPtr() { return produced_; }
2282
131k
  size_t GetBase(ptrdiff_t* op_limit_min_slop) {
2283
131k
    *op_limit_min_slop = std::numeric_limits<ptrdiff_t>::max() - kSlopBytes + 1;
2284
131k
    return 1;
2285
131k
  }
2286
5.56k
  void SetOutputPtr(size_t op) { produced_ = op; }
2287
5.56k
  inline bool CheckLength() const { return expected_ == produced_; }
2288
83.4k
  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
83.4k
    (void)ip;
2291
2292
83.4k
    *produced += len;
2293
83.4k
    return *produced <= expected_;
2294
83.4k
  }
2295
  inline bool TryFastAppend(const char* ip, size_t available, size_t length,
2296
83.4k
                            size_t* produced) {
2297
    // TODO: Switch to [[maybe_unused]] when we can assume C++17.
2298
83.4k
    (void)ip;
2299
83.4k
    (void)available;
2300
83.4k
    (void)length;
2301
83.4k
    (void)produced;
2302
2303
83.4k
    return false;
2304
83.4k
  }
2305
47.8k
  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.8k
    if (*produced <= offset - 1u) return false;
2309
47.8k
    *produced += len;
2310
47.8k
    return *produced <= expected_;
2311
47.8k
  }
2312
5.56k
  inline void Flush() {}
2313
};
2314
2315
5.56k
bool IsValidCompressedBuffer(const char* compressed, size_t compressed_length) {
2316
5.56k
  ByteArraySource reader(compressed, compressed_length);
2317
5.56k
  SnappyDecompressionValidator writer;
2318
5.56k
  return InternalUncompress(&reader, &writer);
2319
5.56k
}
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
5.56k
                 size_t* compressed_length, CompressionOptions options) {
2334
5.56k
  ByteArraySource reader(input, input_length);
2335
5.56k
  UncheckedByteArraySink writer(compressed);
2336
5.56k
  Compress(&reader, &writer, options);
2337
2338
  // Compute how many bytes were added
2339
5.56k
  *compressed_length = (writer.CurrentDestination() - compressed);
2340
5.56k
}
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
5.56k
                CompressionOptions options) {
2366
  // Pre-grow the buffer to the max length of the compressed output
2367
5.56k
  STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
2368
2369
5.56k
  size_t compressed_length;
2370
5.56k
  RawCompress(input, input_length, string_as_array(compressed),
2371
5.56k
              &compressed_length, options);
2372
5.56k
  compressed->erase(compressed_length);
2373
5.56k
  return compressed_length;
2374
5.56k
}
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