| 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.h" |
| 30 | #include "snappy-internal.h" |
| 31 | #include "snappy-sinksource.h" |
| 32 | |
| 33 | #if !defined(SNAPPY_HAVE_SSSE3) |
| 34 | // __SSSE3__ is defined by GCC and Clang. Visual Studio doesn't target SIMD |
| 35 | // support between SSE2 and AVX (so SSSE3 instructions require AVX support), and |
| 36 | // defines __AVX__ when AVX support is available. |
| 37 | #if defined(__SSSE3__) || defined(__AVX__) |
| 38 | #define SNAPPY_HAVE_SSSE3 1 |
| 39 | #else |
| 40 | #define SNAPPY_HAVE_SSSE3 0 |
| 41 | #endif |
| 42 | #endif // !defined(SNAPPY_HAVE_SSSE3) |
| 43 | |
| 44 | #if !defined(SNAPPY_HAVE_BMI2) |
| 45 | // __BMI2__ is defined by GCC and Clang. Visual Studio doesn't target BMI2 |
| 46 | // specifically, but it does define __AVX2__ when AVX2 support is available. |
| 47 | // Fortunately, AVX2 was introduced in Haswell, just like BMI2. |
| 48 | // |
| 49 | // BMI2 is not defined as a subset of AVX2 (unlike SSSE3 and AVX above). So, |
| 50 | // GCC and Clang can build code with AVX2 enabled but BMI2 disabled, in which |
| 51 | // case issuing BMI2 instructions results in a compiler error. |
| 52 | #if defined(__BMI2__) || (defined(_MSC_VER) && defined(__AVX2__)) |
| 53 | #define SNAPPY_HAVE_BMI2 1 |
| 54 | #else |
| 55 | #define SNAPPY_HAVE_BMI2 0 |
| 56 | #endif |
| 57 | #endif // !defined(SNAPPY_HAVE_BMI2) |
| 58 | |
| 59 | #if SNAPPY_HAVE_SSSE3 |
| 60 | // Please do not replace with <x86intrin.h>. or with headers that assume more |
| 61 | // advanced SSE versions without checking with all the OWNERS. |
| 62 | #include <tmmintrin.h> |
| 63 | #endif |
| 64 | |
| 65 | #if SNAPPY_HAVE_BMI2 |
| 66 | // Please do not replace with <x86intrin.h>. or with headers that assume more |
| 67 | // advanced SSE versions without checking with all the OWNERS. |
| 68 | #include <immintrin.h> |
| 69 | #endif |
| 70 | |
| 71 | #include <stdio.h> |
| 72 | |
| 73 | #include <algorithm> |
| 74 | #include <string> |
| 75 | #include <vector> |
| 76 | |
| 77 | |
| 78 | namespace snappy { |
| 79 | |
| 80 | using internal::COPY_1_BYTE_OFFSET; |
| 81 | using internal::COPY_2_BYTE_OFFSET; |
| 82 | using internal::LITERAL; |
| 83 | using internal::char_table; |
| 84 | using internal::kMaximumTagLength; |
| 85 | |
| 86 | // Any hash function will produce a valid compressed bitstream, but a good |
| 87 | // hash function reduces the number of collisions and thus yields better |
| 88 | // compression for compressible input, and more speed for incompressible |
| 89 | // input. Of course, it doesn't hurt if the hash function is reasonably fast |
| 90 | // either, as it gets called a lot. |
| 91 | static inline uint32 HashBytes(uint32 bytes, int shift) { |
| 92 | uint32 kMul = 0x1e35a7bd; |
| 93 | return (bytes * kMul) >> shift; |
| 94 | } |
| 95 | static inline uint32 Hash(const char* p, int shift) { |
| 96 | return HashBytes(UNALIGNED_LOAD32(p), shift); |
| 97 | } |
| 98 | |
| 99 | size_t MaxCompressedLength(size_t source_len) { |
| 100 | // Compressed data can be defined as: |
| 101 | // compressed := item* literal* |
| 102 | // item := literal* copy |
| 103 | // |
| 104 | // The trailing literal sequence has a space blowup of at most 62/60 |
| 105 | // since a literal of length 60 needs one tag byte + one extra byte |
| 106 | // for length information. |
| 107 | // |
| 108 | // Item blowup is trickier to measure. Suppose the "copy" op copies |
| 109 | // 4 bytes of data. Because of a special check in the encoding code, |
| 110 | // we produce a 4-byte copy only if the offset is < 65536. Therefore |
| 111 | // the copy op takes 3 bytes to encode, and this type of item leads |
| 112 | // to at most the 62/60 blowup for representing literals. |
| 113 | // |
| 114 | // Suppose the "copy" op copies 5 bytes of data. If the offset is big |
| 115 | // enough, it will take 5 bytes to encode the copy op. Therefore the |
| 116 | // worst case here is a one-byte literal followed by a five-byte copy. |
| 117 | // I.e., 6 bytes of input turn into 7 bytes of "compressed" data. |
| 118 | // |
| 119 | // This last factor dominates the blowup, so the final estimate is: |
| 120 | return 32 + source_len + source_len/6; |
| 121 | } |
| 122 | |
| 123 | namespace { |
| 124 | |
| 125 | void UnalignedCopy64(const void* src, void* dst) { |
| 126 | char tmp[8]; |
| 127 | memcpy(tmp, src, 8); |
| 128 | memcpy(dst, tmp, 8); |
| 129 | } |
| 130 | |
| 131 | void UnalignedCopy128(const void* src, void* dst) { |
| 132 | // memcpy gets vectorized when the appropriate compiler options are used. |
| 133 | // For example, x86 compilers targeting SSE2+ will optimize to an SSE2 load |
| 134 | // and store. |
| 135 | char tmp[16]; |
| 136 | memcpy(tmp, src, 16); |
| 137 | memcpy(dst, tmp, 16); |
| 138 | } |
| 139 | |
| 140 | // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used |
| 141 | // for handling COPY operations where the input and output regions may overlap. |
| 142 | // For example, suppose: |
| 143 | // src == "ab" |
| 144 | // op == src + 2 |
| 145 | // op_limit == op + 20 |
| 146 | // After IncrementalCopySlow(src, op, op_limit), the result will have eleven |
| 147 | // copies of "ab" |
| 148 | // ababababababababababab |
| 149 | // Note that this does not match the semantics of either memcpy() or memmove(). |
| 150 | inline char* IncrementalCopySlow(const char* src, char* op, |
| 151 | char* const op_limit) { |
| 152 | // TODO: Remove pragma when LLVM is aware this function is only called in |
| 153 | // cold regions and when cold regions don't get vectorized or unrolled. |
| 154 | #ifdef __clang__ |
| 155 | #pragma clang loop unroll(disable) |
| 156 | #endif |
| 157 | while (op < op_limit) { |
| 158 | *op++ = *src++; |
| 159 | } |
| 160 | return op_limit; |
| 161 | } |
| 162 | |
| 163 | #if SNAPPY_HAVE_SSSE3 |
| 164 | |
| 165 | // This is a table of shuffle control masks that can be used as the source |
| 166 | // operand for PSHUFB to permute the contents of the destination XMM register |
| 167 | // into a repeating byte pattern. |
| 168 | alignas(16) const char pshufb_fill_patterns[7][16] = { |
| 169 | {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, |
| 170 | {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}, |
| 171 | {0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0}, |
| 172 | {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3}, |
| 173 | {0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0}, |
| 174 | {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3}, |
| 175 | {0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1}, |
| 176 | }; |
| 177 | |
| 178 | #endif // SNAPPY_HAVE_SSSE3 |
| 179 | |
| 180 | // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) but faster than |
| 181 | // IncrementalCopySlow. buf_limit is the address past the end of the writable |
| 182 | // region of the buffer. |
| 183 | inline char* IncrementalCopy(const char* src, char* op, char* const op_limit, |
| 184 | char* const buf_limit) { |
| 185 | // Terminology: |
| 186 | // |
| 187 | // slop = buf_limit - op |
| 188 | // pat = op - src |
| 189 | // len = limit - op |
| 190 | assert(src < op); |
| 191 | assert(op <= op_limit); |
| 192 | assert(op_limit <= buf_limit); |
| 193 | // NOTE: The compressor always emits 4 <= len <= 64. It is ok to assume that |
| 194 | // to optimize this function but we have to also handle other cases in case |
| 195 | // the input does not satisfy these conditions. |
| 196 | |
| 197 | size_t pattern_size = op - src; |
| 198 | // The cases are split into different branches to allow the branch predictor, |
| 199 | // FDO, and static prediction hints to work better. For each input we list the |
| 200 | // ratio of invocations that match each condition. |
| 201 | // |
| 202 | // input slop < 16 pat < 8 len > 16 |
| 203 | // ------------------------------------------ |
| 204 | // html|html4|cp 0% 1.01% 27.73% |
| 205 | // urls 0% 0.88% 14.79% |
| 206 | // jpg 0% 64.29% 7.14% |
| 207 | // pdf 0% 2.56% 58.06% |
| 208 | // txt[1-4] 0% 0.23% 0.97% |
| 209 | // pb 0% 0.96% 13.88% |
| 210 | // bin 0.01% 22.27% 41.17% |
| 211 | // |
| 212 | // It is very rare that we don't have enough slop for doing block copies. It |
| 213 | // is also rare that we need to expand a pattern. Small patterns are common |
| 214 | // for incompressible formats and for those we are plenty fast already. |
| 215 | // Lengths are normally not greater than 16 but they vary depending on the |
| 216 | // input. In general if we always predict len <= 16 it would be an ok |
| 217 | // prediction. |
| 218 | // |
| 219 | // In order to be fast we want a pattern >= 8 bytes and an unrolled loop |
| 220 | // copying 2x 8 bytes at a time. |
| 221 | |
| 222 | // Handle the uncommon case where pattern is less than 8 bytes. |
| 223 | if (SNAPPY_PREDICT_FALSE(pattern_size < 8)) { |
| 224 | #if SNAPPY_HAVE_SSSE3 |
| 225 | // Load the first eight bytes into an 128-bit XMM register, then use PSHUFB |
| 226 | // to permute the register's contents in-place into a repeating sequence of |
| 227 | // the first "pattern_size" bytes. |
| 228 | // For example, suppose: |
| 229 | // src == "abc" |
| 230 | // op == op + 3 |
| 231 | // After _mm_shuffle_epi8(), "pattern" will have five copies of "abc" |
| 232 | // followed by one byte of slop: abcabcabcabcabca. |
| 233 | // |
| 234 | // The non-SSE fallback implementation suffers from store-forwarding stalls |
| 235 | // because its loads and stores partly overlap. By expanding the pattern |
| 236 | // in-place, we avoid the penalty. |
| 237 | if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 16)) { |
| 238 | const __m128i shuffle_mask = _mm_load_si128( |
| 239 | reinterpret_cast<const __m128i*>(pshufb_fill_patterns) |
| 240 | + pattern_size - 1); |
| 241 | const __m128i pattern = _mm_shuffle_epi8( |
| 242 | _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src)), shuffle_mask); |
| 243 | // Uninitialized bytes are masked out by the shuffle mask. |
| 244 | SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(&pattern, sizeof(pattern)); |
| 245 | pattern_size *= 16 / pattern_size; |
| 246 | char* op_end = std::min(op_limit, buf_limit - 15); |
| 247 | while (op < op_end) { |
| 248 | _mm_storeu_si128(reinterpret_cast<__m128i*>(op), pattern); |
| 249 | op += pattern_size; |
| 250 | } |
| 251 | if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit; |
| 252 | } |
| 253 | return IncrementalCopySlow(src, op, op_limit); |
| 254 | #else // !SNAPPY_HAVE_SSSE3 |
| 255 | // If plenty of buffer space remains, expand the pattern to at least 8 |
| 256 | // bytes. The way the following loop is written, we need 8 bytes of buffer |
| 257 | // space if pattern_size >= 4, 11 bytes if pattern_size is 1 or 3, and 10 |
| 258 | // bytes if pattern_size is 2. Precisely encoding that is probably not |
| 259 | // worthwhile; instead, invoke the slow path if we cannot write 11 bytes |
| 260 | // (because 11 are required in the worst case). |
| 261 | if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) { |
| 262 | while (pattern_size < 8) { |
| 263 | UnalignedCopy64(src, op); |
| 264 | op += pattern_size; |
| 265 | pattern_size *= 2; |
| 266 | } |
| 267 | if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit; |
| 268 | } else { |
| 269 | return IncrementalCopySlow(src, op, op_limit); |
| 270 | } |
| 271 | #endif // SNAPPY_HAVE_SSSE3 |
| 272 | } |
| 273 | assert(pattern_size >= 8); |
| 274 | |
| 275 | // Copy 2x 8 bytes at a time. Because op - src can be < 16, a single |
| 276 | // UnalignedCopy128 might overwrite data in op. UnalignedCopy64 is safe |
| 277 | // because expanding the pattern to at least 8 bytes guarantees that |
| 278 | // op - src >= 8. |
| 279 | // |
| 280 | // Typically, the op_limit is the gating factor so try to simplify the loop |
| 281 | // based on that. |
| 282 | if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 16)) { |
| 283 | // Factor the displacement from op to the source into a variable. This helps |
| 284 | // simplify the loop below by only varying the op pointer which we need to |
| 285 | // test for the end. Note that this was done after carefully examining the |
| 286 | // generated code to allow the addressing modes in the loop below to |
| 287 | // maximize micro-op fusion where possible on modern Intel processors. The |
| 288 | // generated code should be checked carefully for new processors or with |
| 289 | // major changes to the compiler. |
| 290 | // TODO: Simplify this code when the compiler reliably produces the correct |
| 291 | // x86 instruction sequence. |
| 292 | ptrdiff_t op_to_src = src - op; |
| 293 | |
| 294 | // The trip count of this loop is not large and so unrolling will only hurt |
| 295 | // code size without helping performance. |
| 296 | // |
| 297 | // TODO: Replace with loop trip count hint. |
| 298 | #ifdef __clang__ |
| 299 | #pragma clang loop unroll(disable) |
| 300 | #endif |
| 301 | do { |
| 302 | UnalignedCopy64(op + op_to_src, op); |
| 303 | UnalignedCopy64(op + op_to_src + 8, op + 8); |
| 304 | op += 16; |
| 305 | } while (op < op_limit); |
| 306 | return op_limit; |
| 307 | } |
| 308 | |
| 309 | // Fall back to doing as much as we can with the available slop in the |
| 310 | // buffer. This code path is relatively cold however so we save code size by |
| 311 | // avoiding unrolling and vectorizing. |
| 312 | // |
| 313 | // TODO: Remove pragma when when cold regions don't get vectorized or |
| 314 | // unrolled. |
| 315 | #ifdef __clang__ |
| 316 | #pragma clang loop unroll(disable) |
| 317 | #endif |
| 318 | for (char *op_end = buf_limit - 16; op < op_end; op += 16, src += 16) { |
| 319 | UnalignedCopy64(src, op); |
| 320 | UnalignedCopy64(src + 8, op + 8); |
| 321 | } |
| 322 | if (op >= op_limit) |
| 323 | return op_limit; |
| 324 | |
| 325 | // We only take this branch if we didn't have enough slop and we can do a |
| 326 | // single 8 byte copy. |
| 327 | if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) { |
| 328 | UnalignedCopy64(src, op); |
| 329 | src += 8; |
| 330 | op += 8; |
| 331 | } |
| 332 | return IncrementalCopySlow(src, op, op_limit); |
| 333 | } |
| 334 | |
| 335 | } // namespace |
| 336 | |
| 337 | template <bool allow_fast_path> |
| 338 | static inline char* EmitLiteral(char* op, |
| 339 | const char* literal, |
| 340 | int len) { |
| 341 | // The vast majority of copies are below 16 bytes, for which a |
| 342 | // call to memcpy is overkill. This fast path can sometimes |
| 343 | // copy up to 15 bytes too much, but that is okay in the |
| 344 | // main loop, since we have a bit to go on for both sides: |
| 345 | // |
| 346 | // - The input will always have kInputMarginBytes = 15 extra |
| 347 | // available bytes, as long as we're in the main loop, and |
| 348 | // if not, allow_fast_path = false. |
| 349 | // - The output will always have 32 spare bytes (see |
| 350 | // MaxCompressedLength). |
| 351 | assert(len > 0); // Zero-length literals are disallowed |
| 352 | int n = len - 1; |
| 353 | if (allow_fast_path && len <= 16) { |
| 354 | // Fits in tag byte |
| 355 | *op++ = LITERAL | (n << 2); |
| 356 | |
| 357 | UnalignedCopy128(literal, op); |
| 358 | return op + len; |
| 359 | } |
| 360 | |
| 361 | if (n < 60) { |
| 362 | // Fits in tag byte |
| 363 | *op++ = LITERAL | (n << 2); |
| 364 | } else { |
| 365 | // Encode in upcoming bytes |
| 366 | char* base = op; |
| 367 | int count = 0; |
| 368 | op++; |
| 369 | while (n > 0) { |
| 370 | *op++ = n & 0xff; |
| 371 | n >>= 8; |
| 372 | count++; |
| 373 | } |
| 374 | assert(count >= 1); |
| 375 | assert(count <= 4); |
| 376 | *base = LITERAL | ((59+count) << 2); |
| 377 | } |
| 378 | memcpy(op, literal, len); |
| 379 | return op + len; |
| 380 | } |
| 381 | |
| 382 | template <bool len_less_than_12> |
| 383 | static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) { |
| 384 | assert(len <= 64); |
| 385 | assert(len >= 4); |
| 386 | assert(offset < 65536); |
| 387 | assert(len_less_than_12 == (len < 12)); |
| 388 | |
| 389 | if (len_less_than_12 && SNAPPY_PREDICT_TRUE(offset < 2048)) { |
| 390 | // offset fits in 11 bits. The 3 highest go in the top of the first byte, |
| 391 | // and the rest go in the second byte. |
| 392 | *op++ = COPY_1_BYTE_OFFSET + ((len - 4) << 2) + ((offset >> 3) & 0xe0); |
| 393 | *op++ = offset & 0xff; |
| 394 | } else { |
| 395 | // Write 4 bytes, though we only care about 3 of them. The output buffer |
| 396 | // is required to have some slack, so the extra byte won't overrun it. |
| 397 | uint32 u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8); |
| 398 | LittleEndian::Store32(op, u); |
| 399 | op += 3; |
| 400 | } |
| 401 | return op; |
| 402 | } |
| 403 | |
| 404 | template <bool len_less_than_12> |
| 405 | static inline char* EmitCopy(char* op, size_t offset, size_t len) { |
| 406 | assert(len_less_than_12 == (len < 12)); |
| 407 | if (len_less_than_12) { |
| 408 | return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len); |
| 409 | } else { |
| 410 | // A special case for len <= 64 might help, but so far measurements suggest |
| 411 | // it's in the noise. |
| 412 | |
| 413 | // Emit 64 byte copies but make sure to keep at least four bytes reserved. |
| 414 | while (SNAPPY_PREDICT_FALSE(len >= 68)) { |
| 415 | op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64); |
| 416 | len -= 64; |
| 417 | } |
| 418 | |
| 419 | // One or two copies will now finish the job. |
| 420 | if (len > 64) { |
| 421 | op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60); |
| 422 | len -= 60; |
| 423 | } |
| 424 | |
| 425 | // Emit remainder. |
| 426 | if (len < 12) { |
| 427 | op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len); |
| 428 | } else { |
| 429 | op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len); |
| 430 | } |
| 431 | return op; |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | bool GetUncompressedLength(const char* start, size_t n, size_t* result) { |
| 436 | uint32 v = 0; |
| 437 | const char* limit = start + n; |
| 438 | if (Varint::Parse32WithLimit(start, limit, &v) != NULL) { |
| 439 | *result = v; |
| 440 | return true; |
| 441 | } else { |
| 442 | return false; |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | namespace { |
| 447 | uint32 CalculateTableSize(uint32 input_size) { |
| 448 | assert(kMaxHashTableSize >= 256); |
| 449 | if (input_size > kMaxHashTableSize) { |
| 450 | return kMaxHashTableSize; |
| 451 | } |
| 452 | if (input_size < 256) { |
| 453 | return 256; |
| 454 | } |
| 455 | // This is equivalent to Log2Ceiling(input_size), assuming input_size > 1. |
| 456 | // 2 << Log2Floor(x - 1) is equivalent to 1 << (1 + Log2Floor(x - 1)). |
| 457 | return 2u << Bits::Log2Floor(input_size - 1); |
| 458 | } |
| 459 | } // namespace |
| 460 | |
| 461 | namespace internal { |
| 462 | WorkingMemory::WorkingMemory(size_t input_size) { |
| 463 | const size_t max_fragment_size = std::min(input_size, kBlockSize); |
| 464 | const size_t table_size = CalculateTableSize(max_fragment_size); |
| 465 | size_ = table_size * sizeof(*table_) + max_fragment_size + |
| 466 | MaxCompressedLength(max_fragment_size); |
| 467 | mem_ = std::allocator<char>().allocate(size_); |
| 468 | table_ = reinterpret_cast<uint16*>(mem_); |
| 469 | input_ = mem_ + table_size * sizeof(*table_); |
| 470 | output_ = input_ + max_fragment_size; |
| 471 | } |
| 472 | |
| 473 | WorkingMemory::~WorkingMemory() { |
| 474 | std::allocator<char>().deallocate(mem_, size_); |
| 475 | } |
| 476 | |
| 477 | uint16* WorkingMemory::GetHashTable(size_t fragment_size, |
| 478 | int* table_size) const { |
| 479 | const size_t htsize = CalculateTableSize(fragment_size); |
| 480 | memset(table_, 0, htsize * sizeof(*table_)); |
| 481 | *table_size = htsize; |
| 482 | return table_; |
| 483 | } |
| 484 | } // end namespace internal |
| 485 | |
| 486 | // For 0 <= offset <= 4, GetUint32AtOffset(GetEightBytesAt(p), offset) will |
| 487 | // equal UNALIGNED_LOAD32(p + offset). Motivation: On x86-64 hardware we have |
| 488 | // empirically found that overlapping loads such as |
| 489 | // UNALIGNED_LOAD32(p) ... UNALIGNED_LOAD32(p+1) ... UNALIGNED_LOAD32(p+2) |
| 490 | // are slower than UNALIGNED_LOAD64(p) followed by shifts and casts to uint32. |
| 491 | // |
| 492 | // We have different versions for 64- and 32-bit; ideally we would avoid the |
| 493 | // two functions and just inline the UNALIGNED_LOAD64 call into |
| 494 | // GetUint32AtOffset, but GCC (at least not as of 4.6) is seemingly not clever |
| 495 | // enough to avoid loading the value multiple times then. For 64-bit, the load |
| 496 | // is done when GetEightBytesAt() is called, whereas for 32-bit, the load is |
| 497 | // done at GetUint32AtOffset() time. |
| 498 | |
| 499 | #ifdef ARCH_K8 |
| 500 | |
| 501 | typedef uint64 EightBytesReference; |
| 502 | |
| 503 | static inline EightBytesReference GetEightBytesAt(const char* ptr) { |
| 504 | return UNALIGNED_LOAD64(ptr); |
| 505 | } |
| 506 | |
| 507 | static inline uint32 GetUint32AtOffset(uint64 v, int offset) { |
| 508 | assert(offset >= 0); |
| 509 | assert(offset <= 4); |
| 510 | return v >> (LittleEndian::IsLittleEndian() ? 8 * offset : 32 - 8 * offset); |
| 511 | } |
| 512 | |
| 513 | #else |
| 514 | |
| 515 | typedef const char* EightBytesReference; |
| 516 | |
| 517 | static inline EightBytesReference GetEightBytesAt(const char* ptr) { |
| 518 | return ptr; |
| 519 | } |
| 520 | |
| 521 | static inline uint32 GetUint32AtOffset(const char* v, int offset) { |
| 522 | assert(offset >= 0); |
| 523 | assert(offset <= 4); |
| 524 | return UNALIGNED_LOAD32(v + offset); |
| 525 | } |
| 526 | |
| 527 | #endif |
| 528 | |
| 529 | // Flat array compression that does not emit the "uncompressed length" |
| 530 | // prefix. Compresses "input" string to the "*op" buffer. |
| 531 | // |
| 532 | // REQUIRES: "input" is at most "kBlockSize" bytes long. |
| 533 | // REQUIRES: "op" points to an array of memory that is at least |
| 534 | // "MaxCompressedLength(input.size())" in size. |
| 535 | // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero. |
| 536 | // REQUIRES: "table_size" is a power of two |
| 537 | // |
| 538 | // Returns an "end" pointer into "op" buffer. |
| 539 | // "end - op" is the compressed size of "input". |
| 540 | namespace internal { |
| 541 | char* CompressFragment(const char* input, |
| 542 | size_t input_size, |
| 543 | char* op, |
| 544 | uint16* table, |
| 545 | const int table_size) { |
| 546 | // "ip" is the input pointer, and "op" is the output pointer. |
| 547 | const char* ip = input; |
| 548 | assert(input_size <= kBlockSize); |
| 549 | assert((table_size & (table_size - 1)) == 0); // table must be power of two |
| 550 | const int shift = 32 - Bits::Log2Floor(table_size); |
| 551 | assert(static_cast<int>(kuint32max >> shift) == table_size - 1); |
| 552 | const char* ip_end = input + input_size; |
| 553 | const char* base_ip = ip; |
| 554 | // Bytes in [next_emit, ip) will be emitted as literal bytes. Or |
| 555 | // [next_emit, ip_end) after the main loop. |
| 556 | const char* next_emit = ip; |
| 557 | |
| 558 | const size_t kInputMarginBytes = 15; |
| 559 | if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) { |
| 560 | const char* ip_limit = input + input_size - kInputMarginBytes; |
| 561 | |
| 562 | for (uint32 next_hash = Hash(++ip, shift); ; ) { |
| 563 | assert(next_emit < ip); |
| 564 | // The body of this loop calls EmitLiteral once and then EmitCopy one or |
| 565 | // more times. (The exception is that when we're close to exhausting |
| 566 | // the input we goto emit_remainder.) |
| 567 | // |
| 568 | // In the first iteration of this loop we're just starting, so |
| 569 | // there's nothing to copy, so calling EmitLiteral once is |
| 570 | // necessary. And we only start a new iteration when the |
| 571 | // current iteration has determined that a call to EmitLiteral will |
| 572 | // precede the next call to EmitCopy (if any). |
| 573 | // |
| 574 | // Step 1: Scan forward in the input looking for a 4-byte-long match. |
| 575 | // If we get close to exhausting the input then goto emit_remainder. |
| 576 | // |
| 577 | // Heuristic match skipping: If 32 bytes are scanned with no matches |
| 578 | // found, start looking only at every other byte. If 32 more bytes are |
| 579 | // scanned (or skipped), look at every third byte, etc.. When a match is |
| 580 | // found, immediately go back to looking at every byte. This is a small |
| 581 | // loss (~5% performance, ~0.1% density) for compressible data due to more |
| 582 | // bookkeeping, but for non-compressible data (such as JPEG) it's a huge |
| 583 | // win since the compressor quickly "realizes" the data is incompressible |
| 584 | // and doesn't bother looking for matches everywhere. |
| 585 | // |
| 586 | // The "skip" variable keeps track of how many bytes there are since the |
| 587 | // last match; dividing it by 32 (ie. right-shifting by five) gives the |
| 588 | // number of bytes to move ahead for each iteration. |
| 589 | uint32 skip = 32; |
| 590 | |
| 591 | const char* next_ip = ip; |
| 592 | const char* candidate; |
| 593 | do { |
| 594 | ip = next_ip; |
| 595 | uint32 hash = next_hash; |
| 596 | assert(hash == Hash(ip, shift)); |
| 597 | uint32 bytes_between_hash_lookups = skip >> 5; |
| 598 | skip += bytes_between_hash_lookups; |
| 599 | next_ip = ip + bytes_between_hash_lookups; |
| 600 | if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) { |
| 601 | goto emit_remainder; |
| 602 | } |
| 603 | next_hash = Hash(next_ip, shift); |
| 604 | candidate = base_ip + table[hash]; |
| 605 | assert(candidate >= base_ip); |
| 606 | assert(candidate < ip); |
| 607 | |
| 608 | table[hash] = ip - base_ip; |
| 609 | } while (SNAPPY_PREDICT_TRUE(UNALIGNED_LOAD32(ip) != |
| 610 | UNALIGNED_LOAD32(candidate))); |
| 611 | |
| 612 | // Step 2: A 4-byte match has been found. We'll later see if more |
| 613 | // than 4 bytes match. But, prior to the match, input |
| 614 | // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes." |
| 615 | assert(next_emit + 16 <= ip_end); |
| 616 | op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit, ip - next_emit); |
| 617 | |
| 618 | // Step 3: Call EmitCopy, and then see if another EmitCopy could |
| 619 | // be our next move. Repeat until we find no match for the |
| 620 | // input immediately after what was consumed by the last EmitCopy call. |
| 621 | // |
| 622 | // If we exit this loop normally then we need to call EmitLiteral next, |
| 623 | // though we don't yet know how big the literal will be. We handle that |
| 624 | // by proceeding to the next iteration of the main loop. We also can exit |
| 625 | // this loop via goto if we get close to exhausting the input. |
| 626 | EightBytesReference input_bytes; |
| 627 | uint32 candidate_bytes = 0; |
| 628 | |
| 629 | do { |
| 630 | // We have a 4-byte match at ip, and no need to emit any |
| 631 | // "literal bytes" prior to ip. |
| 632 | const char* base = ip; |
| 633 | std::pair<size_t, bool> p = |
| 634 | FindMatchLength(candidate + 4, ip + 4, ip_end); |
| 635 | size_t matched = 4 + p.first; |
| 636 | ip += matched; |
| 637 | size_t offset = base - candidate; |
| 638 | assert(0 == memcmp(base, candidate, matched)); |
| 639 | if (p.second) { |
| 640 | op = EmitCopy</*len_less_than_12=*/true>(op, offset, matched); |
| 641 | } else { |
| 642 | op = EmitCopy</*len_less_than_12=*/false>(op, offset, matched); |
| 643 | } |
| 644 | next_emit = ip; |
| 645 | if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) { |
| 646 | goto emit_remainder; |
| 647 | } |
| 648 | // We are now looking for a 4-byte match again. We read |
| 649 | // table[Hash(ip, shift)] for that. To improve compression, |
| 650 | // we also update table[Hash(ip - 1, shift)] and table[Hash(ip, shift)]. |
| 651 | input_bytes = GetEightBytesAt(ip - 1); |
| 652 | uint32 prev_hash = HashBytes(GetUint32AtOffset(input_bytes, 0), shift); |
| 653 | table[prev_hash] = ip - base_ip - 1; |
| 654 | uint32 cur_hash = HashBytes(GetUint32AtOffset(input_bytes, 1), shift); |
| 655 | candidate = base_ip + table[cur_hash]; |
| 656 | candidate_bytes = UNALIGNED_LOAD32(candidate); |
| 657 | table[cur_hash] = ip - base_ip; |
| 658 | } while (GetUint32AtOffset(input_bytes, 1) == candidate_bytes); |
| 659 | |
| 660 | next_hash = HashBytes(GetUint32AtOffset(input_bytes, 2), shift); |
| 661 | ++ip; |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | emit_remainder: |
| 666 | // Emit the remaining bytes as a literal |
| 667 | if (next_emit < ip_end) { |
| 668 | op = EmitLiteral</*allow_fast_path=*/false>(op, next_emit, |
| 669 | ip_end - next_emit); |
| 670 | } |
| 671 | |
| 672 | return op; |
| 673 | } |
| 674 | } // end namespace internal |
| 675 | |
| 676 | // Called back at avery compression call to trace parameters and sizes. |
| 677 | static inline void Report(const char *algorithm, size_t compressed_size, |
| 678 | size_t uncompressed_size) {} |
| 679 | |
| 680 | // Signature of output types needed by decompression code. |
| 681 | // The decompression code is templatized on a type that obeys this |
| 682 | // signature so that we do not pay virtual function call overhead in |
| 683 | // the middle of a tight decompression loop. |
| 684 | // |
| 685 | // class DecompressionWriter { |
| 686 | // public: |
| 687 | // // Called before decompression |
| 688 | // void SetExpectedLength(size_t length); |
| 689 | // |
| 690 | // // Called after decompression |
| 691 | // bool CheckLength() const; |
| 692 | // |
| 693 | // // Called repeatedly during decompression |
| 694 | // bool Append(const char* ip, size_t length); |
| 695 | // bool AppendFromSelf(uint32 offset, size_t length); |
| 696 | // |
| 697 | // // The rules for how TryFastAppend differs from Append are somewhat |
| 698 | // // convoluted: |
| 699 | // // |
| 700 | // // - TryFastAppend is allowed to decline (return false) at any |
| 701 | // // time, for any reason -- just "return false" would be |
| 702 | // // a perfectly legal implementation of TryFastAppend. |
| 703 | // // The intention is for TryFastAppend to allow a fast path |
| 704 | // // in the common case of a small append. |
| 705 | // // - TryFastAppend is allowed to read up to <available> bytes |
| 706 | // // from the input buffer, whereas Append is allowed to read |
| 707 | // // <length>. However, if it returns true, it must leave |
| 708 | // // at least five (kMaximumTagLength) bytes in the input buffer |
| 709 | // // afterwards, so that there is always enough space to read the |
| 710 | // // next tag without checking for a refill. |
| 711 | // // - TryFastAppend must always return decline (return false) |
| 712 | // // if <length> is 61 or more, as in this case the literal length is not |
| 713 | // // decoded fully. In practice, this should not be a big problem, |
| 714 | // // as it is unlikely that one would implement a fast path accepting |
| 715 | // // this much data. |
| 716 | // // |
| 717 | // bool TryFastAppend(const char* ip, size_t available, size_t length); |
| 718 | // }; |
| 719 | |
| 720 | static inline uint32 (uint32 v, int n) { |
| 721 | assert(n >= 0); |
| 722 | assert(n <= 4); |
| 723 | // TODO(b/121042345): Remove !defined(MEMORY_SANITIZER) once MSan |
| 724 | // handles _bzhi_u32() correctly. |
| 725 | #if SNAPPY_HAVE_BMI2 && !defined(MEMORY_SANITIZER) |
| 726 | return _bzhi_u32(v, 8 * n); |
| 727 | #else |
| 728 | // This needs to be wider than uint32 otherwise `mask << 32` will be |
| 729 | // undefined. |
| 730 | uint64 mask = 0xffffffff; |
| 731 | return v & ~(mask << (8 * n)); |
| 732 | #endif |
| 733 | } |
| 734 | |
| 735 | static inline bool LeftShiftOverflows(uint8 value, uint32 shift) { |
| 736 | assert(shift < 32); |
| 737 | static const uint8 masks[] = { |
| 738 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 739 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 740 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 741 | 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe}; |
| 742 | return (value & masks[shift]) != 0; |
| 743 | } |
| 744 | |
| 745 | // Helper class for decompression |
| 746 | class SnappyDecompressor { |
| 747 | private: |
| 748 | Source* reader_; // Underlying source of bytes to decompress |
| 749 | const char* ip_; // Points to next buffered byte |
| 750 | const char* ip_limit_; // Points just past buffered bytes |
| 751 | uint32 peeked_; // Bytes peeked from reader (need to skip) |
| 752 | bool eof_; // Hit end of input without an error? |
| 753 | char scratch_[kMaximumTagLength]; // See RefillTag(). |
| 754 | |
| 755 | // Ensure that all of the tag metadata for the next tag is available |
| 756 | // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even |
| 757 | // if (ip_limit_ - ip_ < 5). |
| 758 | // |
| 759 | // Returns true on success, false on error or end of input. |
| 760 | bool RefillTag(); |
| 761 | |
| 762 | public: |
| 763 | explicit SnappyDecompressor(Source* reader) |
| 764 | : reader_(reader), |
| 765 | ip_(NULL), |
| 766 | ip_limit_(NULL), |
| 767 | peeked_(0), |
| 768 | eof_(false) { |
| 769 | } |
| 770 | |
| 771 | ~SnappyDecompressor() { |
| 772 | // Advance past any bytes we peeked at from the reader |
| 773 | reader_->Skip(peeked_); |
| 774 | } |
| 775 | |
| 776 | // Returns true iff we have hit the end of the input without an error. |
| 777 | bool eof() const { |
| 778 | return eof_; |
| 779 | } |
| 780 | |
| 781 | // Read the uncompressed length stored at the start of the compressed data. |
| 782 | // On success, stores the length in *result and returns true. |
| 783 | // On failure, returns false. |
| 784 | bool ReadUncompressedLength(uint32* result) { |
| 785 | assert(ip_ == NULL); // Must not have read anything yet |
| 786 | // Length is encoded in 1..5 bytes |
| 787 | *result = 0; |
| 788 | uint32 shift = 0; |
| 789 | while (true) { |
| 790 | if (shift >= 32) return false; |
| 791 | size_t n; |
| 792 | const char* ip = reader_->Peek(&n); |
| 793 | if (n == 0) return false; |
| 794 | const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip)); |
| 795 | reader_->Skip(1); |
| 796 | uint32 val = c & 0x7f; |
| 797 | if (LeftShiftOverflows(static_cast<uint8>(val), shift)) return false; |
| 798 | *result |= val << shift; |
| 799 | if (c < 128) { |
| 800 | break; |
| 801 | } |
| 802 | shift += 7; |
| 803 | } |
| 804 | return true; |
| 805 | } |
| 806 | |
| 807 | // Process the next item found in the input. |
| 808 | // Returns true if successful, false on error or end of input. |
| 809 | template <class Writer> |
| 810 | #if defined(__GNUC__) && defined(__x86_64__) |
| 811 | __attribute__((aligned(32))) |
| 812 | #endif |
| 813 | void DecompressAllTags(Writer* writer) { |
| 814 | // In x86, pad the function body to start 16 bytes later. This function has |
| 815 | // a couple of hotspots that are highly sensitive to alignment: we have |
| 816 | // observed regressions by more than 20% in some metrics just by moving the |
| 817 | // exact same code to a different position in the benchmark binary. |
| 818 | // |
| 819 | // Putting this code on a 32-byte-aligned boundary + 16 bytes makes us hit |
| 820 | // the "lucky" case consistently. Unfortunately, this is a very brittle |
| 821 | // workaround, and future differences in code generation may reintroduce |
| 822 | // this regression. If you experience a big, difficult to explain, benchmark |
| 823 | // performance regression here, first try removing this hack. |
| 824 | #if defined(__GNUC__) && defined(__x86_64__) |
| 825 | // Two 8-byte "NOP DWORD ptr [EAX + EAX*1 + 00000000H]" instructions. |
| 826 | asm(".byte 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00" ); |
| 827 | asm(".byte 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00" ); |
| 828 | #endif |
| 829 | |
| 830 | const char* ip = ip_; |
| 831 | // We could have put this refill fragment only at the beginning of the loop. |
| 832 | // However, duplicating it at the end of each branch gives the compiler more |
| 833 | // scope to optimize the <ip_limit_ - ip> expression based on the local |
| 834 | // context, which overall increases speed. |
| 835 | #define MAYBE_REFILL() \ |
| 836 | if (ip_limit_ - ip < kMaximumTagLength) { \ |
| 837 | ip_ = ip; \ |
| 838 | if (!RefillTag()) return; \ |
| 839 | ip = ip_; \ |
| 840 | } |
| 841 | |
| 842 | MAYBE_REFILL(); |
| 843 | for ( ;; ) { |
| 844 | const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip++)); |
| 845 | |
| 846 | // Ratio of iterations that have LITERAL vs non-LITERAL for different |
| 847 | // inputs. |
| 848 | // |
| 849 | // input LITERAL NON_LITERAL |
| 850 | // ----------------------------------- |
| 851 | // html|html4|cp 23% 77% |
| 852 | // urls 36% 64% |
| 853 | // jpg 47% 53% |
| 854 | // pdf 19% 81% |
| 855 | // txt[1-4] 25% 75% |
| 856 | // pb 24% 76% |
| 857 | // bin 24% 76% |
| 858 | if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) { |
| 859 | size_t literal_length = (c >> 2) + 1u; |
| 860 | if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length)) { |
| 861 | assert(literal_length < 61); |
| 862 | ip += literal_length; |
| 863 | // NOTE(user): There is no MAYBE_REFILL() here, as TryFastAppend() |
| 864 | // will not return true unless there's already at least five spare |
| 865 | // bytes in addition to the literal. |
| 866 | continue; |
| 867 | } |
| 868 | if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) { |
| 869 | // Long literal. |
| 870 | const size_t literal_length_length = literal_length - 60; |
| 871 | literal_length = |
| 872 | ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) + |
| 873 | 1; |
| 874 | ip += literal_length_length; |
| 875 | } |
| 876 | |
| 877 | size_t avail = ip_limit_ - ip; |
| 878 | while (avail < literal_length) { |
| 879 | if (!writer->Append(ip, avail)) return; |
| 880 | literal_length -= avail; |
| 881 | reader_->Skip(peeked_); |
| 882 | size_t n; |
| 883 | ip = reader_->Peek(&n); |
| 884 | avail = n; |
| 885 | peeked_ = avail; |
| 886 | if (avail == 0) return; // Premature end of input |
| 887 | ip_limit_ = ip + avail; |
| 888 | } |
| 889 | if (!writer->Append(ip, literal_length)) { |
| 890 | return; |
| 891 | } |
| 892 | ip += literal_length; |
| 893 | MAYBE_REFILL(); |
| 894 | } else { |
| 895 | const size_t entry = char_table[c]; |
| 896 | const size_t trailer = |
| 897 | ExtractLowBytes(LittleEndian::Load32(ip), entry >> 11); |
| 898 | const size_t length = entry & 0xff; |
| 899 | ip += entry >> 11; |
| 900 | |
| 901 | // copy_offset/256 is encoded in bits 8..10. By just fetching |
| 902 | // those bits, we get copy_offset (since the bit-field starts at |
| 903 | // bit 8). |
| 904 | const size_t copy_offset = entry & 0x700; |
| 905 | if (!writer->AppendFromSelf(copy_offset + trailer, length)) { |
| 906 | return; |
| 907 | } |
| 908 | MAYBE_REFILL(); |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | #undef MAYBE_REFILL |
| 913 | } |
| 914 | }; |
| 915 | |
| 916 | bool SnappyDecompressor::RefillTag() { |
| 917 | const char* ip = ip_; |
| 918 | if (ip == ip_limit_) { |
| 919 | // Fetch a new fragment from the reader |
| 920 | reader_->Skip(peeked_); // All peeked bytes are used up |
| 921 | size_t n; |
| 922 | ip = reader_->Peek(&n); |
| 923 | peeked_ = n; |
| 924 | eof_ = (n == 0); |
| 925 | if (eof_) return false; |
| 926 | ip_limit_ = ip + n; |
| 927 | } |
| 928 | |
| 929 | // Read the tag character |
| 930 | assert(ip < ip_limit_); |
| 931 | const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip)); |
| 932 | const uint32 entry = char_table[c]; |
| 933 | const uint32 needed = (entry >> 11) + 1; // +1 byte for 'c' |
| 934 | assert(needed <= sizeof(scratch_)); |
| 935 | |
| 936 | // Read more bytes from reader if needed |
| 937 | uint32 nbuf = ip_limit_ - ip; |
| 938 | if (nbuf < needed) { |
| 939 | // Stitch together bytes from ip and reader to form the word |
| 940 | // contents. We store the needed bytes in "scratch_". They |
| 941 | // will be consumed immediately by the caller since we do not |
| 942 | // read more than we need. |
| 943 | memmove(scratch_, ip, nbuf); |
| 944 | reader_->Skip(peeked_); // All peeked bytes are used up |
| 945 | peeked_ = 0; |
| 946 | while (nbuf < needed) { |
| 947 | size_t length; |
| 948 | const char* src = reader_->Peek(&length); |
| 949 | if (length == 0) return false; |
| 950 | uint32 to_add = std::min<uint32>(needed - nbuf, length); |
| 951 | memcpy(scratch_ + nbuf, src, to_add); |
| 952 | nbuf += to_add; |
| 953 | reader_->Skip(to_add); |
| 954 | } |
| 955 | assert(nbuf == needed); |
| 956 | ip_ = scratch_; |
| 957 | ip_limit_ = scratch_ + needed; |
| 958 | } else if (nbuf < kMaximumTagLength) { |
| 959 | // Have enough bytes, but move into scratch_ so that we do not |
| 960 | // read past end of input |
| 961 | memmove(scratch_, ip, nbuf); |
| 962 | reader_->Skip(peeked_); // All peeked bytes are used up |
| 963 | peeked_ = 0; |
| 964 | ip_ = scratch_; |
| 965 | ip_limit_ = scratch_ + nbuf; |
| 966 | } else { |
| 967 | // Pass pointer to buffer returned by reader_. |
| 968 | ip_ = ip; |
| 969 | } |
| 970 | return true; |
| 971 | } |
| 972 | |
| 973 | template <typename Writer> |
| 974 | static bool InternalUncompress(Source* r, Writer* writer) { |
| 975 | // Read the uncompressed length from the front of the compressed input |
| 976 | SnappyDecompressor decompressor(r); |
| 977 | uint32 uncompressed_len = 0; |
| 978 | if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false; |
| 979 | |
| 980 | return InternalUncompressAllTags(&decompressor, writer, r->Available(), |
| 981 | uncompressed_len); |
| 982 | } |
| 983 | |
| 984 | template <typename Writer> |
| 985 | static bool InternalUncompressAllTags(SnappyDecompressor* decompressor, |
| 986 | Writer* writer, |
| 987 | uint32 compressed_len, |
| 988 | uint32 uncompressed_len) { |
| 989 | Report("snappy_uncompress" , compressed_len, uncompressed_len); |
| 990 | |
| 991 | writer->SetExpectedLength(uncompressed_len); |
| 992 | |
| 993 | // Process the entire input |
| 994 | decompressor->DecompressAllTags(writer); |
| 995 | writer->Flush(); |
| 996 | return (decompressor->eof() && writer->CheckLength()); |
| 997 | } |
| 998 | |
| 999 | bool GetUncompressedLength(Source* source, uint32* result) { |
| 1000 | SnappyDecompressor decompressor(source); |
| 1001 | return decompressor.ReadUncompressedLength(result); |
| 1002 | } |
| 1003 | |
| 1004 | size_t Compress(Source* reader, Sink* writer) { |
| 1005 | size_t written = 0; |
| 1006 | size_t N = reader->Available(); |
| 1007 | const size_t uncompressed_size = N; |
| 1008 | char ulength[Varint::kMax32]; |
| 1009 | char* p = Varint::Encode32(ulength, N); |
| 1010 | writer->Append(ulength, p-ulength); |
| 1011 | written += (p - ulength); |
| 1012 | |
| 1013 | internal::WorkingMemory wmem(N); |
| 1014 | |
| 1015 | while (N > 0) { |
| 1016 | // Get next block to compress (without copying if possible) |
| 1017 | size_t fragment_size; |
| 1018 | const char* fragment = reader->Peek(&fragment_size); |
| 1019 | assert(fragment_size != 0); // premature end of input |
| 1020 | const size_t num_to_read = std::min(N, kBlockSize); |
| 1021 | size_t bytes_read = fragment_size; |
| 1022 | |
| 1023 | size_t pending_advance = 0; |
| 1024 | if (bytes_read >= num_to_read) { |
| 1025 | // Buffer returned by reader is large enough |
| 1026 | pending_advance = num_to_read; |
| 1027 | fragment_size = num_to_read; |
| 1028 | } else { |
| 1029 | char* scratch = wmem.GetScratchInput(); |
| 1030 | memcpy(scratch, fragment, bytes_read); |
| 1031 | reader->Skip(bytes_read); |
| 1032 | |
| 1033 | while (bytes_read < num_to_read) { |
| 1034 | fragment = reader->Peek(&fragment_size); |
| 1035 | size_t n = std::min<size_t>(fragment_size, num_to_read - bytes_read); |
| 1036 | memcpy(scratch + bytes_read, fragment, n); |
| 1037 | bytes_read += n; |
| 1038 | reader->Skip(n); |
| 1039 | } |
| 1040 | assert(bytes_read == num_to_read); |
| 1041 | fragment = scratch; |
| 1042 | fragment_size = num_to_read; |
| 1043 | } |
| 1044 | assert(fragment_size == num_to_read); |
| 1045 | |
| 1046 | // Get encoding table for compression |
| 1047 | int table_size; |
| 1048 | uint16* table = wmem.GetHashTable(num_to_read, &table_size); |
| 1049 | |
| 1050 | // Compress input_fragment and append to dest |
| 1051 | const int max_output = MaxCompressedLength(num_to_read); |
| 1052 | |
| 1053 | // Need a scratch buffer for the output, in case the byte sink doesn't |
| 1054 | // have room for us directly. |
| 1055 | |
| 1056 | // Since we encode kBlockSize regions followed by a region |
| 1057 | // which is <= kBlockSize in length, a previously allocated |
| 1058 | // scratch_output[] region is big enough for this iteration. |
| 1059 | char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput()); |
| 1060 | char* end = internal::CompressFragment(fragment, fragment_size, dest, table, |
| 1061 | table_size); |
| 1062 | writer->Append(dest, end - dest); |
| 1063 | written += (end - dest); |
| 1064 | |
| 1065 | N -= num_to_read; |
| 1066 | reader->Skip(pending_advance); |
| 1067 | } |
| 1068 | |
| 1069 | Report("snappy_compress" , written, uncompressed_size); |
| 1070 | |
| 1071 | return written; |
| 1072 | } |
| 1073 | |
| 1074 | // ----------------------------------------------------------------------- |
| 1075 | // IOVec interfaces |
| 1076 | // ----------------------------------------------------------------------- |
| 1077 | |
| 1078 | // A type that writes to an iovec. |
| 1079 | // Note that this is not a "ByteSink", but a type that matches the |
| 1080 | // Writer template argument to SnappyDecompressor::DecompressAllTags(). |
| 1081 | class SnappyIOVecWriter { |
| 1082 | private: |
| 1083 | // output_iov_end_ is set to iov + count and used to determine when |
| 1084 | // the end of the iovs is reached. |
| 1085 | const struct iovec* output_iov_end_; |
| 1086 | |
| 1087 | #if !defined(NDEBUG) |
| 1088 | const struct iovec* output_iov_; |
| 1089 | #endif // !defined(NDEBUG) |
| 1090 | |
| 1091 | // Current iov that is being written into. |
| 1092 | const struct iovec* curr_iov_; |
| 1093 | |
| 1094 | // Pointer to current iov's write location. |
| 1095 | char* curr_iov_output_; |
| 1096 | |
| 1097 | // Remaining bytes to write into curr_iov_output. |
| 1098 | size_t curr_iov_remaining_; |
| 1099 | |
| 1100 | // Total bytes decompressed into output_iov_ so far. |
| 1101 | size_t total_written_; |
| 1102 | |
| 1103 | // Maximum number of bytes that will be decompressed into output_iov_. |
| 1104 | size_t output_limit_; |
| 1105 | |
| 1106 | static inline char* GetIOVecPointer(const struct iovec* iov, size_t offset) { |
| 1107 | return reinterpret_cast<char*>(iov->iov_base) + offset; |
| 1108 | } |
| 1109 | |
| 1110 | public: |
| 1111 | // Does not take ownership of iov. iov must be valid during the |
| 1112 | // entire lifetime of the SnappyIOVecWriter. |
| 1113 | inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count) |
| 1114 | : output_iov_end_(iov + iov_count), |
| 1115 | #if !defined(NDEBUG) |
| 1116 | output_iov_(iov), |
| 1117 | #endif // !defined(NDEBUG) |
| 1118 | curr_iov_(iov), |
| 1119 | curr_iov_output_(iov_count ? reinterpret_cast<char*>(iov->iov_base) |
| 1120 | : nullptr), |
| 1121 | curr_iov_remaining_(iov_count ? iov->iov_len : 0), |
| 1122 | total_written_(0), |
| 1123 | output_limit_(-1) {} |
| 1124 | |
| 1125 | inline void SetExpectedLength(size_t len) { |
| 1126 | output_limit_ = len; |
| 1127 | } |
| 1128 | |
| 1129 | inline bool CheckLength() const { |
| 1130 | return total_written_ == output_limit_; |
| 1131 | } |
| 1132 | |
| 1133 | inline bool Append(const char* ip, size_t len) { |
| 1134 | if (total_written_ + len > output_limit_) { |
| 1135 | return false; |
| 1136 | } |
| 1137 | |
| 1138 | return AppendNoCheck(ip, len); |
| 1139 | } |
| 1140 | |
| 1141 | inline bool AppendNoCheck(const char* ip, size_t len) { |
| 1142 | while (len > 0) { |
| 1143 | if (curr_iov_remaining_ == 0) { |
| 1144 | // This iovec is full. Go to the next one. |
| 1145 | if (curr_iov_ + 1 >= output_iov_end_) { |
| 1146 | return false; |
| 1147 | } |
| 1148 | ++curr_iov_; |
| 1149 | curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base); |
| 1150 | curr_iov_remaining_ = curr_iov_->iov_len; |
| 1151 | } |
| 1152 | |
| 1153 | const size_t to_write = std::min(len, curr_iov_remaining_); |
| 1154 | memcpy(curr_iov_output_, ip, to_write); |
| 1155 | curr_iov_output_ += to_write; |
| 1156 | curr_iov_remaining_ -= to_write; |
| 1157 | total_written_ += to_write; |
| 1158 | ip += to_write; |
| 1159 | len -= to_write; |
| 1160 | } |
| 1161 | |
| 1162 | return true; |
| 1163 | } |
| 1164 | |
| 1165 | inline bool TryFastAppend(const char* ip, size_t available, size_t len) { |
| 1166 | const size_t space_left = output_limit_ - total_written_; |
| 1167 | if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 && |
| 1168 | curr_iov_remaining_ >= 16) { |
| 1169 | // Fast path, used for the majority (about 95%) of invocations. |
| 1170 | UnalignedCopy128(ip, curr_iov_output_); |
| 1171 | curr_iov_output_ += len; |
| 1172 | curr_iov_remaining_ -= len; |
| 1173 | total_written_ += len; |
| 1174 | return true; |
| 1175 | } |
| 1176 | |
| 1177 | return false; |
| 1178 | } |
| 1179 | |
| 1180 | inline bool AppendFromSelf(size_t offset, size_t len) { |
| 1181 | // See SnappyArrayWriter::AppendFromSelf for an explanation of |
| 1182 | // the "offset - 1u" trick. |
| 1183 | if (offset - 1u >= total_written_) { |
| 1184 | return false; |
| 1185 | } |
| 1186 | const size_t space_left = output_limit_ - total_written_; |
| 1187 | if (len > space_left) { |
| 1188 | return false; |
| 1189 | } |
| 1190 | |
| 1191 | // Locate the iovec from which we need to start the copy. |
| 1192 | const iovec* from_iov = curr_iov_; |
| 1193 | size_t from_iov_offset = curr_iov_->iov_len - curr_iov_remaining_; |
| 1194 | while (offset > 0) { |
| 1195 | if (from_iov_offset >= offset) { |
| 1196 | from_iov_offset -= offset; |
| 1197 | break; |
| 1198 | } |
| 1199 | |
| 1200 | offset -= from_iov_offset; |
| 1201 | --from_iov; |
| 1202 | #if !defined(NDEBUG) |
| 1203 | assert(from_iov >= output_iov_); |
| 1204 | #endif // !defined(NDEBUG) |
| 1205 | from_iov_offset = from_iov->iov_len; |
| 1206 | } |
| 1207 | |
| 1208 | // Copy <len> bytes starting from the iovec pointed to by from_iov_index to |
| 1209 | // the current iovec. |
| 1210 | while (len > 0) { |
| 1211 | assert(from_iov <= curr_iov_); |
| 1212 | if (from_iov != curr_iov_) { |
| 1213 | const size_t to_copy = |
| 1214 | std::min(from_iov->iov_len - from_iov_offset, len); |
| 1215 | AppendNoCheck(GetIOVecPointer(from_iov, from_iov_offset), to_copy); |
| 1216 | len -= to_copy; |
| 1217 | if (len > 0) { |
| 1218 | ++from_iov; |
| 1219 | from_iov_offset = 0; |
| 1220 | } |
| 1221 | } else { |
| 1222 | size_t to_copy = curr_iov_remaining_; |
| 1223 | if (to_copy == 0) { |
| 1224 | // This iovec is full. Go to the next one. |
| 1225 | if (curr_iov_ + 1 >= output_iov_end_) { |
| 1226 | return false; |
| 1227 | } |
| 1228 | ++curr_iov_; |
| 1229 | curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base); |
| 1230 | curr_iov_remaining_ = curr_iov_->iov_len; |
| 1231 | continue; |
| 1232 | } |
| 1233 | if (to_copy > len) { |
| 1234 | to_copy = len; |
| 1235 | } |
| 1236 | |
| 1237 | IncrementalCopy(GetIOVecPointer(from_iov, from_iov_offset), |
| 1238 | curr_iov_output_, curr_iov_output_ + to_copy, |
| 1239 | curr_iov_output_ + curr_iov_remaining_); |
| 1240 | curr_iov_output_ += to_copy; |
| 1241 | curr_iov_remaining_ -= to_copy; |
| 1242 | from_iov_offset += to_copy; |
| 1243 | total_written_ += to_copy; |
| 1244 | len -= to_copy; |
| 1245 | } |
| 1246 | } |
| 1247 | |
| 1248 | return true; |
| 1249 | } |
| 1250 | |
| 1251 | inline void Flush() {} |
| 1252 | }; |
| 1253 | |
| 1254 | bool RawUncompressToIOVec(const char* compressed, size_t compressed_length, |
| 1255 | const struct iovec* iov, size_t iov_cnt) { |
| 1256 | ByteArraySource reader(compressed, compressed_length); |
| 1257 | return RawUncompressToIOVec(&reader, iov, iov_cnt); |
| 1258 | } |
| 1259 | |
| 1260 | bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov, |
| 1261 | size_t iov_cnt) { |
| 1262 | SnappyIOVecWriter output(iov, iov_cnt); |
| 1263 | return InternalUncompress(compressed, &output); |
| 1264 | } |
| 1265 | |
| 1266 | // ----------------------------------------------------------------------- |
| 1267 | // Flat array interfaces |
| 1268 | // ----------------------------------------------------------------------- |
| 1269 | |
| 1270 | // A type that writes to a flat array. |
| 1271 | // Note that this is not a "ByteSink", but a type that matches the |
| 1272 | // Writer template argument to SnappyDecompressor::DecompressAllTags(). |
| 1273 | class SnappyArrayWriter { |
| 1274 | private: |
| 1275 | char* base_; |
| 1276 | char* op_; |
| 1277 | char* op_limit_; |
| 1278 | |
| 1279 | public: |
| 1280 | inline explicit SnappyArrayWriter(char* dst) |
| 1281 | : base_(dst), |
| 1282 | op_(dst), |
| 1283 | op_limit_(dst) { |
| 1284 | } |
| 1285 | |
| 1286 | inline void SetExpectedLength(size_t len) { |
| 1287 | op_limit_ = op_ + len; |
| 1288 | } |
| 1289 | |
| 1290 | inline bool CheckLength() const { |
| 1291 | return op_ == op_limit_; |
| 1292 | } |
| 1293 | |
| 1294 | inline bool Append(const char* ip, size_t len) { |
| 1295 | char* op = op_; |
| 1296 | const size_t space_left = op_limit_ - op; |
| 1297 | if (space_left < len) { |
| 1298 | return false; |
| 1299 | } |
| 1300 | memcpy(op, ip, len); |
| 1301 | op_ = op + len; |
| 1302 | return true; |
| 1303 | } |
| 1304 | |
| 1305 | inline bool TryFastAppend(const char* ip, size_t available, size_t len) { |
| 1306 | char* op = op_; |
| 1307 | const size_t space_left = op_limit_ - op; |
| 1308 | if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) { |
| 1309 | // Fast path, used for the majority (about 95%) of invocations. |
| 1310 | UnalignedCopy128(ip, op); |
| 1311 | op_ = op + len; |
| 1312 | return true; |
| 1313 | } else { |
| 1314 | return false; |
| 1315 | } |
| 1316 | } |
| 1317 | |
| 1318 | inline bool AppendFromSelf(size_t offset, size_t len) { |
| 1319 | char* const op_end = op_ + len; |
| 1320 | |
| 1321 | // Check if we try to append from before the start of the buffer. |
| 1322 | // Normally this would just be a check for "produced < offset", |
| 1323 | // but "produced <= offset - 1u" is equivalent for every case |
| 1324 | // except the one where offset==0, where the right side will wrap around |
| 1325 | // to a very big number. This is convenient, as offset==0 is another |
| 1326 | // invalid case that we also want to catch, so that we do not go |
| 1327 | // into an infinite loop. |
| 1328 | if (Produced() <= offset - 1u || op_end > op_limit_) return false; |
| 1329 | op_ = IncrementalCopy(op_ - offset, op_, op_end, op_limit_); |
| 1330 | |
| 1331 | return true; |
| 1332 | } |
| 1333 | inline size_t Produced() const { |
| 1334 | assert(op_ >= base_); |
| 1335 | return op_ - base_; |
| 1336 | } |
| 1337 | inline void Flush() {} |
| 1338 | }; |
| 1339 | |
| 1340 | bool RawUncompress(const char* compressed, size_t n, char* uncompressed) { |
| 1341 | ByteArraySource reader(compressed, n); |
| 1342 | return RawUncompress(&reader, uncompressed); |
| 1343 | } |
| 1344 | |
| 1345 | bool RawUncompress(Source* compressed, char* uncompressed) { |
| 1346 | SnappyArrayWriter output(uncompressed); |
| 1347 | return InternalUncompress(compressed, &output); |
| 1348 | } |
| 1349 | |
| 1350 | bool Uncompress(const char* compressed, size_t n, string* uncompressed) { |
| 1351 | size_t ulength; |
| 1352 | if (!GetUncompressedLength(compressed, n, &ulength)) { |
| 1353 | return false; |
| 1354 | } |
| 1355 | // On 32-bit builds: max_size() < kuint32max. Check for that instead |
| 1356 | // of crashing (e.g., consider externally specified compressed data). |
| 1357 | if (ulength > uncompressed->max_size()) { |
| 1358 | return false; |
| 1359 | } |
| 1360 | STLStringResizeUninitialized(uncompressed, ulength); |
| 1361 | return RawUncompress(compressed, n, string_as_array(uncompressed)); |
| 1362 | } |
| 1363 | |
| 1364 | // A Writer that drops everything on the floor and just does validation |
| 1365 | class SnappyDecompressionValidator { |
| 1366 | private: |
| 1367 | size_t expected_; |
| 1368 | size_t produced_; |
| 1369 | |
| 1370 | public: |
| 1371 | inline SnappyDecompressionValidator() : expected_(0), produced_(0) { } |
| 1372 | inline void SetExpectedLength(size_t len) { |
| 1373 | expected_ = len; |
| 1374 | } |
| 1375 | inline bool CheckLength() const { |
| 1376 | return expected_ == produced_; |
| 1377 | } |
| 1378 | inline bool Append(const char* ip, size_t len) { |
| 1379 | produced_ += len; |
| 1380 | return produced_ <= expected_; |
| 1381 | } |
| 1382 | inline bool TryFastAppend(const char* ip, size_t available, size_t length) { |
| 1383 | return false; |
| 1384 | } |
| 1385 | inline bool AppendFromSelf(size_t offset, size_t len) { |
| 1386 | // See SnappyArrayWriter::AppendFromSelf for an explanation of |
| 1387 | // the "offset - 1u" trick. |
| 1388 | if (produced_ <= offset - 1u) return false; |
| 1389 | produced_ += len; |
| 1390 | return produced_ <= expected_; |
| 1391 | } |
| 1392 | inline void Flush() {} |
| 1393 | }; |
| 1394 | |
| 1395 | bool IsValidCompressedBuffer(const char* compressed, size_t n) { |
| 1396 | ByteArraySource reader(compressed, n); |
| 1397 | SnappyDecompressionValidator writer; |
| 1398 | return InternalUncompress(&reader, &writer); |
| 1399 | } |
| 1400 | |
| 1401 | bool IsValidCompressed(Source* compressed) { |
| 1402 | SnappyDecompressionValidator writer; |
| 1403 | return InternalUncompress(compressed, &writer); |
| 1404 | } |
| 1405 | |
| 1406 | void RawCompress(const char* input, |
| 1407 | size_t input_length, |
| 1408 | char* compressed, |
| 1409 | size_t* compressed_length) { |
| 1410 | ByteArraySource reader(input, input_length); |
| 1411 | UncheckedByteArraySink writer(compressed); |
| 1412 | Compress(&reader, &writer); |
| 1413 | |
| 1414 | // Compute how many bytes were added |
| 1415 | *compressed_length = (writer.CurrentDestination() - compressed); |
| 1416 | } |
| 1417 | |
| 1418 | size_t Compress(const char* input, size_t input_length, string* compressed) { |
| 1419 | // Pre-grow the buffer to the max length of the compressed output |
| 1420 | STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length)); |
| 1421 | |
| 1422 | size_t compressed_length; |
| 1423 | RawCompress(input, input_length, string_as_array(compressed), |
| 1424 | &compressed_length); |
| 1425 | compressed->resize(compressed_length); |
| 1426 | return compressed_length; |
| 1427 | } |
| 1428 | |
| 1429 | // ----------------------------------------------------------------------- |
| 1430 | // Sink interface |
| 1431 | // ----------------------------------------------------------------------- |
| 1432 | |
| 1433 | // A type that decompresses into a Sink. The template parameter |
| 1434 | // Allocator must export one method "char* Allocate(int size);", which |
| 1435 | // allocates a buffer of "size" and appends that to the destination. |
| 1436 | template <typename Allocator> |
| 1437 | class SnappyScatteredWriter { |
| 1438 | Allocator allocator_; |
| 1439 | |
| 1440 | // We need random access into the data generated so far. Therefore |
| 1441 | // we keep track of all of the generated data as an array of blocks. |
| 1442 | // All of the blocks except the last have length kBlockSize. |
| 1443 | std::vector<char*> blocks_; |
| 1444 | size_t expected_; |
| 1445 | |
| 1446 | // Total size of all fully generated blocks so far |
| 1447 | size_t full_size_; |
| 1448 | |
| 1449 | // Pointer into current output block |
| 1450 | char* op_base_; // Base of output block |
| 1451 | char* op_ptr_; // Pointer to next unfilled byte in block |
| 1452 | char* op_limit_; // Pointer just past block |
| 1453 | |
| 1454 | inline size_t Size() const { |
| 1455 | return full_size_ + (op_ptr_ - op_base_); |
| 1456 | } |
| 1457 | |
| 1458 | bool SlowAppend(const char* ip, size_t len); |
| 1459 | bool SlowAppendFromSelf(size_t offset, size_t len); |
| 1460 | |
| 1461 | public: |
| 1462 | inline explicit SnappyScatteredWriter(const Allocator& allocator) |
| 1463 | : allocator_(allocator), |
| 1464 | full_size_(0), |
| 1465 | op_base_(NULL), |
| 1466 | op_ptr_(NULL), |
| 1467 | op_limit_(NULL) { |
| 1468 | } |
| 1469 | |
| 1470 | inline void SetExpectedLength(size_t len) { |
| 1471 | assert(blocks_.empty()); |
| 1472 | expected_ = len; |
| 1473 | } |
| 1474 | |
| 1475 | inline bool CheckLength() const { |
| 1476 | return Size() == expected_; |
| 1477 | } |
| 1478 | |
| 1479 | // Return the number of bytes actually uncompressed so far |
| 1480 | inline size_t Produced() const { |
| 1481 | return Size(); |
| 1482 | } |
| 1483 | |
| 1484 | inline bool Append(const char* ip, size_t len) { |
| 1485 | size_t avail = op_limit_ - op_ptr_; |
| 1486 | if (len <= avail) { |
| 1487 | // Fast path |
| 1488 | memcpy(op_ptr_, ip, len); |
| 1489 | op_ptr_ += len; |
| 1490 | return true; |
| 1491 | } else { |
| 1492 | return SlowAppend(ip, len); |
| 1493 | } |
| 1494 | } |
| 1495 | |
| 1496 | inline bool TryFastAppend(const char* ip, size_t available, size_t length) { |
| 1497 | char* op = op_ptr_; |
| 1498 | const int space_left = op_limit_ - op; |
| 1499 | if (length <= 16 && available >= 16 + kMaximumTagLength && |
| 1500 | space_left >= 16) { |
| 1501 | // Fast path, used for the majority (about 95%) of invocations. |
| 1502 | UnalignedCopy128(ip, op); |
| 1503 | op_ptr_ = op + length; |
| 1504 | return true; |
| 1505 | } else { |
| 1506 | return false; |
| 1507 | } |
| 1508 | } |
| 1509 | |
| 1510 | inline bool AppendFromSelf(size_t offset, size_t len) { |
| 1511 | char* const op_end = op_ptr_ + len; |
| 1512 | // See SnappyArrayWriter::AppendFromSelf for an explanation of |
| 1513 | // the "offset - 1u" trick. |
| 1514 | if (SNAPPY_PREDICT_TRUE(offset - 1u < op_ptr_ - op_base_ && |
| 1515 | op_end <= op_limit_)) { |
| 1516 | // Fast path: src and dst in current block. |
| 1517 | op_ptr_ = IncrementalCopy(op_ptr_ - offset, op_ptr_, op_end, op_limit_); |
| 1518 | return true; |
| 1519 | } |
| 1520 | return SlowAppendFromSelf(offset, len); |
| 1521 | } |
| 1522 | |
| 1523 | // Called at the end of the decompress. We ask the allocator |
| 1524 | // write all blocks to the sink. |
| 1525 | inline void Flush() { allocator_.Flush(Produced()); } |
| 1526 | }; |
| 1527 | |
| 1528 | template<typename Allocator> |
| 1529 | bool SnappyScatteredWriter<Allocator>::SlowAppend(const char* ip, size_t len) { |
| 1530 | size_t avail = op_limit_ - op_ptr_; |
| 1531 | while (len > avail) { |
| 1532 | // Completely fill this block |
| 1533 | memcpy(op_ptr_, ip, avail); |
| 1534 | op_ptr_ += avail; |
| 1535 | assert(op_limit_ - op_ptr_ == 0); |
| 1536 | full_size_ += (op_ptr_ - op_base_); |
| 1537 | len -= avail; |
| 1538 | ip += avail; |
| 1539 | |
| 1540 | // Bounds check |
| 1541 | if (full_size_ + len > expected_) { |
| 1542 | return false; |
| 1543 | } |
| 1544 | |
| 1545 | // Make new block |
| 1546 | size_t bsize = std::min<size_t>(kBlockSize, expected_ - full_size_); |
| 1547 | op_base_ = allocator_.Allocate(bsize); |
| 1548 | op_ptr_ = op_base_; |
| 1549 | op_limit_ = op_base_ + bsize; |
| 1550 | blocks_.push_back(op_base_); |
| 1551 | avail = bsize; |
| 1552 | } |
| 1553 | |
| 1554 | memcpy(op_ptr_, ip, len); |
| 1555 | op_ptr_ += len; |
| 1556 | return true; |
| 1557 | } |
| 1558 | |
| 1559 | template<typename Allocator> |
| 1560 | bool SnappyScatteredWriter<Allocator>::SlowAppendFromSelf(size_t offset, |
| 1561 | size_t len) { |
| 1562 | // Overflow check |
| 1563 | // See SnappyArrayWriter::AppendFromSelf for an explanation of |
| 1564 | // the "offset - 1u" trick. |
| 1565 | const size_t cur = Size(); |
| 1566 | if (offset - 1u >= cur) return false; |
| 1567 | if (expected_ - cur < len) return false; |
| 1568 | |
| 1569 | // Currently we shouldn't ever hit this path because Compress() chops the |
| 1570 | // input into blocks and does not create cross-block copies. However, it is |
| 1571 | // nice if we do not rely on that, since we can get better compression if we |
| 1572 | // allow cross-block copies and thus might want to change the compressor in |
| 1573 | // the future. |
| 1574 | size_t src = cur - offset; |
| 1575 | while (len-- > 0) { |
| 1576 | char c = blocks_[src >> kBlockLog][src & (kBlockSize-1)]; |
| 1577 | Append(&c, 1); |
| 1578 | src++; |
| 1579 | } |
| 1580 | return true; |
| 1581 | } |
| 1582 | |
| 1583 | class SnappySinkAllocator { |
| 1584 | public: |
| 1585 | explicit SnappySinkAllocator(Sink* dest): dest_(dest) {} |
| 1586 | ~SnappySinkAllocator() {} |
| 1587 | |
| 1588 | char* Allocate(int size) { |
| 1589 | Datablock block(new char[size], size); |
| 1590 | blocks_.push_back(block); |
| 1591 | return block.data; |
| 1592 | } |
| 1593 | |
| 1594 | // We flush only at the end, because the writer wants |
| 1595 | // random access to the blocks and once we hand the |
| 1596 | // block over to the sink, we can't access it anymore. |
| 1597 | // Also we don't write more than has been actually written |
| 1598 | // to the blocks. |
| 1599 | void Flush(size_t size) { |
| 1600 | size_t size_written = 0; |
| 1601 | size_t block_size; |
| 1602 | for (int i = 0; i < blocks_.size(); ++i) { |
| 1603 | block_size = std::min<size_t>(blocks_[i].size, size - size_written); |
| 1604 | dest_->AppendAndTakeOwnership(blocks_[i].data, block_size, |
| 1605 | &SnappySinkAllocator::Deleter, NULL); |
| 1606 | size_written += block_size; |
| 1607 | } |
| 1608 | blocks_.clear(); |
| 1609 | } |
| 1610 | |
| 1611 | private: |
| 1612 | struct Datablock { |
| 1613 | char* data; |
| 1614 | size_t size; |
| 1615 | Datablock(char* p, size_t s) : data(p), size(s) {} |
| 1616 | }; |
| 1617 | |
| 1618 | static void Deleter(void* arg, const char* bytes, size_t size) { |
| 1619 | delete[] bytes; |
| 1620 | } |
| 1621 | |
| 1622 | Sink* dest_; |
| 1623 | std::vector<Datablock> blocks_; |
| 1624 | |
| 1625 | // Note: copying this object is allowed |
| 1626 | }; |
| 1627 | |
| 1628 | size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) { |
| 1629 | SnappySinkAllocator allocator(uncompressed); |
| 1630 | SnappyScatteredWriter<SnappySinkAllocator> writer(allocator); |
| 1631 | InternalUncompress(compressed, &writer); |
| 1632 | return writer.Produced(); |
| 1633 | } |
| 1634 | |
| 1635 | bool Uncompress(Source* compressed, Sink* uncompressed) { |
| 1636 | // Read the uncompressed length from the front of the compressed input |
| 1637 | SnappyDecompressor decompressor(compressed); |
| 1638 | uint32 uncompressed_len = 0; |
| 1639 | if (!decompressor.ReadUncompressedLength(&uncompressed_len)) { |
| 1640 | return false; |
| 1641 | } |
| 1642 | |
| 1643 | char c; |
| 1644 | size_t allocated_size; |
| 1645 | char* buf = uncompressed->GetAppendBufferVariable( |
| 1646 | 1, uncompressed_len, &c, 1, &allocated_size); |
| 1647 | |
| 1648 | const size_t compressed_len = compressed->Available(); |
| 1649 | // If we can get a flat buffer, then use it, otherwise do block by block |
| 1650 | // uncompression |
| 1651 | if (allocated_size >= uncompressed_len) { |
| 1652 | SnappyArrayWriter writer(buf); |
| 1653 | bool result = InternalUncompressAllTags(&decompressor, &writer, |
| 1654 | compressed_len, uncompressed_len); |
| 1655 | uncompressed->Append(buf, writer.Produced()); |
| 1656 | return result; |
| 1657 | } else { |
| 1658 | SnappySinkAllocator allocator(uncompressed); |
| 1659 | SnappyScatteredWriter<SnappySinkAllocator> writer(allocator); |
| 1660 | return InternalUncompressAllTags(&decompressor, &writer, compressed_len, |
| 1661 | uncompressed_len); |
| 1662 | } |
| 1663 | } |
| 1664 | |
| 1665 | } // namespace snappy |
| 1666 | |