Coverage Report

Created: 2026-12-04 06:19

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