snappy.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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. #ifndef SNAPPY_HAVE_SSE2
  32. #if defined(__SSE2__) || defined(_M_X64) || \
  33. (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
  34. #define SNAPPY_HAVE_SSE2 1
  35. #else
  36. #define SNAPPY_HAVE_SSE2 0
  37. #endif
  38. #endif
  39. #if SNAPPY_HAVE_SSE2
  40. #include <emmintrin.h>
  41. #endif
  42. #include <stdio.h>
  43. #include <algorithm>
  44. //#include <string>
  45. //#include <vector>
  46. namespace snappy {
  47. using internal::COPY_1_BYTE_OFFSET;
  48. using internal::COPY_2_BYTE_OFFSET;
  49. using internal::LITERAL;
  50. using internal::char_table;
  51. using internal::kMaximumTagLength;
  52. // Any hash function will produce a valid compressed bitstream, but a good
  53. // hash function reduces the number of collisions and thus yields better
  54. // compression for compressible input, and more speed for incompressible
  55. // input. Of course, it doesn't hurt if the hash function is reasonably fast
  56. // either, as it gets called a lot.
  57. static inline uint32 HashBytes(uint32 bytes, int shift) {
  58. uint32 kMul = 0x1e35a7bd;
  59. return (bytes * kMul) >> shift;
  60. }
  61. static inline uint32 Hash(const char* p, int shift) {
  62. return HashBytes(UNALIGNED_LOAD32(p), shift);
  63. }
  64. size_t MaxCompressedLength(size_t source_len) {
  65. // Compressed data can be defined as:
  66. // compressed := item* literal*
  67. // item := literal* copy
  68. //
  69. // The trailing literal sequence has a space blowup of at most 62/60
  70. // since a literal of length 60 needs one tag byte + one extra byte
  71. // for length information.
  72. //
  73. // Item blowup is trickier to measure. Suppose the "copy" op copies
  74. // 4 bytes of data. Because of a special check in the encoding code,
  75. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  76. // the copy op takes 3 bytes to encode, and this type of item leads
  77. // to at most the 62/60 blowup for representing literals.
  78. //
  79. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  80. // enough, it will take 5 bytes to encode the copy op. Therefore the
  81. // worst case here is a one-byte literal followed by a five-byte copy.
  82. // I.e., 6 bytes of input turn into 7 bytes of "compressed" data.
  83. //
  84. // This last factor dominates the blowup, so the final estimate is:
  85. return 32 + source_len + source_len/6;
  86. }
  87. namespace {
  88. void UnalignedCopy64(const void* src, void* dst) {
  89. char tmp[8];
  90. memcpy(tmp, src, 8);
  91. memcpy(dst, tmp, 8);
  92. }
  93. void UnalignedCopy128(const void* src, void* dst) {
  94. // TODO(alkis): Remove this when we upgrade to a recent compiler that emits
  95. // SSE2 moves for memcpy(dst, src, 16).
  96. #if SNAPPY_HAVE_SSE2
  97. __m128i x = _mm_loadu_si128(static_cast<const __m128i*>(src));
  98. _mm_storeu_si128(static_cast<__m128i*>(dst), x);
  99. #else
  100. char tmp[16];
  101. memcpy(tmp, src, 16);
  102. memcpy(dst, tmp, 16);
  103. #endif
  104. }
  105. // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used
  106. // for handling COPY operations where the input and output regions may overlap.
  107. // For example, suppose:
  108. // src == "ab"
  109. // op == src + 2
  110. // op_limit == op + 20
  111. // After IncrementalCopySlow(src, op, op_limit), the result will have eleven
  112. // copies of "ab"
  113. // ababababababababababab
  114. // Note that this does not match the semantics of either memcpy() or memmove().
  115. inline char* IncrementalCopySlow(const char* src, char* op,
  116. char* const op_limit) {
  117. while (op < op_limit) {
  118. *op++ = *src++;
  119. }
  120. return op_limit;
  121. }
  122. // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) but faster than
  123. // IncrementalCopySlow. buf_limit is the address past the end of the writable
  124. // region of the buffer.
  125. inline char* IncrementalCopy(const char* src, char* op, char* const op_limit,
  126. char* const buf_limit) {
  127. // Terminology:
  128. //
  129. // slop = buf_limit - op
  130. // pat = op - src
  131. // len = limit - op
  132. assert(src < op);
  133. assert(op_limit <= buf_limit);
  134. // NOTE: The compressor always emits 4 <= len <= 64. It is ok to assume that
  135. // to optimize this function but we have to also handle these cases in case
  136. // the input does not satisfy these conditions.
  137. size_t pattern_size = op - src;
  138. // The cases are split into different branches to allow the branch predictor,
  139. // FDO, and static prediction hints to work better. For each input we list the
  140. // ratio of invocations that match each condition.
  141. //
  142. // input slop < 16 pat < 8 len > 16
  143. // ------------------------------------------
  144. // html|html4|cp 0% 1.01% 27.73%
  145. // urls 0% 0.88% 14.79%
  146. // jpg 0% 64.29% 7.14%
  147. // pdf 0% 2.56% 58.06%
  148. // txt[1-4] 0% 0.23% 0.97%
  149. // pb 0% 0.96% 13.88%
  150. // bin 0.01% 22.27% 41.17%
  151. //
  152. // It is very rare that we don't have enough slop for doing block copies. It
  153. // is also rare that we need to expand a pattern. Small patterns are common
  154. // for incompressible formats and for those we are plenty fast already.
  155. // Lengths are normally not greater than 16 but they vary depending on the
  156. // input. In general if we always predict len <= 16 it would be an ok
  157. // prediction.
  158. //
  159. // In order to be fast we want a pattern >= 8 bytes and an unrolled loop
  160. // copying 2x 8 bytes at a time.
  161. // Handle the uncommon case where pattern is less than 8 bytes.
  162. if (PREDICT_FALSE(pattern_size < 8)) {
  163. // Expand pattern to at least 8 bytes. The worse case scenario in terms of
  164. // buffer usage is when the pattern is size 3. ^ is the original position
  165. // of op. x are irrelevant bytes copied by the last UnalignedCopy64.
  166. //
  167. // abc
  168. // abcabcxxxxx
  169. // abcabcabcabcxxxxx
  170. // ^
  171. // The last x is 14 bytes after ^.
  172. if (PREDICT_TRUE(op <= buf_limit - 14)) {
  173. while (pattern_size < 8) {
  174. UnalignedCopy64(src, op);
  175. op += pattern_size;
  176. pattern_size *= 2;
  177. }
  178. if (PREDICT_TRUE(op >= op_limit)) return op_limit;
  179. } else {
  180. return IncrementalCopySlow(src, op, op_limit);
  181. }
  182. }
  183. assert(pattern_size >= 8);
  184. // Copy 2x 8 bytes at a time. Because op - src can be < 16, a single
  185. // UnalignedCopy128 might overwrite data in op. UnalignedCopy64 is safe
  186. // because expanding the pattern to at least 8 bytes guarantees that
  187. // op - src >= 8.
  188. while (op <= buf_limit - 16) {
  189. UnalignedCopy64(src, op);
  190. UnalignedCopy64(src + 8, op + 8);
  191. src += 16;
  192. op += 16;
  193. if (PREDICT_TRUE(op >= op_limit)) return op_limit;
  194. }
  195. // We only take this branch if we didn't have enough slop and we can do a
  196. // single 8 byte copy.
  197. if (PREDICT_FALSE(op <= buf_limit - 8)) {
  198. UnalignedCopy64(src, op);
  199. src += 8;
  200. op += 8;
  201. }
  202. return IncrementalCopySlow(src, op, op_limit);
  203. }
  204. } // namespace
  205. static inline char* EmitLiteral(char* op,
  206. const char* literal,
  207. int len,
  208. bool allow_fast_path) {
  209. // The vast majority of copies are below 16 bytes, for which a
  210. // call to memcpy is overkill. This fast path can sometimes
  211. // copy up to 15 bytes too much, but that is okay in the
  212. // main loop, since we have a bit to go on for both sides:
  213. //
  214. // - The input will always have kInputMarginBytes = 15 extra
  215. // available bytes, as long as we're in the main loop, and
  216. // if not, allow_fast_path = false.
  217. // - The output will always have 32 spare bytes (see
  218. // MaxCompressedLength).
  219. assert(len > 0); // Zero-length literals are disallowed
  220. int n = len - 1;
  221. if (allow_fast_path && len <= 16) {
  222. // Fits in tag byte
  223. *op++ = LITERAL | (n << 2);
  224. UnalignedCopy128(literal, op);
  225. return op + len;
  226. }
  227. if (n < 60) {
  228. // Fits in tag byte
  229. *op++ = LITERAL | (n << 2);
  230. } else {
  231. // Encode in upcoming bytes
  232. char* base = op;
  233. int count = 0;
  234. op++;
  235. while (n > 0) {
  236. *op++ = n & 0xff;
  237. n >>= 8;
  238. count++;
  239. }
  240. assert(count >= 1);
  241. assert(count <= 4);
  242. *base = LITERAL | ((59+count) << 2);
  243. }
  244. memcpy(op, literal, len);
  245. return op + len;
  246. }
  247. static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len,
  248. bool len_less_than_12) {
  249. assert(len <= 64);
  250. assert(len >= 4);
  251. assert(offset < 65536);
  252. assert(len_less_than_12 == (len < 12));
  253. if (len_less_than_12 && PREDICT_TRUE(offset < 2048)) {
  254. // offset fits in 11 bits. The 3 highest go in the top of the first byte,
  255. // and the rest go in the second byte.
  256. *op++ = COPY_1_BYTE_OFFSET + ((len - 4) << 2) + ((offset >> 3) & 0xe0);
  257. *op++ = offset & 0xff;
  258. } else {
  259. // Write 4 bytes, though we only care about 3 of them. The output buffer
  260. // is required to have some slack, so the extra byte won't overrun it.
  261. uint32 u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
  262. LittleEndian::Store32(op, u);
  263. op += 3;
  264. }
  265. return op;
  266. }
  267. static inline char* EmitCopy(char* op, size_t offset, size_t len,
  268. bool len_less_than_12) {
  269. assert(len_less_than_12 == (len < 12));
  270. if (len_less_than_12) {
  271. return EmitCopyAtMost64(op, offset, len, true);
  272. } else {
  273. // A special case for len <= 64 might help, but so far measurements suggest
  274. // it's in the noise.
  275. // Emit 64 byte copies but make sure to keep at least four bytes reserved.
  276. while (PREDICT_FALSE(len >= 68)) {
  277. op = EmitCopyAtMost64(op, offset, 64, false);
  278. len -= 64;
  279. }
  280. // One or two copies will now finish the job.
  281. if (len > 64) {
  282. op = EmitCopyAtMost64(op, offset, 60, false);
  283. len -= 60;
  284. }
  285. // Emit remainder.
  286. op = EmitCopyAtMost64(op, offset, len, len < 12);
  287. return op;
  288. }
  289. }
  290. bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
  291. uint32 v = 0;
  292. const char* limit = start + n;
  293. if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
  294. *result = v;
  295. return true;
  296. } else {
  297. return false;
  298. }
  299. }
  300. namespace internal {
  301. uint16* WorkingMemory::GetHashTable(size_t input_size, int* table_size) {
  302. // Use smaller hash table when input.size() is smaller, since we
  303. // fill the table, incurring O(hash table size) overhead for
  304. // compression, and if the input is short, we won't need that
  305. // many hash table entries anyway.
  306. assert(kMaxHashTableSize >= 256);
  307. size_t htsize = 256;
  308. while (htsize < kMaxHashTableSize && htsize < input_size) {
  309. htsize <<= 1;
  310. }
  311. uint16* table;
  312. if (htsize <= ARRAYSIZE(small_table_)) {
  313. table = small_table_;
  314. } else {
  315. if (large_table_ == NULL) {
  316. large_table_ = new uint16[kMaxHashTableSize];
  317. }
  318. table = large_table_;
  319. }
  320. *table_size = htsize;
  321. memset(table, 0, htsize * sizeof(*table));
  322. return table;
  323. }
  324. } // end namespace internal
  325. // For 0 <= offset <= 4, GetUint32AtOffset(GetEightBytesAt(p), offset) will
  326. // equal UNALIGNED_LOAD32(p + offset). Motivation: On x86-64 hardware we have
  327. // empirically found that overlapping loads such as
  328. // UNALIGNED_LOAD32(p) ... UNALIGNED_LOAD32(p+1) ... UNALIGNED_LOAD32(p+2)
  329. // are slower than UNALIGNED_LOAD64(p) followed by shifts and casts to uint32.
  330. //
  331. // We have different versions for 64- and 32-bit; ideally we would avoid the
  332. // two functions and just inline the UNALIGNED_LOAD64 call into
  333. // GetUint32AtOffset, but GCC (at least not as of 4.6) is seemingly not clever
  334. // enough to avoid loading the value multiple times then. For 64-bit, the load
  335. // is done when GetEightBytesAt() is called, whereas for 32-bit, the load is
  336. // done at GetUint32AtOffset() time.
  337. #ifdef ARCH_K8
  338. typedef uint64 EightBytesReference;
  339. static inline EightBytesReference GetEightBytesAt(const char* ptr) {
  340. return UNALIGNED_LOAD64(ptr);
  341. }
  342. static inline uint32 GetUint32AtOffset(uint64 v, int offset) {
  343. assert(offset >= 0);
  344. assert(offset <= 4);
  345. return v >> (LittleEndian::IsLittleEndian() ? 8 * offset : 32 - 8 * offset);
  346. }
  347. #else
  348. typedef const char* EightBytesReference;
  349. static inline EightBytesReference GetEightBytesAt(const char* ptr) {
  350. return ptr;
  351. }
  352. static inline uint32 GetUint32AtOffset(const char* v, int offset) {
  353. assert(offset >= 0);
  354. assert(offset <= 4);
  355. return UNALIGNED_LOAD32(v + offset);
  356. }
  357. #endif
  358. // Flat array compression that does not emit the "uncompressed length"
  359. // prefix. Compresses "input" string to the "*op" buffer.
  360. //
  361. // REQUIRES: "input" is at most "kBlockSize" bytes long.
  362. // REQUIRES: "op" points to an array of memory that is at least
  363. // "MaxCompressedLength(input.size())" in size.
  364. // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
  365. // REQUIRES: "table_size" is a power of two
  366. //
  367. // Returns an "end" pointer into "op" buffer.
  368. // "end - op" is the compressed size of "input".
  369. namespace internal {
  370. char* CompressFragment(const char* input,
  371. size_t input_size,
  372. char* op,
  373. uint16* table,
  374. const int table_size) {
  375. // "ip" is the input pointer, and "op" is the output pointer.
  376. const char* ip = input;
  377. assert(input_size <= kBlockSize);
  378. assert((table_size & (table_size - 1)) == 0); // table must be power of two
  379. const int shift = 32 - Bits::Log2Floor(table_size);
  380. assert(static_cast<int>(kuint32max >> shift) == table_size - 1);
  381. const char* ip_end = input + input_size;
  382. const char* base_ip = ip;
  383. // Bytes in [next_emit, ip) will be emitted as literal bytes. Or
  384. // [next_emit, ip_end) after the main loop.
  385. const char* next_emit = ip;
  386. const size_t kInputMarginBytes = 15;
  387. if (PREDICT_TRUE(input_size >= kInputMarginBytes)) {
  388. const char* ip_limit = input + input_size - kInputMarginBytes;
  389. for (uint32 next_hash = Hash(++ip, shift); ; ) {
  390. assert(next_emit < ip);
  391. // The body of this loop calls EmitLiteral once and then EmitCopy one or
  392. // more times. (The exception is that when we're close to exhausting
  393. // the input we goto emit_remainder.)
  394. //
  395. // In the first iteration of this loop we're just starting, so
  396. // there's nothing to copy, so calling EmitLiteral once is
  397. // necessary. And we only start a new iteration when the
  398. // current iteration has determined that a call to EmitLiteral will
  399. // precede the next call to EmitCopy (if any).
  400. //
  401. // Step 1: Scan forward in the input looking for a 4-byte-long match.
  402. // If we get close to exhausting the input then goto emit_remainder.
  403. //
  404. // Heuristic match skipping: If 32 bytes are scanned with no matches
  405. // found, start looking only at every other byte. If 32 more bytes are
  406. // scanned (or skipped), look at every third byte, etc.. When a match is
  407. // found, immediately go back to looking at every byte. This is a small
  408. // loss (~5% performance, ~0.1% density) for compressible data due to more
  409. // bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  410. // win since the compressor quickly "realizes" the data is incompressible
  411. // and doesn't bother looking for matches everywhere.
  412. //
  413. // The "skip" variable keeps track of how many bytes there are since the
  414. // last match; dividing it by 32 (ie. right-shifting by five) gives the
  415. // number of bytes to move ahead for each iteration.
  416. uint32 skip = 32;
  417. const char* next_ip = ip;
  418. const char* candidate;
  419. do {
  420. ip = next_ip;
  421. uint32 hash = next_hash;
  422. assert(hash == Hash(ip, shift));
  423. uint32 bytes_between_hash_lookups = skip++ >> 5; // uint32 bytes_between_hash_lookups = skip >> 5; skip += bytes_between_hash_lookups; ESENTHEL CHANGED
  424. next_ip = ip + bytes_between_hash_lookups;
  425. if (PREDICT_FALSE(next_ip > ip_limit)) {
  426. goto emit_remainder;
  427. }
  428. next_hash = Hash(next_ip, shift);
  429. candidate = base_ip + table[hash];
  430. assert(candidate >= base_ip);
  431. assert(candidate < ip);
  432. table[hash] = ip - base_ip;
  433. } while (PREDICT_TRUE(UNALIGNED_LOAD32(ip) !=
  434. UNALIGNED_LOAD32(candidate)));
  435. // Step 2: A 4-byte match has been found. We'll later see if more
  436. // than 4 bytes match. But, prior to the match, input
  437. // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes."
  438. assert(next_emit + 16 <= ip_end);
  439. op = EmitLiteral(op, next_emit, ip - next_emit, true);
  440. // Step 3: Call EmitCopy, and then see if another EmitCopy could
  441. // be our next move. Repeat until we find no match for the
  442. // input immediately after what was consumed by the last EmitCopy call.
  443. //
  444. // If we exit this loop normally then we need to call EmitLiteral next,
  445. // though we don't yet know how big the literal will be. We handle that
  446. // by proceeding to the next iteration of the main loop. We also can exit
  447. // this loop via goto if we get close to exhausting the input.
  448. EightBytesReference input_bytes;
  449. uint32 candidate_bytes = 0;
  450. do {
  451. // We have a 4-byte match at ip, and no need to emit any
  452. // "literal bytes" prior to ip.
  453. const char* base = ip;
  454. std::pair<size_t, bool> p =
  455. FindMatchLength(candidate + 4, ip + 4, ip_end);
  456. size_t matched = 4 + p.first;
  457. ip += matched;
  458. size_t offset = base - candidate;
  459. assert(0 == memcmp(base, candidate, matched));
  460. op = EmitCopy(op, offset, matched, p.second);
  461. next_emit = ip;
  462. if (PREDICT_FALSE(ip >= ip_limit)) {
  463. goto emit_remainder;
  464. }
  465. // We are now looking for a 4-byte match again. We read
  466. // table[Hash(ip, shift)] for that. To improve compression,
  467. // we also update table[Hash(ip - 1, shift)] and table[Hash(ip, shift)].
  468. input_bytes = GetEightBytesAt(ip - 1);
  469. uint32 prev_hash = HashBytes(GetUint32AtOffset(input_bytes, 0), shift);
  470. table[prev_hash] = ip - base_ip - 1;
  471. uint32 cur_hash = HashBytes(GetUint32AtOffset(input_bytes, 1), shift);
  472. candidate = base_ip + table[cur_hash];
  473. candidate_bytes = UNALIGNED_LOAD32(candidate);
  474. table[cur_hash] = ip - base_ip;
  475. } while (GetUint32AtOffset(input_bytes, 1) == candidate_bytes);
  476. next_hash = HashBytes(GetUint32AtOffset(input_bytes, 2), shift);
  477. ++ip;
  478. }
  479. }
  480. emit_remainder:
  481. // Emit the remaining bytes as a literal
  482. if (next_emit < ip_end) {
  483. op = EmitLiteral(op, next_emit, ip_end - next_emit, false);
  484. }
  485. return op;
  486. }
  487. } // end namespace internal
  488. // Called back at avery compression call to trace parameters and sizes.
  489. static inline void Report(const char *algorithm, size_t compressed_size,
  490. size_t uncompressed_size) {}
  491. // Signature of output types needed by decompression code.
  492. // The decompression code is templatized on a type that obeys this
  493. // signature so that we do not pay virtual function call overhead in
  494. // the middle of a tight decompression loop.
  495. //
  496. // class DecompressionWriter {
  497. // public:
  498. // // Called before decompression
  499. // void SetExpectedLength(size_t length);
  500. //
  501. // // Called after decompression
  502. // bool CheckLength() const;
  503. //
  504. // // Called repeatedly during decompression
  505. // bool Append(const char* ip, size_t length);
  506. // bool AppendFromSelf(uint32 offset, size_t length);
  507. //
  508. // // The rules for how TryFastAppend differs from Append are somewhat
  509. // // convoluted:
  510. // //
  511. // // - TryFastAppend is allowed to decline (return false) at any
  512. // // time, for any reason -- just "return false" would be
  513. // // a perfectly legal implementation of TryFastAppend.
  514. // // The intention is for TryFastAppend to allow a fast path
  515. // // in the common case of a small append.
  516. // // - TryFastAppend is allowed to read up to <available> bytes
  517. // // from the input buffer, whereas Append is allowed to read
  518. // // <length>. However, if it returns true, it must leave
  519. // // at least five (kMaximumTagLength) bytes in the input buffer
  520. // // afterwards, so that there is always enough space to read the
  521. // // next tag without checking for a refill.
  522. // // - TryFastAppend must always return decline (return false)
  523. // // if <length> is 61 or more, as in this case the literal length is not
  524. // // decoded fully. In practice, this should not be a big problem,
  525. // // as it is unlikely that one would implement a fast path accepting
  526. // // this much data.
  527. // //
  528. // bool TryFastAppend(const char* ip, size_t available, size_t length);
  529. // };
  530. namespace internal {
  531. // Mapping from i in range [0,4] to a mask to extract the bottom 8*i bits
  532. static const uint32 wordmask[] = {
  533. 0u, 0xffu, 0xffffu, 0xffffffu, 0xffffffffu
  534. };
  535. } // end namespace internal
  536. // Helper class for decompression
  537. class SnappyDecompressor {
  538. private:
  539. Source* reader_; // Underlying source of bytes to decompress
  540. const char* ip_; // Points to next buffered byte
  541. const char* ip_limit_; // Points just past buffered bytes
  542. uint32 peeked_; // Bytes peeked from reader (need to skip)
  543. bool eof_; // Hit end of input without an error?
  544. char scratch_[kMaximumTagLength]; // See RefillTag().
  545. // Ensure that all of the tag metadata for the next tag is available
  546. // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even
  547. // if (ip_limit_ - ip_ < 5).
  548. //
  549. // Returns true on success, false on error or end of input.
  550. bool RefillTag();
  551. public:
  552. explicit SnappyDecompressor(Source* reader)
  553. : reader_(reader),
  554. ip_(NULL),
  555. ip_limit_(NULL),
  556. peeked_(0),
  557. eof_(false) {
  558. }
  559. ~SnappyDecompressor() {
  560. // Advance past any bytes we peeked at from the reader
  561. reader_->Skip(peeked_);
  562. }
  563. // Returns true iff we have hit the end of the input without an error.
  564. bool eof() const {
  565. return eof_;
  566. }
  567. // Read the uncompressed length stored at the start of the compressed data.
  568. // On succcess, stores the length in *result and returns true.
  569. // On failure, returns false.
  570. bool ReadUncompressedLength(uint32* result) {
  571. assert(ip_ == NULL); // Must not have read anything yet
  572. // Length is encoded in 1..5 bytes
  573. *result = 0;
  574. uint32 shift = 0;
  575. while (true) {
  576. if (shift >= 32) return false;
  577. size_t n;
  578. const char* ip = reader_->Peek(&n);
  579. if (n == 0) return false;
  580. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  581. reader_->Skip(1);
  582. uint32 val = c & 0x7f;
  583. if (((val << shift) >> shift) != val) return false;
  584. *result |= val << shift;
  585. if (c < 128) {
  586. break;
  587. }
  588. shift += 7;
  589. }
  590. return true;
  591. }
  592. // Process the next item found in the input.
  593. // Returns true if successful, false on error or end of input.
  594. template <class Writer>
  595. void DecompressAllTags(Writer* writer) {
  596. const char* ip = ip_;
  597. // For position-independent executables, accessing global arrays can be
  598. // slow. Move wordmask array onto the stack to mitigate this.
  599. uint32 wordmask[sizeof(internal::wordmask)/sizeof(uint32)];
  600. memcpy(wordmask, internal::wordmask, sizeof(wordmask));
  601. // We could have put this refill fragment only at the beginning of the loop.
  602. // However, duplicating it at the end of each branch gives the compiler more
  603. // scope to optimize the <ip_limit_ - ip> expression based on the local
  604. // context, which overall increases speed.
  605. #define MAYBE_REFILL() \
  606. if (ip_limit_ - ip < kMaximumTagLength) { \
  607. ip_ = ip; \
  608. if (!RefillTag()) return; \
  609. ip = ip_; \
  610. }
  611. MAYBE_REFILL();
  612. for ( ;; ) {
  613. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip++));
  614. // Ratio of iterations that have LITERAL vs non-LITERAL for different
  615. // inputs.
  616. //
  617. // input LITERAL NON_LITERAL
  618. // -----------------------------------
  619. // html|html4|cp 23% 77%
  620. // urls 36% 64%
  621. // jpg 47% 53%
  622. // pdf 19% 81%
  623. // txt[1-4] 25% 75%
  624. // pb 24% 76%
  625. // bin 24% 76%
  626. if (PREDICT_FALSE((c & 0x3) == LITERAL)) {
  627. size_t literal_length = (c >> 2) + 1u;
  628. if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length)) {
  629. assert(literal_length < 61);
  630. ip += literal_length;
  631. // NOTE(user): There is no MAYBE_REFILL() here, as TryFastAppend()
  632. // will not return true unless there's already at least five spare
  633. // bytes in addition to the literal.
  634. continue;
  635. }
  636. if (PREDICT_FALSE(literal_length >= 61)) {
  637. // Long literal.
  638. const size_t literal_length_length = literal_length - 60;
  639. literal_length =
  640. (LittleEndian::Load32(ip) & wordmask[literal_length_length]) + 1;
  641. ip += literal_length_length;
  642. }
  643. size_t avail = ip_limit_ - ip;
  644. while (avail < literal_length) {
  645. if (!writer->Append(ip, avail)) return;
  646. literal_length -= avail;
  647. reader_->Skip(peeked_);
  648. size_t n;
  649. ip = reader_->Peek(&n);
  650. avail = n;
  651. peeked_ = avail;
  652. if (avail == 0) return; // Premature end of input
  653. ip_limit_ = ip + avail;
  654. }
  655. if (!writer->Append(ip, literal_length)) {
  656. return;
  657. }
  658. ip += literal_length;
  659. MAYBE_REFILL();
  660. } else {
  661. const size_t entry = char_table[c];
  662. const size_t trailer = LittleEndian::Load32(ip) & wordmask[entry >> 11];
  663. const size_t length = entry & 0xff;
  664. ip += entry >> 11;
  665. // copy_offset/256 is encoded in bits 8..10. By just fetching
  666. // those bits, we get copy_offset (since the bit-field starts at
  667. // bit 8).
  668. const size_t copy_offset = entry & 0x700;
  669. if (!writer->AppendFromSelf(copy_offset + trailer, length)) {
  670. return;
  671. }
  672. MAYBE_REFILL();
  673. }
  674. }
  675. #undef MAYBE_REFILL
  676. }
  677. };
  678. bool SnappyDecompressor::RefillTag() {
  679. const char* ip = ip_;
  680. if (ip == ip_limit_) {
  681. // Fetch a new fragment from the reader
  682. reader_->Skip(peeked_); // All peeked bytes are used up
  683. size_t n;
  684. ip = reader_->Peek(&n);
  685. peeked_ = n;
  686. eof_ = (n == 0);
  687. if (eof_) return false;
  688. ip_limit_ = ip + n;
  689. }
  690. // Read the tag character
  691. assert(ip < ip_limit_);
  692. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  693. const uint32 entry = char_table[c];
  694. const uint32 needed = (entry >> 11) + 1; // +1 byte for 'c'
  695. assert(needed <= sizeof(scratch_));
  696. // Read more bytes from reader if needed
  697. uint32 nbuf = ip_limit_ - ip;
  698. if (nbuf < needed) {
  699. // Stitch together bytes from ip and reader to form the word
  700. // contents. We store the needed bytes in "scratch_". They
  701. // will be consumed immediately by the caller since we do not
  702. // read more than we need.
  703. memmove(scratch_, ip, nbuf);
  704. reader_->Skip(peeked_); // All peeked bytes are used up
  705. peeked_ = 0;
  706. while (nbuf < needed) {
  707. size_t length;
  708. const char* src = reader_->Peek(&length);
  709. if (length == 0) return false;
  710. uint32 to_add = std::min<uint32>(needed - nbuf, length);
  711. memcpy(scratch_ + nbuf, src, to_add);
  712. nbuf += to_add;
  713. reader_->Skip(to_add);
  714. }
  715. assert(nbuf == needed);
  716. ip_ = scratch_;
  717. ip_limit_ = scratch_ + needed;
  718. } else if (nbuf < kMaximumTagLength) {
  719. // Have enough bytes, but move into scratch_ so that we do not
  720. // read past end of input
  721. memmove(scratch_, ip, nbuf);
  722. reader_->Skip(peeked_); // All peeked bytes are used up
  723. peeked_ = 0;
  724. ip_ = scratch_;
  725. ip_limit_ = scratch_ + nbuf;
  726. } else {
  727. // Pass pointer to buffer returned by reader_.
  728. ip_ = ip;
  729. }
  730. return true;
  731. }
  732. template <typename Writer>
  733. static bool InternalUncompress(Source* r, Writer* writer) {
  734. // Read the uncompressed length from the front of the compressed input
  735. SnappyDecompressor decompressor(r);
  736. uint32 uncompressed_len = 0;
  737. if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
  738. return InternalUncompressAllTags(&decompressor, writer, r->Available(),
  739. uncompressed_len);
  740. }
  741. template <typename Writer>
  742. static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
  743. Writer* writer,
  744. uint32 compressed_len,
  745. uint32 uncompressed_len) {
  746. Report("snappy_uncompress", compressed_len, uncompressed_len);
  747. writer->SetExpectedLength(uncompressed_len);
  748. // Process the entire input
  749. decompressor->DecompressAllTags(writer);
  750. writer->Flush();
  751. return (decompressor->eof() && writer->CheckLength());
  752. }
  753. bool GetUncompressedLength(Source* source, uint32* result) {
  754. SnappyDecompressor decompressor(source);
  755. return decompressor.ReadUncompressedLength(result);
  756. }
  757. size_t Compress(Source* reader, Sink* writer) {
  758. size_t written = 0;
  759. size_t N = reader->Available();
  760. const size_t uncompressed_size = N;
  761. char ulength[Varint::kMax32];
  762. char* p = Varint::Encode32(ulength, N);
  763. writer->Append(ulength, p-ulength);
  764. written += (p - ulength);
  765. internal::WorkingMemory wmem;
  766. char* scratch = NULL;
  767. char* scratch_output = NULL;
  768. while (N > 0) {
  769. // Get next block to compress (without copying if possible)
  770. size_t fragment_size;
  771. const char* fragment = reader->Peek(&fragment_size);
  772. assert(fragment_size != 0); // premature end of input
  773. const size_t num_to_read = std::min(N, kBlockSize);
  774. size_t bytes_read = fragment_size;
  775. size_t pending_advance = 0;
  776. if (bytes_read >= num_to_read) {
  777. // Buffer returned by reader is large enough
  778. pending_advance = num_to_read;
  779. fragment_size = num_to_read;
  780. } else {
  781. // Read into scratch buffer
  782. if (scratch == NULL) {
  783. // If this is the last iteration, we want to allocate N bytes
  784. // of space, otherwise the max possible kBlockSize space.
  785. // num_to_read contains exactly the correct value
  786. scratch = new char[num_to_read];
  787. }
  788. memcpy(scratch, fragment, bytes_read);
  789. reader->Skip(bytes_read);
  790. while (bytes_read < num_to_read) {
  791. fragment = reader->Peek(&fragment_size);
  792. size_t n = std::min<size_t>(fragment_size, num_to_read - bytes_read);
  793. memcpy(scratch + bytes_read, fragment, n);
  794. bytes_read += n;
  795. reader->Skip(n);
  796. }
  797. assert(bytes_read == num_to_read);
  798. fragment = scratch;
  799. fragment_size = num_to_read;
  800. }
  801. assert(fragment_size == num_to_read);
  802. // Get encoding table for compression
  803. int table_size;
  804. uint16* table = wmem.GetHashTable(num_to_read, &table_size);
  805. // Compress input_fragment and append to dest
  806. const int max_output = MaxCompressedLength(num_to_read);
  807. // Need a scratch buffer for the output, in case the byte sink doesn't
  808. // have room for us directly.
  809. if (scratch_output == NULL) {
  810. scratch_output = new char[max_output];
  811. } else {
  812. // Since we encode kBlockSize regions followed by a region
  813. // which is <= kBlockSize in length, a previously allocated
  814. // scratch_output[] region is big enough for this iteration.
  815. }
  816. char* dest = writer->GetAppendBuffer(max_output, scratch_output);
  817. char* end = internal::CompressFragment(fragment, fragment_size,
  818. dest, table, table_size);
  819. writer->Append(dest, end - dest);
  820. written += (end - dest);
  821. N -= num_to_read;
  822. reader->Skip(pending_advance);
  823. }
  824. Report("snappy_compress", written, uncompressed_size);
  825. delete[] scratch;
  826. delete[] scratch_output;
  827. return written;
  828. }
  829. // -----------------------------------------------------------------------
  830. // IOVec interfaces
  831. // -----------------------------------------------------------------------
  832. // A type that writes to an iovec.
  833. // Note that this is not a "ByteSink", but a type that matches the
  834. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  835. /*class SnappyIOVecWriter {
  836. private:
  837. const struct iovec* output_iov_;
  838. const size_t output_iov_count_;
  839. // We are currently writing into output_iov_[curr_iov_index_].
  840. size_t curr_iov_index_;
  841. // Bytes written to output_iov_[curr_iov_index_] so far.
  842. size_t curr_iov_written_;
  843. // Total bytes decompressed into output_iov_ so far.
  844. size_t total_written_;
  845. // Maximum number of bytes that will be decompressed into output_iov_.
  846. size_t output_limit_;
  847. inline char* GetIOVecPointer(size_t index, size_t offset) {
  848. return reinterpret_cast<char*>(output_iov_[index].iov_base) +
  849. offset;
  850. }
  851. public:
  852. // Does not take ownership of iov. iov must be valid during the
  853. // entire lifetime of the SnappyIOVecWriter.
  854. inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count)
  855. : output_iov_(iov),
  856. output_iov_count_(iov_count),
  857. curr_iov_index_(0),
  858. curr_iov_written_(0),
  859. total_written_(0),
  860. output_limit_(-1) {
  861. }
  862. inline void SetExpectedLength(size_t len) {
  863. output_limit_ = len;
  864. }
  865. inline bool CheckLength() const {
  866. return total_written_ == output_limit_;
  867. }
  868. inline bool Append(const char* ip, size_t len) {
  869. if (total_written_ + len > output_limit_) {
  870. return false;
  871. }
  872. while (len > 0) {
  873. assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len);
  874. if (curr_iov_written_ >= output_iov_[curr_iov_index_].iov_len) {
  875. // This iovec is full. Go to the next one.
  876. if (curr_iov_index_ + 1 >= output_iov_count_) {
  877. return false;
  878. }
  879. curr_iov_written_ = 0;
  880. ++curr_iov_index_;
  881. }
  882. const size_t to_write = std::min(
  883. len, output_iov_[curr_iov_index_].iov_len - curr_iov_written_);
  884. memcpy(GetIOVecPointer(curr_iov_index_, curr_iov_written_),
  885. ip,
  886. to_write);
  887. curr_iov_written_ += to_write;
  888. total_written_ += to_write;
  889. ip += to_write;
  890. len -= to_write;
  891. }
  892. return true;
  893. }
  894. inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
  895. const size_t space_left = output_limit_ - total_written_;
  896. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
  897. output_iov_[curr_iov_index_].iov_len - curr_iov_written_ >= 16) {
  898. // Fast path, used for the majority (about 95%) of invocations.
  899. char* ptr = GetIOVecPointer(curr_iov_index_, curr_iov_written_);
  900. UnalignedCopy128(ip, ptr);
  901. curr_iov_written_ += len;
  902. total_written_ += len;
  903. return true;
  904. }
  905. return false;
  906. }
  907. inline bool AppendFromSelf(size_t offset, size_t len) {
  908. if (offset > total_written_ || offset == 0) {
  909. return false;
  910. }
  911. const size_t space_left = output_limit_ - total_written_;
  912. if (len > space_left) {
  913. return false;
  914. }
  915. // Locate the iovec from which we need to start the copy.
  916. size_t from_iov_index = curr_iov_index_;
  917. size_t from_iov_offset = curr_iov_written_;
  918. while (offset > 0) {
  919. if (from_iov_offset >= offset) {
  920. from_iov_offset -= offset;
  921. break;
  922. }
  923. offset -= from_iov_offset;
  924. assert(from_iov_index > 0);
  925. --from_iov_index;
  926. from_iov_offset = output_iov_[from_iov_index].iov_len;
  927. }
  928. // Copy <len> bytes starting from the iovec pointed to by from_iov_index to
  929. // the current iovec.
  930. while (len > 0) {
  931. assert(from_iov_index <= curr_iov_index_);
  932. if (from_iov_index != curr_iov_index_) {
  933. const size_t to_copy = std::min(
  934. output_iov_[from_iov_index].iov_len - from_iov_offset,
  935. len);
  936. Append(GetIOVecPointer(from_iov_index, from_iov_offset), to_copy);
  937. len -= to_copy;
  938. if (len > 0) {
  939. ++from_iov_index;
  940. from_iov_offset = 0;
  941. }
  942. } else {
  943. assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len);
  944. size_t to_copy = std::min(output_iov_[curr_iov_index_].iov_len -
  945. curr_iov_written_,
  946. len);
  947. if (to_copy == 0) {
  948. // This iovec is full. Go to the next one.
  949. if (curr_iov_index_ + 1 >= output_iov_count_) {
  950. return false;
  951. }
  952. ++curr_iov_index_;
  953. curr_iov_written_ = 0;
  954. continue;
  955. }
  956. if (to_copy > len) {
  957. to_copy = len;
  958. }
  959. IncrementalCopySlow(
  960. GetIOVecPointer(from_iov_index, from_iov_offset),
  961. GetIOVecPointer(curr_iov_index_, curr_iov_written_),
  962. GetIOVecPointer(curr_iov_index_, curr_iov_written_) + to_copy);
  963. curr_iov_written_ += to_copy;
  964. from_iov_offset += to_copy;
  965. total_written_ += to_copy;
  966. len -= to_copy;
  967. }
  968. }
  969. return true;
  970. }
  971. inline void Flush() {}
  972. };
  973. bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
  974. const struct iovec* iov, size_t iov_cnt) {
  975. ByteArraySource reader(compressed, compressed_length);
  976. return RawUncompressToIOVec(&reader, iov, iov_cnt);
  977. }
  978. bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
  979. size_t iov_cnt) {
  980. SnappyIOVecWriter output(iov, iov_cnt);
  981. return InternalUncompress(compressed, &output);
  982. }
  983. */
  984. // -----------------------------------------------------------------------
  985. // Flat array interfaces
  986. // -----------------------------------------------------------------------
  987. // A type that writes to a flat array.
  988. // Note that this is not a "ByteSink", but a type that matches the
  989. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  990. class SnappyArrayWriter {
  991. private:
  992. char* base_;
  993. char* op_;
  994. char* op_limit_;
  995. public:
  996. inline explicit SnappyArrayWriter(char* dst)
  997. : base_(dst),
  998. op_(dst),
  999. op_limit_(dst) {
  1000. }
  1001. inline void SetExpectedLength(size_t len) {
  1002. op_limit_ = op_ + len;
  1003. }
  1004. inline bool CheckLength() const {
  1005. return op_ == op_limit_;
  1006. }
  1007. inline bool Append(const char* ip, size_t len) {
  1008. char* op = op_;
  1009. const size_t space_left = op_limit_ - op;
  1010. if (space_left < len) {
  1011. return false;
  1012. }
  1013. memcpy(op, ip, len);
  1014. op_ = op + len;
  1015. return true;
  1016. }
  1017. inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
  1018. char* op = op_;
  1019. const size_t space_left = op_limit_ - op;
  1020. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
  1021. // Fast path, used for the majority (about 95%) of invocations.
  1022. UnalignedCopy128(ip, op);
  1023. op_ = op + len;
  1024. return true;
  1025. } else {
  1026. return false;
  1027. }
  1028. }
  1029. inline bool AppendFromSelf(size_t offset, size_t len) {
  1030. char* const op_end = op_ + len;
  1031. // Check if we try to append from before the start of the buffer.
  1032. // Normally this would just be a check for "produced < offset",
  1033. // but "produced <= offset - 1u" is equivalent for every case
  1034. // except the one where offset==0, where the right side will wrap around
  1035. // to a very big number. This is convenient, as offset==0 is another
  1036. // invalid case that we also want to catch, so that we do not go
  1037. // into an infinite loop.
  1038. if (Produced() <= offset - 1u || op_end > op_limit_) return false;
  1039. op_ = IncrementalCopy(op_ - offset, op_, op_end, op_limit_);
  1040. return true;
  1041. }
  1042. inline size_t Produced() const {
  1043. assert(op_ >= base_);
  1044. return op_ - base_;
  1045. }
  1046. inline void Flush() {}
  1047. };
  1048. bool RawUncompress(const char* compressed, size_t n, char* uncompressed) {
  1049. ByteArraySource reader(compressed, n);
  1050. return RawUncompress(&reader, uncompressed);
  1051. }
  1052. bool RawUncompress(Source* compressed, char* uncompressed) {
  1053. SnappyArrayWriter output(uncompressed);
  1054. return InternalUncompress(compressed, &output);
  1055. }
  1056. /*bool Uncompress(const char* compressed, size_t n, string* uncompressed) {
  1057. size_t ulength;
  1058. if (!GetUncompressedLength(compressed, n, &ulength)) {
  1059. return false;
  1060. }
  1061. // On 32-bit builds: max_size() < kuint32max. Check for that instead
  1062. // of crashing (e.g., consider externally specified compressed data).
  1063. if (ulength > uncompressed->max_size()) {
  1064. return false;
  1065. }
  1066. STLStringResizeUninitialized(uncompressed, ulength);
  1067. return RawUncompress(compressed, n, string_as_array(uncompressed));
  1068. }*/
  1069. // A Writer that drops everything on the floor and just does validation
  1070. class SnappyDecompressionValidator {
  1071. private:
  1072. size_t expected_;
  1073. size_t produced_;
  1074. public:
  1075. inline SnappyDecompressionValidator() : expected_(0), produced_(0) { }
  1076. inline void SetExpectedLength(size_t len) {
  1077. expected_ = len;
  1078. }
  1079. inline bool CheckLength() const {
  1080. return expected_ == produced_;
  1081. }
  1082. inline bool Append(const char* ip, size_t len) {
  1083. produced_ += len;
  1084. return produced_ <= expected_;
  1085. }
  1086. inline bool TryFastAppend(const char* ip, size_t available, size_t length) {
  1087. return false;
  1088. }
  1089. inline bool AppendFromSelf(size_t offset, size_t len) {
  1090. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1091. // the "offset - 1u" trick.
  1092. if (produced_ <= offset - 1u) return false;
  1093. produced_ += len;
  1094. return produced_ <= expected_;
  1095. }
  1096. inline void Flush() {}
  1097. };
  1098. bool IsValidCompressedBuffer(const char* compressed, size_t n) {
  1099. ByteArraySource reader(compressed, n);
  1100. SnappyDecompressionValidator writer;
  1101. return InternalUncompress(&reader, &writer);
  1102. }
  1103. bool IsValidCompressed(Source* compressed) {
  1104. SnappyDecompressionValidator writer;
  1105. return InternalUncompress(compressed, &writer);
  1106. }
  1107. void RawCompress(const char* input,
  1108. size_t input_length,
  1109. char* compressed,
  1110. size_t* compressed_length) {
  1111. ByteArraySource reader(input, input_length);
  1112. UncheckedByteArraySink writer(compressed);
  1113. Compress(&reader, &writer);
  1114. // Compute how many bytes were added
  1115. *compressed_length = (writer.CurrentDestination() - compressed);
  1116. }
  1117. /*size_t Compress(const char* input, size_t input_length, string* compressed) {
  1118. // Pre-grow the buffer to the max length of the compressed output
  1119. STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
  1120. size_t compressed_length;
  1121. RawCompress(input, input_length, string_as_array(compressed),
  1122. &compressed_length);
  1123. compressed->resize(compressed_length);
  1124. return compressed_length;
  1125. }*/
  1126. // -----------------------------------------------------------------------
  1127. // Sink interface
  1128. // -----------------------------------------------------------------------
  1129. // A type that decompresses into a Sink. The template parameter
  1130. // Allocator must export one method "char* Allocate(int size);", which
  1131. // allocates a buffer of "size" and appends that to the destination.
  1132. /*template <typename Allocator>
  1133. class SnappyScatteredWriter {
  1134. Allocator allocator_;
  1135. // We need random access into the data generated so far. Therefore
  1136. // we keep track of all of the generated data as an array of blocks.
  1137. // All of the blocks except the last have length kBlockSize.
  1138. std::vector<char*> blocks_;
  1139. size_t expected_;
  1140. // Total size of all fully generated blocks so far
  1141. size_t full_size_;
  1142. // Pointer into current output block
  1143. char* op_base_; // Base of output block
  1144. char* op_ptr_; // Pointer to next unfilled byte in block
  1145. char* op_limit_; // Pointer just past block
  1146. inline size_t Size() const {
  1147. return full_size_ + (op_ptr_ - op_base_);
  1148. }
  1149. bool SlowAppend(const char* ip, size_t len);
  1150. bool SlowAppendFromSelf(size_t offset, size_t len);
  1151. public:
  1152. inline explicit SnappyScatteredWriter(const Allocator& allocator)
  1153. : allocator_(allocator),
  1154. full_size_(0),
  1155. op_base_(NULL),
  1156. op_ptr_(NULL),
  1157. op_limit_(NULL) {
  1158. }
  1159. inline void SetExpectedLength(size_t len) {
  1160. assert(blocks_.empty());
  1161. expected_ = len;
  1162. }
  1163. inline bool CheckLength() const {
  1164. return Size() == expected_;
  1165. }
  1166. // Return the number of bytes actually uncompressed so far
  1167. inline size_t Produced() const {
  1168. return Size();
  1169. }
  1170. inline bool Append(const char* ip, size_t len) {
  1171. size_t avail = op_limit_ - op_ptr_;
  1172. if (len <= avail) {
  1173. // Fast path
  1174. memcpy(op_ptr_, ip, len);
  1175. op_ptr_ += len;
  1176. return true;
  1177. } else {
  1178. return SlowAppend(ip, len);
  1179. }
  1180. }
  1181. inline bool TryFastAppend(const char* ip, size_t available, size_t length) {
  1182. char* op = op_ptr_;
  1183. const int space_left = op_limit_ - op;
  1184. if (length <= 16 && available >= 16 + kMaximumTagLength &&
  1185. space_left >= 16) {
  1186. // Fast path, used for the majority (about 95%) of invocations.
  1187. UnalignedCopy128(ip, op);
  1188. op_ptr_ = op + length;
  1189. return true;
  1190. } else {
  1191. return false;
  1192. }
  1193. }
  1194. inline bool AppendFromSelf(size_t offset, size_t len) {
  1195. char* const op_end = op_ptr_ + len;
  1196. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1197. // the "offset - 1u" trick.
  1198. if (PREDICT_TRUE(offset - 1u < op_ptr_ - op_base_ && op_end <= op_limit_)) {
  1199. // Fast path: src and dst in current block.
  1200. op_ptr_ = IncrementalCopy(op_ptr_ - offset, op_ptr_, op_end, op_limit_);
  1201. return true;
  1202. }
  1203. return SlowAppendFromSelf(offset, len);
  1204. }
  1205. // Called at the end of the decompress. We ask the allocator
  1206. // write all blocks to the sink.
  1207. inline void Flush() { allocator_.Flush(Produced()); }
  1208. };
  1209. template<typename Allocator>
  1210. bool SnappyScatteredWriter<Allocator>::SlowAppend(const char* ip, size_t len) {
  1211. size_t avail = op_limit_ - op_ptr_;
  1212. while (len > avail) {
  1213. // Completely fill this block
  1214. memcpy(op_ptr_, ip, avail);
  1215. op_ptr_ += avail;
  1216. assert(op_limit_ - op_ptr_ == 0);
  1217. full_size_ += (op_ptr_ - op_base_);
  1218. len -= avail;
  1219. ip += avail;
  1220. // Bounds check
  1221. if (full_size_ + len > expected_) {
  1222. return false;
  1223. }
  1224. // Make new block
  1225. size_t bsize = std::min<size_t>(kBlockSize, expected_ - full_size_);
  1226. op_base_ = allocator_.Allocate(bsize);
  1227. op_ptr_ = op_base_;
  1228. op_limit_ = op_base_ + bsize;
  1229. blocks_.push_back(op_base_);
  1230. avail = bsize;
  1231. }
  1232. memcpy(op_ptr_, ip, len);
  1233. op_ptr_ += len;
  1234. return true;
  1235. }
  1236. template<typename Allocator>
  1237. bool SnappyScatteredWriter<Allocator>::SlowAppendFromSelf(size_t offset,
  1238. size_t len) {
  1239. // Overflow check
  1240. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1241. // the "offset - 1u" trick.
  1242. const size_t cur = Size();
  1243. if (offset - 1u >= cur) return false;
  1244. if (expected_ - cur < len) return false;
  1245. // Currently we shouldn't ever hit this path because Compress() chops the
  1246. // input into blocks and does not create cross-block copies. However, it is
  1247. // nice if we do not rely on that, since we can get better compression if we
  1248. // allow cross-block copies and thus might want to change the compressor in
  1249. // the future.
  1250. size_t src = cur - offset;
  1251. while (len-- > 0) {
  1252. char c = blocks_[src >> kBlockLog][src & (kBlockSize-1)];
  1253. Append(&c, 1);
  1254. src++;
  1255. }
  1256. return true;
  1257. }
  1258. class SnappySinkAllocator {
  1259. public:
  1260. explicit SnappySinkAllocator(Sink* dest): dest_(dest) {}
  1261. ~SnappySinkAllocator() {}
  1262. char* Allocate(int size) {
  1263. Datablock block(new char[size], size);
  1264. blocks_.push_back(block);
  1265. return block.data;
  1266. }
  1267. // We flush only at the end, because the writer wants
  1268. // random access to the blocks and once we hand the
  1269. // block over to the sink, we can't access it anymore.
  1270. // Also we don't write more than has been actually written
  1271. // to the blocks.
  1272. void Flush(size_t size) {
  1273. size_t size_written = 0;
  1274. size_t block_size;
  1275. for (int i = 0; i < blocks_.size(); ++i) {
  1276. block_size = std::min<size_t>(blocks_[i].size, size - size_written);
  1277. dest_->AppendAndTakeOwnership(blocks_[i].data, block_size,
  1278. &SnappySinkAllocator::Deleter, NULL);
  1279. size_written += block_size;
  1280. }
  1281. blocks_.clear();
  1282. }
  1283. private:
  1284. struct Datablock {
  1285. char* data;
  1286. size_t size;
  1287. Datablock(char* p, size_t s) : data(p), size(s) {}
  1288. };
  1289. static void Deleter(void* arg, const char* bytes, size_t size) {
  1290. delete[] bytes;
  1291. }
  1292. Sink* dest_;
  1293. std::vector<Datablock> blocks_;
  1294. // Note: copying this object is allowed
  1295. };
  1296. size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) {
  1297. SnappySinkAllocator allocator(uncompressed);
  1298. SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
  1299. InternalUncompress(compressed, &writer);
  1300. return writer.Produced();
  1301. }
  1302. bool Uncompress(Source* compressed, Sink* uncompressed) {
  1303. // Read the uncompressed length from the front of the compressed input
  1304. SnappyDecompressor decompressor(compressed);
  1305. uint32 uncompressed_len = 0;
  1306. if (!decompressor.ReadUncompressedLength(&uncompressed_len)) {
  1307. return false;
  1308. }
  1309. char c;
  1310. size_t allocated_size;
  1311. char* buf = uncompressed->GetAppendBufferVariable(
  1312. 1, uncompressed_len, &c, 1, &allocated_size);
  1313. const size_t compressed_len = compressed->Available();
  1314. // If we can get a flat buffer, then use it, otherwise do block by block
  1315. // uncompression
  1316. if (allocated_size >= uncompressed_len) {
  1317. SnappyArrayWriter writer(buf);
  1318. bool result = InternalUncompressAllTags(&decompressor, &writer,
  1319. compressed_len, uncompressed_len);
  1320. uncompressed->Append(buf, writer.Produced());
  1321. return result;
  1322. } else {
  1323. SnappySinkAllocator allocator(uncompressed);
  1324. SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
  1325. return InternalUncompressAllTags(&decompressor, &writer, compressed_len,
  1326. uncompressed_len);
  1327. }
  1328. }*/
  1329. } // end namespace snappy