snappy.cc 58 KB

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