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