snappy.cc 45 KB

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