Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1319 lines
45 KiB

  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. #include "snappy.h"
  29. #include "snappy-internal.h"
  30. #include "snappy-sinksource.h"
  31. #include <stdio.h>
  32. #include <algorithm>
  33. #include <string>
  34. #include <vector>
  35. #ifdef _WIN32
  36. #pragma warning(disable:4018) // warning C4018: '<' : signed/unsigned mismatch
  37. #pragma warning(disable:4389) // warning C4389: '==' : signed/unsigned mismatch
  38. /* Define like size_t, omitting the "unsigned" */
  39. #ifdef _WIN64
  40. typedef __int64 ssize_t;
  41. #else
  42. typedef int ssize_t;
  43. #endif
  44. #endif //_WIN32
  45. namespace snappy {
  46. // Any hash function will produce a valid compressed bitstream, but a good
  47. // hash function reduces the number of collisions and thus yields better
  48. // compression for compressible input, and more speed for incompressible
  49. // input. Of course, it doesn't hurt if the hash function is reasonably fast
  50. // either, as it gets called a lot.
  51. static inline uint32 HashBytes(uint32 bytes, int shift) {
  52. uint32 kMul = 0x1e35a7bd;
  53. return (bytes * kMul) >> shift;
  54. }
  55. static inline uint32 Hash(const char* p, int shift) {
  56. return HashBytes(UNALIGNED_LOAD32(p), shift);
  57. }
  58. size_t MaxCompressedLength(size_t source_len) {
  59. // Compressed data can be defined as:
  60. // compressed := item* literal*
  61. // item := literal* copy
  62. //
  63. // The trailing literal sequence has a space blowup of at most 62/60
  64. // since a literal of length 60 needs one tag byte + one extra byte
  65. // for length information.
  66. //
  67. // Item blowup is trickier to measure. Suppose the "copy" op copies
  68. // 4 bytes of data. Because of a special check in the encoding code,
  69. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  70. // the copy op takes 3 bytes to encode, and this type of item leads
  71. // to at most the 62/60 blowup for representing literals.
  72. //
  73. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  74. // enough, it will take 5 bytes to encode the copy op. Therefore the
  75. // worst case here is a one-byte literal followed by a five-byte copy.
  76. // I.e., 6 bytes of input turn into 7 bytes of "compressed" data.
  77. //
  78. // This last factor dominates the blowup, so the final estimate is:
  79. return 32 + source_len + source_len/6;
  80. }
  81. enum {
  82. LITERAL = 0,
  83. COPY_1_BYTE_OFFSET = 1, // 3 bit length + 3 bits of offset in opcode
  84. COPY_2_BYTE_OFFSET = 2,
  85. COPY_4_BYTE_OFFSET = 3
  86. };
  87. static const int kMaximumTagLength = 5; // COPY_4_BYTE_OFFSET plus the actual offset.
  88. // Copy "len" bytes from "src" to "op", one byte at a time. Used for
  89. // handling COPY operations where the input and output regions may
  90. // overlap. For example, suppose:
  91. // src == "ab"
  92. // op == src + 2
  93. // len == 20
  94. // After IncrementalCopy(src, op, len), the result will have
  95. // eleven copies of "ab"
  96. // ababababababababababab
  97. // Note that this does not match the semantics of either memcpy()
  98. // or memmove().
  99. static inline void IncrementalCopy(const char* src, char* op, ssize_t len) {
  100. assert(len > 0);
  101. do {
  102. *op++ = *src++;
  103. } while (--len > 0);
  104. }
  105. // Equivalent to IncrementalCopy except that it can write up to ten extra
  106. // bytes after the end of the copy, and that it is faster.
  107. //
  108. // The main part of this loop is a simple copy of eight bytes at a time until
  109. // we've copied (at least) the requested amount of bytes. However, if op and
  110. // src are less than eight bytes apart (indicating a repeating pattern of
  111. // length < 8), we first need to expand the pattern in order to get the correct
  112. // results. For instance, if the buffer looks like this, with the eight-byte
  113. // <src> and <op> patterns marked as intervals:
  114. //
  115. // abxxxxxxxxxxxx
  116. // [------] src
  117. // [------] op
  118. //
  119. // a single eight-byte copy from <src> to <op> will repeat the pattern once,
  120. // after which we can move <op> two bytes without moving <src>:
  121. //
  122. // ababxxxxxxxxxx
  123. // [------] src
  124. // [------] op
  125. //
  126. // and repeat the exercise until the two no longer overlap.
  127. //
  128. // This allows us to do very well in the special case of one single byte
  129. // repeated many times, without taking a big hit for more general cases.
  130. //
  131. // The worst case of extra writing past the end of the match occurs when
  132. // op - src == 1 and len == 1; the last copy will read from byte positions
  133. // [0..7] and write to [4..11], whereas it was only supposed to write to
  134. // position 1. Thus, ten excess bytes.
  135. namespace {
  136. const int kMaxIncrementCopyOverflow = 10;
  137. inline void IncrementalCopyFastPath(const char* src, char* op, ssize_t len) {
  138. while (op - src < 8) {
  139. UnalignedCopy64(src, op);
  140. len -= op - src;
  141. op += op - src;
  142. }
  143. while (len > 0) {
  144. UnalignedCopy64(src, op);
  145. src += 8;
  146. op += 8;
  147. len -= 8;
  148. }
  149. }
  150. } // namespace
  151. static inline char* EmitLiteral(char* op,
  152. const char* literal,
  153. int len,
  154. bool allow_fast_path) {
  155. int n = len - 1; // Zero-length literals are disallowed
  156. if (n < 60) {
  157. // Fits in tag byte
  158. *op++ = LITERAL | (n << 2);
  159. // The vast majority of copies are below 16 bytes, for which a
  160. // call to memcpy is overkill. This fast path can sometimes
  161. // copy up to 15 bytes too much, but that is okay in the
  162. // main loop, since we have a bit to go on for both sides:
  163. //
  164. // - The input will always have kInputMarginBytes = 15 extra
  165. // available bytes, as long as we're in the main loop, and
  166. // if not, allow_fast_path = false.
  167. // - The output will always have 32 spare bytes (see
  168. // MaxCompressedLength).
  169. if (allow_fast_path && len <= 16) {
  170. UnalignedCopy64(literal, op);
  171. UnalignedCopy64(literal + 8, op + 8);
  172. return op + len;
  173. }
  174. } else {
  175. // Encode in upcoming bytes
  176. char* base = op;
  177. int count = 0;
  178. op++;
  179. while (n > 0) {
  180. *op++ = n & 0xff;
  181. n >>= 8;
  182. count++;
  183. }
  184. assert(count >= 1);
  185. assert(count <= 4);
  186. *base = LITERAL | ((59+count) << 2);
  187. }
  188. memcpy(op, literal, len);
  189. return op + len;
  190. }
  191. static inline char* EmitCopyLessThan64(char* op, size_t offset, int len) {
  192. assert(len <= 64);
  193. assert(len >= 4);
  194. assert(offset < 65536);
  195. if ((len < 12) && (offset < 2048)) {
  196. size_t len_minus_4 = len - 4;
  197. assert(len_minus_4 < 8); // Must fit in 3 bits
  198. *op++ = (char)(COPY_1_BYTE_OFFSET + ((len_minus_4) << 2) + ((offset >> 8) << 5));
  199. *op++ = offset & 0xff;
  200. } else {
  201. *op++ = COPY_2_BYTE_OFFSET + ((len-1) << 2);
  202. LittleEndian::Store16(op, (snappy::uint16)offset);
  203. op += 2;
  204. }
  205. return op;
  206. }
  207. static inline char* EmitCopy(char* op, size_t offset, int len) {
  208. // Emit 64 byte copies but make sure to keep at least four bytes reserved
  209. while (len >= 68) {
  210. op = EmitCopyLessThan64(op, offset, 64);
  211. len -= 64;
  212. }
  213. // Emit an extra 60 byte copy if have too much data to fit in one copy
  214. if (len > 64) {
  215. op = EmitCopyLessThan64(op, offset, 60);
  216. len -= 60;
  217. }
  218. // Emit remainder
  219. op = EmitCopyLessThan64(op, offset, len);
  220. return op;
  221. }
  222. bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
  223. uint32 v = 0;
  224. const char* limit = start + n;
  225. if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
  226. *result = v;
  227. return true;
  228. } else {
  229. return false;
  230. }
  231. }
  232. namespace internal {
  233. uint16* WorkingMemory::GetHashTable(size_t input_size, int* table_size) {
  234. // Use smaller hash table when input.size() is smaller, since we
  235. // fill the table, incurring O(hash table size) overhead for
  236. // compression, and if the input is short, we won't need that
  237. // many hash table entries anyway.
  238. assert(kMaxHashTableSize >= 256);
  239. size_t htsize = 256;
  240. while (htsize < kMaxHashTableSize && htsize < input_size) {
  241. htsize <<= 1;
  242. }
  243. uint16* table;
  244. if (htsize <= ARRAYSIZE(small_table_)) {
  245. table = small_table_;
  246. } else {
  247. if (large_table_ == NULL) {
  248. large_table_ = new uint16[kMaxHashTableSize];
  249. }
  250. table = large_table_;
  251. }
  252. *table_size = (int)htsize;
  253. memset(table, 0, htsize * sizeof(*table));
  254. return table;
  255. }
  256. } // end namespace internal
  257. // For 0 <= offset <= 4, GetUint32AtOffset(GetEightBytesAt(p), offset) will
  258. // equal UNALIGNED_LOAD32(p + offset). Motivation: On x86-64 hardware we have
  259. // empirically found that overlapping loads such as
  260. // UNALIGNED_LOAD32(p) ... UNALIGNED_LOAD32(p+1) ... UNALIGNED_LOAD32(p+2)
  261. // are slower than UNALIGNED_LOAD64(p) followed by shifts and casts to uint32.
  262. //
  263. // We have different versions for 64- and 32-bit; ideally we would avoid the
  264. // two functions and just inline the UNALIGNED_LOAD64 call into
  265. // GetUint32AtOffset, but GCC (at least not as of 4.6) is seemingly not clever
  266. // enough to avoid loading the value multiple times then. For 64-bit, the load
  267. // is done when GetEightBytesAt() is called, whereas for 32-bit, the load is
  268. // done at GetUint32AtOffset() time.
  269. #ifdef ARCH_K8
  270. typedef uint64 EightBytesReference;
  271. static inline EightBytesReference GetEightBytesAt(const char* ptr) {
  272. return UNALIGNED_LOAD64(ptr);
  273. }
  274. static inline uint32 GetUint32AtOffset(uint64 v, int offset) {
  275. assert(offset >= 0);
  276. assert(offset <= 4);
  277. return v >> (LittleEndian::IsLittleEndian() ? 8 * offset : 32 - 8 * offset);
  278. }
  279. #else
  280. typedef const char* EightBytesReference;
  281. static inline EightBytesReference GetEightBytesAt(const char* ptr) {
  282. return ptr;
  283. }
  284. static inline uint32 GetUint32AtOffset(const char* v, int offset) {
  285. assert(offset >= 0);
  286. assert(offset <= 4);
  287. return UNALIGNED_LOAD32(v + offset);
  288. }
  289. #endif
  290. // Flat array compression that does not emit the "uncompressed length"
  291. // prefix. Compresses "input" string to the "*op" buffer.
  292. //
  293. // REQUIRES: "input" is at most "kBlockSize" bytes long.
  294. // REQUIRES: "op" points to an array of memory that is at least
  295. // "MaxCompressedLength(input.size())" in size.
  296. // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
  297. // REQUIRES: "table_size" is a power of two
  298. //
  299. // Returns an "end" pointer into "op" buffer.
  300. // "end - op" is the compressed size of "input".
  301. namespace internal {
  302. char* CompressFragment(const char* input,
  303. size_t input_size,
  304. char* op,
  305. uint16* table,
  306. const int table_size) {
  307. // "ip" is the input pointer, and "op" is the output pointer.
  308. const char* ip = input;
  309. assert(input_size <= kBlockSize);
  310. assert((table_size & (table_size - 1)) == 0); // table must be power of two
  311. const int shift = 32 - Bits::Log2Floor(table_size);
  312. assert(static_cast<int>(kuint32max >> shift) == table_size - 1);
  313. const char* ip_end = input + input_size;
  314. const char* base_ip = ip;
  315. // Bytes in [next_emit, ip) will be emitted as literal bytes. Or
  316. // [next_emit, ip_end) after the main loop.
  317. const char* next_emit = ip;
  318. const size_t kInputMarginBytes = 15;
  319. if (PREDICT_TRUE(input_size >= kInputMarginBytes)) {
  320. const char* ip_limit = input + input_size - kInputMarginBytes;
  321. for (uint32 next_hash = Hash(++ip, shift); ; ) {
  322. assert(next_emit < ip);
  323. // The body of this loop calls EmitLiteral once and then EmitCopy one or
  324. // more times. (The exception is that when we're close to exhausting
  325. // the input we goto emit_remainder.)
  326. //
  327. // In the first iteration of this loop we're just starting, so
  328. // there's nothing to copy, so calling EmitLiteral once is
  329. // necessary. And we only start a new iteration when the
  330. // current iteration has determined that a call to EmitLiteral will
  331. // precede the next call to EmitCopy (if any).
  332. //
  333. // Step 1: Scan forward in the input looking for a 4-byte-long match.
  334. // If we get close to exhausting the input then goto emit_remainder.
  335. //
  336. // Heuristic match skipping: If 32 bytes are scanned with no matches
  337. // found, start looking only at every other byte. If 32 more bytes are
  338. // scanned, look at every third byte, etc.. When a match is found,
  339. // immediately go back to looking at every byte. This is a small loss
  340. // (~5% performance, ~0.1% density) for compressible data due to more
  341. // bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  342. // win since the compressor quickly "realizes" the data is incompressible
  343. // and doesn't bother looking for matches everywhere.
  344. //
  345. // The "skip" variable keeps track of how many bytes there are since the
  346. // last match; dividing it by 32 (ie. right-shifting by five) gives the
  347. // number of bytes to move ahead for each iteration.
  348. uint32 skip = 32;
  349. const char* next_ip = ip;
  350. const char* candidate;
  351. do {
  352. ip = next_ip;
  353. uint32 hash = next_hash;
  354. assert(hash == Hash(ip, shift));
  355. uint32 bytes_between_hash_lookups = skip++ >> 5;
  356. next_ip = ip + bytes_between_hash_lookups;
  357. if (PREDICT_FALSE(next_ip > ip_limit)) {
  358. goto emit_remainder;
  359. }
  360. next_hash = Hash(next_ip, shift);
  361. candidate = base_ip + table[hash];
  362. assert(candidate >= base_ip);
  363. assert(candidate < ip);
  364. table[hash] = ip - base_ip;
  365. } while (PREDICT_TRUE(UNALIGNED_LOAD32(ip) !=
  366. UNALIGNED_LOAD32(candidate)));
  367. // Step 2: A 4-byte match has been found. We'll later see if more
  368. // than 4 bytes match. But, prior to the match, input
  369. // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes."
  370. assert(next_emit + 16 <= ip_end);
  371. op = EmitLiteral(op, next_emit, ip - next_emit, true);
  372. // Step 3: Call EmitCopy, and then see if another EmitCopy could
  373. // be our next move. Repeat until we find no match for the
  374. // input immediately after what was consumed by the last EmitCopy call.
  375. //
  376. // If we exit this loop normally then we need to call EmitLiteral next,
  377. // though we don't yet know how big the literal will be. We handle that
  378. // by proceeding to the next iteration of the main loop. We also can exit
  379. // this loop via goto if we get close to exhausting the input.
  380. EightBytesReference input_bytes;
  381. uint32 candidate_bytes = 0;
  382. do {
  383. // We have a 4-byte match at ip, and no need to emit any
  384. // "literal bytes" prior to ip.
  385. const char* base = ip;
  386. int matched = 4 + FindMatchLength(candidate + 4, ip + 4, ip_end);
  387. ip += matched;
  388. size_t offset = base - candidate;
  389. assert(0 == memcmp(base, candidate, matched));
  390. op = EmitCopy(op, offset, matched);
  391. // We could immediately start working at ip now, but to improve
  392. // compression we first update table[Hash(ip - 1, ...)].
  393. const char* insert_tail = ip - 1;
  394. next_emit = ip;
  395. if (PREDICT_FALSE(ip >= ip_limit)) {
  396. goto emit_remainder;
  397. }
  398. input_bytes = GetEightBytesAt(insert_tail);
  399. uint32 prev_hash = HashBytes(GetUint32AtOffset(input_bytes, 0), shift);
  400. table[prev_hash] = ip - base_ip - 1;
  401. uint32 cur_hash = HashBytes(GetUint32AtOffset(input_bytes, 1), shift);
  402. candidate = base_ip + table[cur_hash];
  403. candidate_bytes = UNALIGNED_LOAD32(candidate);
  404. table[cur_hash] = ip - base_ip;
  405. } while (GetUint32AtOffset(input_bytes, 1) == candidate_bytes);
  406. next_hash = HashBytes(GetUint32AtOffset(input_bytes, 2), shift);
  407. ++ip;
  408. }
  409. }
  410. emit_remainder:
  411. // Emit the remaining bytes as a literal
  412. if (next_emit < ip_end) {
  413. op = EmitLiteral(op, next_emit, ip_end - next_emit, false);
  414. }
  415. return op;
  416. }
  417. } // end namespace internal
  418. // Signature of output types needed by decompression code.
  419. // The decompression code is templatized on a type that obeys this
  420. // signature so that we do not pay virtual function call overhead in
  421. // the middle of a tight decompression loop.
  422. //
  423. // class DecompressionWriter {
  424. // public:
  425. // // Called before decompression
  426. // void SetExpectedLength(size_t length);
  427. //
  428. // // Called after decompression
  429. // bool CheckLength() const;
  430. //
  431. // // Called repeatedly during decompression
  432. // bool Append(const char* ip, size_t length);
  433. // bool AppendFromSelf(uint32 offset, size_t length);
  434. //
  435. // // The rules for how TryFastAppend differs from Append are somewhat
  436. // // convoluted:
  437. // //
  438. // // - TryFastAppend is allowed to decline (return false) at any
  439. // // time, for any reason -- just "return false" would be
  440. // // a perfectly legal implementation of TryFastAppend.
  441. // // The intention is for TryFastAppend to allow a fast path
  442. // // in the common case of a small append.
  443. // // - TryFastAppend is allowed to read up to <available> bytes
  444. // // from the input buffer, whereas Append is allowed to read
  445. // // <length>. However, if it returns true, it must leave
  446. // // at least five (kMaximumTagLength) bytes in the input buffer
  447. // // afterwards, so that there is always enough space to read the
  448. // // next tag without checking for a refill.
  449. // // - TryFastAppend must always return decline (return false)
  450. // // if <length> is 61 or more, as in this case the literal length is not
  451. // // decoded fully. In practice, this should not be a big problem,
  452. // // as it is unlikely that one would implement a fast path accepting
  453. // // this much data.
  454. // //
  455. // bool TryFastAppend(const char* ip, size_t available, size_t length);
  456. // };
  457. // -----------------------------------------------------------------------
  458. // Lookup table for decompression code. Generated by ComputeTable() below.
  459. // -----------------------------------------------------------------------
  460. // Mapping from i in range [0,4] to a mask to extract the bottom 8*i bits
  461. static const uint32 wordmask[] = {
  462. 0u, 0xffu, 0xffffu, 0xffffffu, 0xffffffffu
  463. };
  464. // Data stored per entry in lookup table:
  465. // Range Bits-used Description
  466. // ------------------------------------
  467. // 1..64 0..7 Literal/copy length encoded in opcode byte
  468. // 0..7 8..10 Copy offset encoded in opcode byte / 256
  469. // 0..4 11..13 Extra bytes after opcode
  470. //
  471. // We use eight bits for the length even though 7 would have sufficed
  472. // because of efficiency reasons:
  473. // (1) Extracting a byte is faster than a bit-field
  474. // (2) It properly aligns copy offset so we do not need a <<8
  475. static const uint16 char_table[256] = {
  476. 0x0001, 0x0804, 0x1001, 0x2001, 0x0002, 0x0805, 0x1002, 0x2002,
  477. 0x0003, 0x0806, 0x1003, 0x2003, 0x0004, 0x0807, 0x1004, 0x2004,
  478. 0x0005, 0x0808, 0x1005, 0x2005, 0x0006, 0x0809, 0x1006, 0x2006,
  479. 0x0007, 0x080a, 0x1007, 0x2007, 0x0008, 0x080b, 0x1008, 0x2008,
  480. 0x0009, 0x0904, 0x1009, 0x2009, 0x000a, 0x0905, 0x100a, 0x200a,
  481. 0x000b, 0x0906, 0x100b, 0x200b, 0x000c, 0x0907, 0x100c, 0x200c,
  482. 0x000d, 0x0908, 0x100d, 0x200d, 0x000e, 0x0909, 0x100e, 0x200e,
  483. 0x000f, 0x090a, 0x100f, 0x200f, 0x0010, 0x090b, 0x1010, 0x2010,
  484. 0x0011, 0x0a04, 0x1011, 0x2011, 0x0012, 0x0a05, 0x1012, 0x2012,
  485. 0x0013, 0x0a06, 0x1013, 0x2013, 0x0014, 0x0a07, 0x1014, 0x2014,
  486. 0x0015, 0x0a08, 0x1015, 0x2015, 0x0016, 0x0a09, 0x1016, 0x2016,
  487. 0x0017, 0x0a0a, 0x1017, 0x2017, 0x0018, 0x0a0b, 0x1018, 0x2018,
  488. 0x0019, 0x0b04, 0x1019, 0x2019, 0x001a, 0x0b05, 0x101a, 0x201a,
  489. 0x001b, 0x0b06, 0x101b, 0x201b, 0x001c, 0x0b07, 0x101c, 0x201c,
  490. 0x001d, 0x0b08, 0x101d, 0x201d, 0x001e, 0x0b09, 0x101e, 0x201e,
  491. 0x001f, 0x0b0a, 0x101f, 0x201f, 0x0020, 0x0b0b, 0x1020, 0x2020,
  492. 0x0021, 0x0c04, 0x1021, 0x2021, 0x0022, 0x0c05, 0x1022, 0x2022,
  493. 0x0023, 0x0c06, 0x1023, 0x2023, 0x0024, 0x0c07, 0x1024, 0x2024,
  494. 0x0025, 0x0c08, 0x1025, 0x2025, 0x0026, 0x0c09, 0x1026, 0x2026,
  495. 0x0027, 0x0c0a, 0x1027, 0x2027, 0x0028, 0x0c0b, 0x1028, 0x2028,
  496. 0x0029, 0x0d04, 0x1029, 0x2029, 0x002a, 0x0d05, 0x102a, 0x202a,
  497. 0x002b, 0x0d06, 0x102b, 0x202b, 0x002c, 0x0d07, 0x102c, 0x202c,
  498. 0x002d, 0x0d08, 0x102d, 0x202d, 0x002e, 0x0d09, 0x102e, 0x202e,
  499. 0x002f, 0x0d0a, 0x102f, 0x202f, 0x0030, 0x0d0b, 0x1030, 0x2030,
  500. 0x0031, 0x0e04, 0x1031, 0x2031, 0x0032, 0x0e05, 0x1032, 0x2032,
  501. 0x0033, 0x0e06, 0x1033, 0x2033, 0x0034, 0x0e07, 0x1034, 0x2034,
  502. 0x0035, 0x0e08, 0x1035, 0x2035, 0x0036, 0x0e09, 0x1036, 0x2036,
  503. 0x0037, 0x0e0a, 0x1037, 0x2037, 0x0038, 0x0e0b, 0x1038, 0x2038,
  504. 0x0039, 0x0f04, 0x1039, 0x2039, 0x003a, 0x0f05, 0x103a, 0x203a,
  505. 0x003b, 0x0f06, 0x103b, 0x203b, 0x003c, 0x0f07, 0x103c, 0x203c,
  506. 0x0801, 0x0f08, 0x103d, 0x203d, 0x1001, 0x0f09, 0x103e, 0x203e,
  507. 0x1801, 0x0f0a, 0x103f, 0x203f, 0x2001, 0x0f0b, 0x1040, 0x2040
  508. };
  509. // In debug mode, allow optional computation of the table at startup.
  510. // Also, check that the decompression table is correct.
  511. #ifndef NDEBUG
  512. DEFINE_bool(snappy_dump_decompression_table, false,
  513. "If true, we print the decompression table at startup.");
  514. static uint16 MakeEntry(unsigned int extra,
  515. unsigned int len,
  516. unsigned int copy_offset) {
  517. // Check that all of the fields fit within the allocated space
  518. assert(extra == (extra & 0x7)); // At most 3 bits
  519. assert(copy_offset == (copy_offset & 0x7)); // At most 3 bits
  520. assert(len == (len & 0x7f)); // At most 7 bits
  521. return len | (copy_offset << 8) | (extra << 11);
  522. }
  523. static void ComputeTable() {
  524. uint16 dst[256];
  525. // Place invalid entries in all places to detect missing initialization
  526. int assigned = 0;
  527. for (int i = 0; i < 256; i++) {
  528. dst[i] = 0xffff;
  529. }
  530. // Small LITERAL entries. We store (len-1) in the top 6 bits.
  531. for (unsigned int len = 1; len <= 60; len++) {
  532. dst[LITERAL | ((len-1) << 2)] = MakeEntry(0, len, 0);
  533. assigned++;
  534. }
  535. // Large LITERAL entries. We use 60..63 in the high 6 bits to
  536. // encode the number of bytes of length info that follow the opcode.
  537. for (unsigned int extra_bytes = 1; extra_bytes <= 4; extra_bytes++) {
  538. // We set the length field in the lookup table to 1 because extra
  539. // bytes encode len-1.
  540. dst[LITERAL | ((extra_bytes+59) << 2)] = MakeEntry(extra_bytes, 1, 0);
  541. assigned++;
  542. }
  543. // COPY_1_BYTE_OFFSET.
  544. //
  545. // The tag byte in the compressed data stores len-4 in 3 bits, and
  546. // offset/256 in 5 bits. offset%256 is stored in the next byte.
  547. //
  548. // This format is used for length in range [4..11] and offset in
  549. // range [0..2047]
  550. for (unsigned int len = 4; len < 12; len++) {
  551. for (unsigned int offset = 0; offset < 2048; offset += 256) {
  552. dst[COPY_1_BYTE_OFFSET | ((len-4)<<2) | ((offset>>8)<<5)] =
  553. MakeEntry(1, len, offset>>8);
  554. assigned++;
  555. }
  556. }
  557. // COPY_2_BYTE_OFFSET.
  558. // Tag contains len-1 in top 6 bits, and offset in next two bytes.
  559. for (unsigned int len = 1; len <= 64; len++) {
  560. dst[COPY_2_BYTE_OFFSET | ((len-1)<<2)] = MakeEntry(2, len, 0);
  561. assigned++;
  562. }
  563. // COPY_4_BYTE_OFFSET.
  564. // Tag contents len-1 in top 6 bits, and offset in next four bytes.
  565. for (unsigned int len = 1; len <= 64; len++) {
  566. dst[COPY_4_BYTE_OFFSET | ((len-1)<<2)] = MakeEntry(4, len, 0);
  567. assigned++;
  568. }
  569. // Check that each entry was initialized exactly once.
  570. if (assigned != 256) {
  571. fprintf(stderr, "ComputeTable: assigned only %d of 256\n", assigned);
  572. abort();
  573. }
  574. for (int i = 0; i < 256; i++) {
  575. if (dst[i] == 0xffff) {
  576. fprintf(stderr, "ComputeTable: did not assign byte %d\n", i);
  577. abort();
  578. }
  579. }
  580. if (FLAGS_snappy_dump_decompression_table) {
  581. printf("static const uint16 char_table[256] = {\n ");
  582. for (int i = 0; i < 256; i++) {
  583. printf("0x%04x%s",
  584. dst[i],
  585. ((i == 255) ? "\n" : (((i%8) == 7) ? ",\n " : ", ")));
  586. }
  587. printf("};\n");
  588. }
  589. // Check that computed table matched recorded table
  590. for (int i = 0; i < 256; i++) {
  591. if (dst[i] != char_table[i]) {
  592. fprintf(stderr, "ComputeTable: byte %d: computed (%x), expect (%x)\n",
  593. i, static_cast<int>(dst[i]), static_cast<int>(char_table[i]));
  594. abort();
  595. }
  596. }
  597. }
  598. #endif /* !NDEBUG */
  599. // Helper class for decompression
  600. class SnappyDecompressor {
  601. private:
  602. Source* reader_; // Underlying source of bytes to decompress
  603. const char* ip_; // Points to next buffered byte
  604. const char* ip_limit_; // Points just past buffered bytes
  605. uint32 peeked_; // Bytes peeked from reader (need to skip)
  606. bool eof_; // Hit end of input without an error?
  607. char scratch_[kMaximumTagLength]; // See RefillTag().
  608. // Ensure that all of the tag metadata for the next tag is available
  609. // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even
  610. // if (ip_limit_ - ip_ < 5).
  611. //
  612. // Returns true on success, false on error or end of input.
  613. bool RefillTag();
  614. public:
  615. explicit SnappyDecompressor(Source* reader)
  616. : reader_(reader),
  617. ip_(NULL),
  618. ip_limit_(NULL),
  619. peeked_(0),
  620. eof_(false) {
  621. }
  622. ~SnappyDecompressor() {
  623. // Advance past any bytes we peeked at from the reader
  624. reader_->Skip(peeked_);
  625. }
  626. // Returns true iff we have hit the end of the input without an error.
  627. bool eof() const {
  628. return eof_;
  629. }
  630. // Read the uncompressed length stored at the start of the compressed data.
  631. // On succcess, stores the length in *result and returns true.
  632. // On failure, returns false.
  633. bool ReadUncompressedLength(uint32* result) {
  634. assert(ip_ == NULL); // Must not have read anything yet
  635. // Length is encoded in 1..5 bytes
  636. *result = 0;
  637. uint32 shift = 0;
  638. while (true) {
  639. if (shift >= 32) return false;
  640. size_t n;
  641. const char* ip = reader_->Peek(&n);
  642. if (n == 0) return false;
  643. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  644. reader_->Skip(1);
  645. *result |= static_cast<uint32>(c & 0x7f) << shift;
  646. if (c < 128) {
  647. break;
  648. }
  649. shift += 7;
  650. }
  651. return true;
  652. }
  653. // Process the next item found in the input.
  654. // Returns true if successful, false on error or end of input.
  655. template <class Writer>
  656. void DecompressAllTags(Writer* writer) {
  657. const char* ip = ip_;
  658. // We could have put this refill fragment only at the beginning of the loop.
  659. // However, duplicating it at the end of each branch gives the compiler more
  660. // scope to optimize the <ip_limit_ - ip> expression based on the local
  661. // context, which overall increases speed.
  662. #define MAYBE_REFILL() \
  663. if (ip_limit_ - ip < kMaximumTagLength) { \
  664. ip_ = ip; \
  665. if (!RefillTag()) return; \
  666. ip = ip_; \
  667. }
  668. MAYBE_REFILL();
  669. for ( ;; ) {
  670. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip++));
  671. if ((c & 0x3) == LITERAL) {
  672. size_t literal_length = (c >> 2) + 1u;
  673. if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length)) {
  674. assert(literal_length < 61);
  675. ip += literal_length;
  676. // NOTE(user): There is no MAYBE_REFILL() here, as TryFastAppend()
  677. // will not return true unless there's already at least five spare
  678. // bytes in addition to the literal.
  679. continue;
  680. }
  681. if (PREDICT_FALSE(literal_length >= 61)) {
  682. // Long literal.
  683. const size_t literal_length_length = literal_length - 60;
  684. literal_length =
  685. (LittleEndian::Load32(ip) & wordmask[literal_length_length]) + 1;
  686. ip += literal_length_length;
  687. }
  688. size_t avail = ip_limit_ - ip;
  689. while (avail < literal_length) {
  690. if (!writer->Append(ip, avail)) return;
  691. literal_length -= avail;
  692. reader_->Skip(peeked_);
  693. size_t n;
  694. ip = reader_->Peek(&n);
  695. avail = n;
  696. peeked_ = (snappy::uint32)avail;
  697. if (avail == 0) return; // Premature end of input
  698. ip_limit_ = ip + avail;
  699. }
  700. if (!writer->Append(ip, literal_length)) {
  701. return;
  702. }
  703. ip += literal_length;
  704. MAYBE_REFILL();
  705. } else {
  706. const uint32 entry = char_table[c];
  707. const uint32 trailer = LittleEndian::Load32(ip) & wordmask[entry >> 11];
  708. const uint32 length = entry & 0xff;
  709. ip += entry >> 11;
  710. // copy_offset/256 is encoded in bits 8..10. By just fetching
  711. // those bits, we get copy_offset (since the bit-field starts at
  712. // bit 8).
  713. const uint32 copy_offset = entry & 0x700;
  714. if (!writer->AppendFromSelf(copy_offset + trailer, length)) {
  715. return;
  716. }
  717. MAYBE_REFILL();
  718. }
  719. }
  720. #undef MAYBE_REFILL
  721. }
  722. };
  723. bool SnappyDecompressor::RefillTag() {
  724. const char* ip = ip_;
  725. if (ip == ip_limit_) {
  726. // Fetch a new fragment from the reader
  727. reader_->Skip(peeked_); // All peeked bytes are used up
  728. size_t n;
  729. ip = reader_->Peek(&n);
  730. peeked_ = (snappy::uint32)n;
  731. if (n == 0) {
  732. eof_ = true;
  733. return false;
  734. }
  735. ip_limit_ = ip + n;
  736. }
  737. // Read the tag character
  738. assert(ip < ip_limit_);
  739. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  740. const uint32 entry = char_table[c];
  741. const uint32 needed = (entry >> 11) + 1; // +1 byte for 'c'
  742. assert(needed <= sizeof(scratch_));
  743. // Read more bytes from reader if needed
  744. uint32 nbuf = ip_limit_ - ip;
  745. if (nbuf < needed) {
  746. // Stitch together bytes from ip and reader to form the word
  747. // contents. We store the needed bytes in "scratch_". They
  748. // will be consumed immediately by the caller since we do not
  749. // read more than we need.
  750. memmove(scratch_, ip, nbuf);
  751. reader_->Skip(peeked_); // All peeked bytes are used up
  752. peeked_ = 0;
  753. while (nbuf < needed) {
  754. size_t length;
  755. const char* src = reader_->Peek(&length);
  756. if (length == 0) return false;
  757. uint32 to_add = Min(needed - nbuf, (uint32)length);
  758. memcpy(scratch_ + nbuf, src, to_add);
  759. nbuf += to_add;
  760. reader_->Skip(to_add);
  761. }
  762. assert(nbuf == needed);
  763. ip_ = scratch_;
  764. ip_limit_ = scratch_ + needed;
  765. } else if (nbuf < kMaximumTagLength) {
  766. // Have enough bytes, but move into scratch_ so that we do not
  767. // read past end of input
  768. memmove(scratch_, ip, nbuf);
  769. reader_->Skip(peeked_); // All peeked bytes are used up
  770. peeked_ = 0;
  771. ip_ = scratch_;
  772. ip_limit_ = scratch_ + nbuf;
  773. } else {
  774. // Pass pointer to buffer returned by reader_.
  775. ip_ = ip;
  776. }
  777. return true;
  778. }
  779. template <typename Writer>
  780. static bool InternalUncompress(Source* r, Writer* writer) {
  781. // Read the uncompressed length from the front of the compressed input
  782. SnappyDecompressor decompressor(r);
  783. uint32 uncompressed_len = 0;
  784. if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
  785. return InternalUncompressAllTags(&decompressor, writer, uncompressed_len);
  786. }
  787. template <typename Writer>
  788. static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
  789. Writer* writer,
  790. uint32 uncompressed_len) {
  791. writer->SetExpectedLength(uncompressed_len);
  792. // Process the entire input
  793. decompressor->DecompressAllTags(writer);
  794. return (decompressor->eof() && writer->CheckLength());
  795. }
  796. bool GetUncompressedLength(Source* source, uint32* result) {
  797. SnappyDecompressor decompressor(source);
  798. return decompressor.ReadUncompressedLength(result);
  799. }
  800. size_t Compress(Source* reader, Sink* writer) {
  801. size_t written = 0;
  802. size_t N = reader->Available();
  803. char ulength[Varint::kMax32];
  804. char* p = Varint::Encode32(ulength, (snappy::uint32)N);
  805. writer->Append(ulength, p-ulength);
  806. written += (p - ulength);
  807. internal::WorkingMemory wmem;
  808. char* scratch = NULL;
  809. char* scratch_output = NULL;
  810. while (N > 0) {
  811. // Get next block to compress (without copying if possible)
  812. size_t fragment_size;
  813. const char* fragment = reader->Peek(&fragment_size);
  814. assert(fragment_size != 0); // premature end of input
  815. const size_t num_to_read = min(N, kBlockSize);
  816. size_t bytes_read = fragment_size;
  817. size_t pending_advance = 0;
  818. if (bytes_read >= num_to_read) {
  819. // Buffer returned by reader is large enough
  820. pending_advance = num_to_read;
  821. fragment_size = num_to_read;
  822. } else {
  823. // Read into scratch buffer
  824. if (scratch == NULL) {
  825. // If this is the last iteration, we want to allocate N bytes
  826. // of space, otherwise the max possible kBlockSize space.
  827. // num_to_read contains exactly the correct value
  828. scratch = new char[num_to_read];
  829. }
  830. memcpy(scratch, fragment, bytes_read);
  831. reader->Skip(bytes_read);
  832. while (bytes_read < num_to_read) {
  833. fragment = reader->Peek(&fragment_size);
  834. size_t n = Min(fragment_size, num_to_read - bytes_read);
  835. memcpy(scratch + bytes_read, fragment, n);
  836. bytes_read += n;
  837. reader->Skip(n);
  838. }
  839. assert(bytes_read == num_to_read);
  840. fragment = scratch;
  841. fragment_size = num_to_read;
  842. }
  843. assert(fragment_size == num_to_read);
  844. // Get encoding table for compression
  845. int table_size;
  846. uint16* table = wmem.GetHashTable(num_to_read, &table_size);
  847. // Compress input_fragment and append to dest
  848. const int max_output = (int)MaxCompressedLength(num_to_read);
  849. // Need a scratch buffer for the output, in case the byte sink doesn't
  850. // have room for us directly.
  851. if (scratch_output == NULL) {
  852. scratch_output = new char[max_output];
  853. } else {
  854. // Since we encode kBlockSize regions followed by a region
  855. // which is <= kBlockSize in length, a previously allocated
  856. // scratch_output[] region is big enough for this iteration.
  857. }
  858. char* dest = writer->GetAppendBuffer(max_output, scratch_output);
  859. char* end = internal::CompressFragment(fragment, fragment_size,
  860. dest, table, table_size);
  861. writer->Append(dest, end - dest);
  862. written += (end - dest);
  863. N -= num_to_read;
  864. reader->Skip(pending_advance);
  865. }
  866. delete[] scratch;
  867. delete[] scratch_output;
  868. return written;
  869. }
  870. // -----------------------------------------------------------------------
  871. // IOVec interfaces
  872. // -----------------------------------------------------------------------
  873. // A type that writes to an iovec.
  874. // Note that this is not a "ByteSink", but a type that matches the
  875. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  876. class SnappyIOVecWriter {
  877. private:
  878. const struct iovec* output_iov_;
  879. const size_t output_iov_count_;
  880. // We are currently writing into output_iov_[curr_iov_index_].
  881. int curr_iov_index_;
  882. // Bytes written to output_iov_[curr_iov_index_] so far.
  883. size_t curr_iov_written_;
  884. // Total bytes decompressed into output_iov_ so far.
  885. size_t total_written_;
  886. // Maximum number of bytes that will be decompressed into output_iov_.
  887. size_t output_limit_;
  888. inline char* GetIOVecPointer(int index, size_t offset) {
  889. return reinterpret_cast<char*>(output_iov_[index].iov_base) +
  890. offset;
  891. }
  892. public:
  893. // Does not take ownership of iov. iov must be valid during the
  894. // entire lifetime of the SnappyIOVecWriter.
  895. inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count)
  896. : output_iov_(iov),
  897. output_iov_count_(iov_count),
  898. curr_iov_index_(0),
  899. curr_iov_written_(0),
  900. total_written_(0),
  901. output_limit_((size_t)-1) {
  902. }
  903. inline void SetExpectedLength(size_t len) {
  904. output_limit_ = len;
  905. }
  906. inline bool CheckLength() const {
  907. return total_written_ == output_limit_;
  908. }
  909. inline bool Append(const char* ip, size_t len) {
  910. if (total_written_ + len > output_limit_) {
  911. return false;
  912. }
  913. while (len > 0) {
  914. assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len);
  915. if (curr_iov_written_ >= output_iov_[curr_iov_index_].iov_len) {
  916. // This iovec is full. Go to the next one.
  917. if (curr_iov_index_ + 1 >= output_iov_count_) {
  918. return false;
  919. }
  920. curr_iov_written_ = 0;
  921. ++curr_iov_index_;
  922. }
  923. const size_t to_write = Min(
  924. len, output_iov_[curr_iov_index_].iov_len - curr_iov_written_);
  925. memcpy(GetIOVecPointer(curr_iov_index_, curr_iov_written_),
  926. ip,
  927. to_write);
  928. curr_iov_written_ += to_write;
  929. total_written_ += to_write;
  930. ip += to_write;
  931. len -= to_write;
  932. }
  933. return true;
  934. }
  935. inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
  936. const size_t space_left = output_limit_ - total_written_;
  937. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
  938. output_iov_[curr_iov_index_].iov_len - curr_iov_written_ >= 16) {
  939. // Fast path, used for the majority (about 95%) of invocations.
  940. char* ptr = GetIOVecPointer(curr_iov_index_, curr_iov_written_);
  941. UnalignedCopy64(ip, ptr);
  942. UnalignedCopy64(ip + 8, ptr + 8);
  943. curr_iov_written_ += len;
  944. total_written_ += len;
  945. return true;
  946. }
  947. return false;
  948. }
  949. inline bool AppendFromSelf(size_t offset, size_t len) {
  950. if (offset > total_written_ || offset == 0) {
  951. return false;
  952. }
  953. const size_t space_left = output_limit_ - total_written_;
  954. if (len > space_left) {
  955. return false;
  956. }
  957. // Locate the iovec from which we need to start the copy.
  958. int from_iov_index = curr_iov_index_;
  959. size_t from_iov_offset = curr_iov_written_;
  960. while (offset > 0) {
  961. if (from_iov_offset >= offset) {
  962. from_iov_offset -= offset;
  963. break;
  964. }
  965. offset -= from_iov_offset;
  966. --from_iov_index;
  967. assert(from_iov_index >= 0);
  968. from_iov_offset = output_iov_[from_iov_index].iov_len;
  969. }
  970. // Copy <len> bytes starting from the iovec pointed to by from_iov_index to
  971. // the current iovec.
  972. while (len > 0) {
  973. assert(from_iov_index <= curr_iov_index_);
  974. if (from_iov_index != curr_iov_index_) {
  975. const size_t to_copy = Min(
  976. output_iov_[from_iov_index].iov_len - from_iov_offset,
  977. len);
  978. Append(GetIOVecPointer(from_iov_index, from_iov_offset), to_copy);
  979. len -= to_copy;
  980. if (len > 0) {
  981. ++from_iov_index;
  982. from_iov_offset = 0;
  983. }
  984. } else {
  985. assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len);
  986. size_t to_copy = Min(output_iov_[curr_iov_index_].iov_len -
  987. curr_iov_written_,
  988. len);
  989. if (to_copy == 0) {
  990. // This iovec is full. Go to the next one.
  991. if (curr_iov_index_ + 1 >= output_iov_count_) {
  992. return false;
  993. }
  994. ++curr_iov_index_;
  995. curr_iov_written_ = 0;
  996. continue;
  997. }
  998. if (to_copy > len) {
  999. to_copy = len;
  1000. }
  1001. IncrementalCopy(GetIOVecPointer(from_iov_index, from_iov_offset),
  1002. GetIOVecPointer(curr_iov_index_, curr_iov_written_),
  1003. to_copy);
  1004. curr_iov_written_ += to_copy;
  1005. from_iov_offset += to_copy;
  1006. total_written_ += to_copy;
  1007. len -= to_copy;
  1008. }
  1009. }
  1010. return true;
  1011. }
  1012. };
  1013. bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
  1014. const struct iovec* iov, size_t iov_cnt) {
  1015. ByteArraySource reader(compressed, compressed_length);
  1016. return RawUncompressToIOVec(&reader, iov, iov_cnt);
  1017. }
  1018. bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
  1019. size_t iov_cnt) {
  1020. SnappyIOVecWriter output(iov, iov_cnt);
  1021. return InternalUncompress(compressed, &output);
  1022. }
  1023. // -----------------------------------------------------------------------
  1024. // Flat array interfaces
  1025. // -----------------------------------------------------------------------
  1026. // A type that writes to a flat array.
  1027. // Note that this is not a "ByteSink", but a type that matches the
  1028. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  1029. class SnappyArrayWriter {
  1030. private:
  1031. char* base_;
  1032. char* op_;
  1033. char* op_limit_;
  1034. public:
  1035. inline explicit SnappyArrayWriter(char* dst)
  1036. : base_(dst),
  1037. op_(dst) {
  1038. }
  1039. inline void SetExpectedLength(size_t len) {
  1040. op_limit_ = op_ + len;
  1041. }
  1042. inline bool CheckLength() const {
  1043. return op_ == op_limit_;
  1044. }
  1045. inline bool Append(const char* ip, size_t len) {
  1046. char* op = op_;
  1047. const size_t space_left = op_limit_ - op;
  1048. if (space_left < len) {
  1049. return false;
  1050. }
  1051. memcpy(op, ip, len);
  1052. op_ = op + len;
  1053. return true;
  1054. }
  1055. inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
  1056. char* op = op_;
  1057. const size_t space_left = op_limit_ - op;
  1058. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
  1059. // Fast path, used for the majority (about 95%) of invocations.
  1060. UnalignedCopy64(ip, op);
  1061. UnalignedCopy64(ip + 8, op + 8);
  1062. op_ = op + len;
  1063. return true;
  1064. } else {
  1065. return false;
  1066. }
  1067. }
  1068. inline bool AppendFromSelf(size_t offset, size_t len) {
  1069. char* op = op_;
  1070. const size_t space_left = op_limit_ - op;
  1071. // Check if we try to append from before the start of the buffer.
  1072. // Normally this would just be a check for "produced < offset",
  1073. // but "produced <= offset - 1u" is equivalent for every case
  1074. // except the one where offset==0, where the right side will wrap around
  1075. // to a very big number. This is convenient, as offset==0 is another
  1076. // invalid case that we also want to catch, so that we do not go
  1077. // into an infinite loop.
  1078. assert(op >= base_);
  1079. size_t produced = op - base_;
  1080. if (produced <= offset - 1u) {
  1081. return false;
  1082. }
  1083. if (len <= 16 && offset >= 8 && space_left >= 16) {
  1084. // Fast path, used for the majority (70-80%) of dynamic invocations.
  1085. UnalignedCopy64(op - offset, op);
  1086. UnalignedCopy64(op - offset + 8, op + 8);
  1087. } else {
  1088. if (space_left >= len + kMaxIncrementCopyOverflow) {
  1089. IncrementalCopyFastPath(op - offset, op, len);
  1090. } else {
  1091. if (space_left < len) {
  1092. return false;
  1093. }
  1094. IncrementalCopy(op - offset, op, len);
  1095. }
  1096. }
  1097. op_ = op + len;
  1098. return true;
  1099. }
  1100. };
  1101. bool RawUncompress(const char* compressed, size_t n, char* uncompressed) {
  1102. ByteArraySource reader(compressed, n);
  1103. return RawUncompress(&reader, uncompressed);
  1104. }
  1105. bool RawUncompress(Source* compressed, char* uncompressed) {
  1106. SnappyArrayWriter output(uncompressed);
  1107. return InternalUncompress(compressed, &output);
  1108. }
  1109. bool Uncompress(const char* compressed, size_t n, string* uncompressed) {
  1110. size_t ulength;
  1111. if (!GetUncompressedLength(compressed, n, &ulength)) {
  1112. return false;
  1113. }
  1114. // On 32-bit builds: max_size() < kuint32max. Check for that instead
  1115. // of crashing (e.g., consider externally specified compressed data).
  1116. if (ulength > uncompressed->max_size()) {
  1117. return false;
  1118. }
  1119. STLStringResizeUninitialized(uncompressed, ulength);
  1120. return RawUncompress(compressed, n, string_as_array(uncompressed));
  1121. }
  1122. // A Writer that drops everything on the floor and just does validation
  1123. class SnappyDecompressionValidator {
  1124. private:
  1125. size_t expected_;
  1126. size_t produced_;
  1127. public:
  1128. inline SnappyDecompressionValidator() : produced_(0) { }
  1129. inline void SetExpectedLength(size_t len) {
  1130. expected_ = len;
  1131. }
  1132. inline bool CheckLength() const {
  1133. return expected_ == produced_;
  1134. }
  1135. inline bool Append(const char* ip, size_t len) {
  1136. produced_ += len;
  1137. return produced_ <= expected_;
  1138. }
  1139. inline bool TryFastAppend(const char* ip, size_t available, size_t length) {
  1140. return false;
  1141. }
  1142. inline bool AppendFromSelf(size_t offset, size_t len) {
  1143. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1144. // the "offset - 1u" trick.
  1145. if (produced_ <= offset - 1u) return false;
  1146. produced_ += len;
  1147. return produced_ <= expected_;
  1148. }
  1149. };
  1150. bool IsValidCompressedBuffer(const char* compressed, size_t n) {
  1151. ByteArraySource reader(compressed, n);
  1152. SnappyDecompressionValidator writer;
  1153. return InternalUncompress(&reader, &writer);
  1154. }
  1155. void RawCompress(const char* input,
  1156. size_t input_length,
  1157. char* compressed,
  1158. size_t* compressed_length) {
  1159. ByteArraySource reader(input, input_length);
  1160. UncheckedByteArraySink writer(compressed);
  1161. Compress(&reader, &writer);
  1162. // Compute how many bytes were added
  1163. *compressed_length = (writer.CurrentDestination() - compressed);
  1164. }
  1165. size_t Compress(const char* input, size_t input_length, string* compressed) {
  1166. // Pre-grow the buffer to the max length of the compressed output
  1167. compressed->resize(MaxCompressedLength(input_length));
  1168. size_t compressed_length;
  1169. RawCompress(input, input_length, string_as_array(compressed),
  1170. &compressed_length);
  1171. compressed->resize(compressed_length);
  1172. return compressed_length;
  1173. }
  1174. } // end namespace snappy