snappy.cc 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220
  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-internal.h"
  29. #include "snappy-sinksource.h"
  30. #include "snappy.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 <algorithm>
  66. #include <array>
  67. #include <cstddef>
  68. #include <cstdint>
  69. #include <cstdio>
  70. #include <cstring>
  71. #include <string>
  72. #include <utility>
  73. #include <vector>
  74. #include <util/generic/string.h>
  75. namespace snappy {
  76. namespace {
  77. // The amount of slop bytes writers are using for unconditional copies.
  78. constexpr int kSlopBytes = 64;
  79. using internal::char_table;
  80. using internal::COPY_1_BYTE_OFFSET;
  81. using internal::COPY_2_BYTE_OFFSET;
  82. using internal::COPY_4_BYTE_OFFSET;
  83. using internal::kMaximumTagLength;
  84. using internal::LITERAL;
  85. // We translate the information encoded in a tag through a lookup table to a
  86. // format that requires fewer instructions to decode. Effectively we store
  87. // the length minus the tag part of the offset. The lowest significant byte
  88. // thus stores the length. While total length - offset is given by
  89. // entry - ExtractOffset(type). The nice thing is that the subtraction
  90. // immediately sets the flags for the necessary check that offset >= length.
  91. // This folds the cmp with sub. We engineer the long literals and copy-4 to
  92. // always fail this check, so their presence doesn't affect the fast path.
  93. // To prevent literals from triggering the guard against offset < length (offset
  94. // does not apply to literals) the table is giving them a spurious offset of
  95. // 256.
  96. inline constexpr int16_t MakeEntry(int16_t len, int16_t offset) {
  97. return len - (offset << 8);
  98. }
  99. inline constexpr int16_t LengthMinusOffset(int data, int type) {
  100. return type == 3 ? 0xFF // copy-4 (or type == 3)
  101. : type == 2 ? MakeEntry(data + 1, 0) // copy-2
  102. : type == 1 ? MakeEntry((data & 7) + 4, data >> 3) // copy-1
  103. : data < 60 ? MakeEntry(data + 1, 1) // note spurious offset.
  104. : 0xFF; // long literal
  105. }
  106. inline constexpr int16_t LengthMinusOffset(uint8_t tag) {
  107. return LengthMinusOffset(tag >> 2, tag & 3);
  108. }
  109. template <size_t... Ints>
  110. struct index_sequence {};
  111. template <std::size_t N, size_t... Is>
  112. struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {};
  113. template <size_t... Is>
  114. struct make_index_sequence<0, Is...> : index_sequence<Is...> {};
  115. template <size_t... seq>
  116. constexpr std::array<int16_t, 256> MakeTable(index_sequence<seq...>) {
  117. return std::array<int16_t, 256>{LengthMinusOffset(seq)...};
  118. }
  119. // We maximally co-locate the two tables so that only one register needs to be
  120. // reserved for the table address.
  121. struct {
  122. alignas(64) const std::array<int16_t, 256> length_minus_offset;
  123. uint32_t extract_masks[4]; // Used for extracting offset based on tag type.
  124. } table = {MakeTable(make_index_sequence<256>{}), {0, 0xFF, 0xFFFF, 0}};
  125. // Any hash function will produce a valid compressed bitstream, but a good
  126. // hash function reduces the number of collisions and thus yields better
  127. // compression for compressible input, and more speed for incompressible
  128. // input. Of course, it doesn't hurt if the hash function is reasonably fast
  129. // either, as it gets called a lot.
  130. inline uint32_t HashBytes(uint32_t bytes, uint32_t mask) {
  131. constexpr uint32_t kMagic = 0x1e35a7bd;
  132. return ((kMagic * bytes) >> (32 - kMaxHashTableBits)) & mask;
  133. }
  134. } // namespace
  135. size_t MaxCompressedLength(size_t source_bytes) {
  136. // Compressed data can be defined as:
  137. // compressed := item* literal*
  138. // item := literal* copy
  139. //
  140. // The trailing literal sequence has a space blowup of at most 62/60
  141. // since a literal of length 60 needs one tag byte + one extra byte
  142. // for length information.
  143. //
  144. // Item blowup is trickier to measure. Suppose the "copy" op copies
  145. // 4 bytes of data. Because of a special check in the encoding code,
  146. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  147. // the copy op takes 3 bytes to encode, and this type of item leads
  148. // to at most the 62/60 blowup for representing literals.
  149. //
  150. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  151. // enough, it will take 5 bytes to encode the copy op. Therefore the
  152. // worst case here is a one-byte literal followed by a five-byte copy.
  153. // I.e., 6 bytes of input turn into 7 bytes of "compressed" data.
  154. //
  155. // This last factor dominates the blowup, so the final estimate is:
  156. return 32 + source_bytes + source_bytes / 6;
  157. }
  158. namespace {
  159. void UnalignedCopy64(const void* src, void* dst) {
  160. char tmp[8];
  161. std::memcpy(tmp, src, 8);
  162. std::memcpy(dst, tmp, 8);
  163. }
  164. void UnalignedCopy128(const void* src, void* dst) {
  165. // std::memcpy() gets vectorized when the appropriate compiler options are
  166. // used. For example, x86 compilers targeting SSE2+ will optimize to an SSE2
  167. // load and store.
  168. char tmp[16];
  169. std::memcpy(tmp, src, 16);
  170. std::memcpy(dst, tmp, 16);
  171. }
  172. template <bool use_16bytes_chunk>
  173. inline void ConditionalUnalignedCopy128(const char* src, char* dst) {
  174. if (use_16bytes_chunk) {
  175. UnalignedCopy128(src, dst);
  176. } else {
  177. UnalignedCopy64(src, dst);
  178. UnalignedCopy64(src + 8, dst + 8);
  179. }
  180. }
  181. // Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used
  182. // for handling COPY operations where the input and output regions may overlap.
  183. // For example, suppose:
  184. // src == "ab"
  185. // op == src + 2
  186. // op_limit == op + 20
  187. // After IncrementalCopySlow(src, op, op_limit), the result will have eleven
  188. // copies of "ab"
  189. // ababababababababababab
  190. // Note that this does not match the semantics of either std::memcpy() or
  191. // std::memmove().
  192. inline char* IncrementalCopySlow(const char* src, char* op,
  193. char* const op_limit) {
  194. // TODO: Remove pragma when LLVM is aware this
  195. // function is only called in cold regions and when cold regions don't get
  196. // vectorized or unrolled.
  197. #ifdef __clang__
  198. #pragma clang loop unroll(disable)
  199. #endif
  200. while (op < op_limit) {
  201. *op++ = *src++;
  202. }
  203. return op_limit;
  204. }
  205. #if SNAPPY_HAVE_SSSE3
  206. // Computes the bytes for shuffle control mask (please read comments on
  207. // 'pattern_generation_masks' as well) for the given index_offset and
  208. // pattern_size. For example, when the 'offset' is 6, it will generate a
  209. // repeating pattern of size 6. So, the first 16 byte indexes will correspond to
  210. // the pattern-bytes {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3} and the
  211. // next 16 byte indexes will correspond to the pattern-bytes {4, 5, 0, 1, 2, 3,
  212. // 4, 5, 0, 1, 2, 3, 4, 5, 0, 1}. These byte index sequences are generated by
  213. // calling MakePatternMaskBytes(0, 6, index_sequence<16>()) and
  214. // MakePatternMaskBytes(16, 6, index_sequence<16>()) respectively.
  215. template <size_t... indexes>
  216. inline constexpr std::array<char, sizeof...(indexes)> MakePatternMaskBytes(
  217. int index_offset, int pattern_size, index_sequence<indexes...>) {
  218. return {static_cast<char>((index_offset + indexes) % pattern_size)...};
  219. }
  220. // Computes the shuffle control mask bytes array for given pattern-sizes and
  221. // returns an array.
  222. template <size_t... pattern_sizes_minus_one>
  223. inline constexpr std::array<std::array<char, sizeof(__m128i)>,
  224. sizeof...(pattern_sizes_minus_one)>
  225. MakePatternMaskBytesTable(int index_offset,
  226. index_sequence<pattern_sizes_minus_one...>) {
  227. return {MakePatternMaskBytes(
  228. index_offset, pattern_sizes_minus_one + 1,
  229. make_index_sequence</*indexes=*/sizeof(__m128i)>())...};
  230. }
  231. // This is an array of shuffle control masks that can be used as the source
  232. // operand for PSHUFB to permute the contents of the destination XMM register
  233. // into a repeating byte pattern.
  234. alignas(16) constexpr std::array<std::array<char, sizeof(__m128i)>,
  235. 16> pattern_generation_masks =
  236. MakePatternMaskBytesTable(
  237. /*index_offset=*/0,
  238. /*pattern_sizes_minus_one=*/make_index_sequence<16>());
  239. // Similar to 'pattern_generation_masks', this table is used to "rotate" the
  240. // pattern so that we can copy the *next 16 bytes* consistent with the pattern.
  241. // Basically, pattern_reshuffle_masks is a continuation of
  242. // pattern_generation_masks. It follows that, pattern_reshuffle_masks is same as
  243. // pattern_generation_masks for offsets 1, 2, 4, 8 and 16.
  244. alignas(16) constexpr std::array<std::array<char, sizeof(__m128i)>,
  245. 16> pattern_reshuffle_masks =
  246. MakePatternMaskBytesTable(
  247. /*index_offset=*/16,
  248. /*pattern_sizes_minus_one=*/make_index_sequence<16>());
  249. SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  250. static inline __m128i LoadPattern(const char* src, const size_t pattern_size) {
  251. __m128i generation_mask = _mm_load_si128(reinterpret_cast<const __m128i*>(
  252. pattern_generation_masks[pattern_size - 1].data()));
  253. // Uninitialized bytes are masked out by the shuffle mask.
  254. // TODO: remove annotation and macro defs once MSan is fixed.
  255. SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(src + pattern_size, 16 - pattern_size);
  256. return _mm_shuffle_epi8(
  257. _mm_loadu_si128(reinterpret_cast<const __m128i*>(src)), generation_mask);
  258. }
  259. SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  260. static inline std::pair<__m128i /* pattern */, __m128i /* reshuffle_mask */>
  261. LoadPatternAndReshuffleMask(const char* src, const size_t pattern_size) {
  262. __m128i pattern = LoadPattern(src, pattern_size);
  263. // This mask will generate the next 16 bytes in-place. Doing so enables us to
  264. // write data by at most 4 _mm_storeu_si128.
  265. //
  266. // For example, suppose pattern is: abcdefabcdefabcd
  267. // Shuffling with this mask will generate: efabcdefabcdefab
  268. // Shuffling again will generate: cdefabcdefabcdef
  269. __m128i reshuffle_mask = _mm_load_si128(reinterpret_cast<const __m128i*>(
  270. pattern_reshuffle_masks[pattern_size - 1].data()));
  271. return {pattern, reshuffle_mask};
  272. }
  273. #endif // SNAPPY_HAVE_SSSE3
  274. // Fallback for when we need to copy while extending the pattern, for example
  275. // copying 10 bytes from 3 positions back abc -> abcabcabcabca.
  276. //
  277. // REQUIRES: [dst - offset, dst + 64) is a valid address range.
  278. SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  279. static inline bool Copy64BytesWithPatternExtension(char* dst, size_t offset) {
  280. #if SNAPPY_HAVE_SSSE3
  281. if (SNAPPY_PREDICT_TRUE(offset <= 16)) {
  282. switch (offset) {
  283. case 0:
  284. return false;
  285. case 1: {
  286. std::memset(dst, dst[-1], 64);
  287. return true;
  288. }
  289. case 2:
  290. case 4:
  291. case 8:
  292. case 16: {
  293. __m128i pattern = LoadPattern(dst - offset, offset);
  294. for (int i = 0; i < 4; i++) {
  295. _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 16 * i), pattern);
  296. }
  297. return true;
  298. }
  299. default: {
  300. auto pattern_and_reshuffle_mask =
  301. LoadPatternAndReshuffleMask(dst - offset, offset);
  302. __m128i pattern = pattern_and_reshuffle_mask.first;
  303. __m128i reshuffle_mask = pattern_and_reshuffle_mask.second;
  304. for (int i = 0; i < 4; i++) {
  305. _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 16 * i), pattern);
  306. pattern = _mm_shuffle_epi8(pattern, reshuffle_mask);
  307. }
  308. return true;
  309. }
  310. }
  311. }
  312. #else
  313. if (SNAPPY_PREDICT_TRUE(offset < 16)) {
  314. if (SNAPPY_PREDICT_FALSE(offset == 0)) return false;
  315. // Extend the pattern to the first 16 bytes.
  316. for (int i = 0; i < 16; i++) dst[i] = dst[i - offset];
  317. // Find a multiple of pattern >= 16.
  318. static std::array<uint8_t, 16> pattern_sizes = []() {
  319. std::array<uint8_t, 16> res;
  320. for (int i = 1; i < 16; i++) res[i] = (16 / i + 1) * i;
  321. return res;
  322. }();
  323. offset = pattern_sizes[offset];
  324. for (int i = 1; i < 4; i++) {
  325. std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
  326. }
  327. return true;
  328. }
  329. #endif // SNAPPY_HAVE_SSSE3
  330. // Very rare.
  331. for (int i = 0; i < 4; i++) {
  332. std::memcpy(dst + i * 16, dst + i * 16 - offset, 16);
  333. }
  334. return true;
  335. }
  336. // Copy [src, src+(op_limit-op)) to [op, op_limit) but faster than
  337. // IncrementalCopySlow. buf_limit is the address past the end of the writable
  338. // region of the buffer.
  339. inline char* IncrementalCopy(const char* src, char* op, char* const op_limit,
  340. char* const buf_limit) {
  341. #if SNAPPY_HAVE_SSSE3
  342. constexpr int big_pattern_size_lower_bound = 16;
  343. #else
  344. constexpr int big_pattern_size_lower_bound = 8;
  345. #endif
  346. // Terminology:
  347. //
  348. // slop = buf_limit - op
  349. // pat = op - src
  350. // len = op_limit - op
  351. assert(src < op);
  352. assert(op < op_limit);
  353. assert(op_limit <= buf_limit);
  354. // NOTE: The copy tags use 3 or 6 bits to store the copy length, so len <= 64.
  355. assert(op_limit - op <= 64);
  356. // NOTE: In practice the compressor always emits len >= 4, so it is ok to
  357. // assume that to optimize this function, but this is not guaranteed by the
  358. // compression format, so we have to also handle len < 4 in case the input
  359. // does not satisfy these conditions.
  360. size_t pattern_size = op - src;
  361. // The cases are split into different branches to allow the branch predictor,
  362. // FDO, and static prediction hints to work better. For each input we list the
  363. // ratio of invocations that match each condition.
  364. //
  365. // input slop < 16 pat < 8 len > 16
  366. // ------------------------------------------
  367. // html|html4|cp 0% 1.01% 27.73%
  368. // urls 0% 0.88% 14.79%
  369. // jpg 0% 64.29% 7.14%
  370. // pdf 0% 2.56% 58.06%
  371. // txt[1-4] 0% 0.23% 0.97%
  372. // pb 0% 0.96% 13.88%
  373. // bin 0.01% 22.27% 41.17%
  374. //
  375. // It is very rare that we don't have enough slop for doing block copies. It
  376. // is also rare that we need to expand a pattern. Small patterns are common
  377. // for incompressible formats and for those we are plenty fast already.
  378. // Lengths are normally not greater than 16 but they vary depending on the
  379. // input. In general if we always predict len <= 16 it would be an ok
  380. // prediction.
  381. //
  382. // In order to be fast we want a pattern >= 16 bytes (or 8 bytes in non-SSE)
  383. // and an unrolled loop copying 1x 16 bytes (or 2x 8 bytes in non-SSE) at a
  384. // time.
  385. // Handle the uncommon case where pattern is less than 16 (or 8 in non-SSE)
  386. // bytes.
  387. if (pattern_size < big_pattern_size_lower_bound) {
  388. #if SNAPPY_HAVE_SSSE3
  389. // Load the first eight bytes into an 128-bit XMM register, then use PSHUFB
  390. // to permute the register's contents in-place into a repeating sequence of
  391. // the first "pattern_size" bytes.
  392. // For example, suppose:
  393. // src == "abc"
  394. // op == op + 3
  395. // After _mm_shuffle_epi8(), "pattern" will have five copies of "abc"
  396. // followed by one byte of slop: abcabcabcabcabca.
  397. //
  398. // The non-SSE fallback implementation suffers from store-forwarding stalls
  399. // because its loads and stores partly overlap. By expanding the pattern
  400. // in-place, we avoid the penalty.
  401. // Typically, the op_limit is the gating factor so try to simplify the loop
  402. // based on that.
  403. if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 15)) {
  404. auto pattern_and_reshuffle_mask =
  405. LoadPatternAndReshuffleMask(src, pattern_size);
  406. __m128i pattern = pattern_and_reshuffle_mask.first;
  407. __m128i reshuffle_mask = pattern_and_reshuffle_mask.second;
  408. // There is at least one, and at most four 16-byte blocks. Writing four
  409. // conditionals instead of a loop allows FDO to layout the code with
  410. // respect to the actual probabilities of each length.
  411. // TODO: Replace with loop with trip count hint.
  412. _mm_storeu_si128(reinterpret_cast<__m128i*>(op), pattern);
  413. if (op + 16 < op_limit) {
  414. pattern = _mm_shuffle_epi8(pattern, reshuffle_mask);
  415. _mm_storeu_si128(reinterpret_cast<__m128i*>(op + 16), pattern);
  416. }
  417. if (op + 32 < op_limit) {
  418. pattern = _mm_shuffle_epi8(pattern, reshuffle_mask);
  419. _mm_storeu_si128(reinterpret_cast<__m128i*>(op + 32), pattern);
  420. }
  421. if (op + 48 < op_limit) {
  422. pattern = _mm_shuffle_epi8(pattern, reshuffle_mask);
  423. _mm_storeu_si128(reinterpret_cast<__m128i*>(op + 48), pattern);
  424. }
  425. return op_limit;
  426. }
  427. char* const op_end = buf_limit - 15;
  428. if (SNAPPY_PREDICT_TRUE(op < op_end)) {
  429. auto pattern_and_reshuffle_mask =
  430. LoadPatternAndReshuffleMask(src, pattern_size);
  431. __m128i pattern = pattern_and_reshuffle_mask.first;
  432. __m128i reshuffle_mask = pattern_and_reshuffle_mask.second;
  433. // This code path is relatively cold however so we save code size
  434. // by avoiding unrolling and vectorizing.
  435. //
  436. // TODO: Remove pragma when when cold regions don't get
  437. // vectorized or unrolled.
  438. #ifdef __clang__
  439. #pragma clang loop unroll(disable)
  440. #endif
  441. do {
  442. _mm_storeu_si128(reinterpret_cast<__m128i*>(op), pattern);
  443. pattern = _mm_shuffle_epi8(pattern, reshuffle_mask);
  444. op += 16;
  445. } while (SNAPPY_PREDICT_TRUE(op < op_end));
  446. }
  447. return IncrementalCopySlow(op - pattern_size, op, op_limit);
  448. #else // !SNAPPY_HAVE_SSSE3
  449. // If plenty of buffer space remains, expand the pattern to at least 8
  450. // bytes. The way the following loop is written, we need 8 bytes of buffer
  451. // space if pattern_size >= 4, 11 bytes if pattern_size is 1 or 3, and 10
  452. // bytes if pattern_size is 2. Precisely encoding that is probably not
  453. // worthwhile; instead, invoke the slow path if we cannot write 11 bytes
  454. // (because 11 are required in the worst case).
  455. if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) {
  456. while (pattern_size < 8) {
  457. UnalignedCopy64(src, op);
  458. op += pattern_size;
  459. pattern_size *= 2;
  460. }
  461. if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
  462. } else {
  463. return IncrementalCopySlow(src, op, op_limit);
  464. }
  465. #endif // SNAPPY_HAVE_SSSE3
  466. }
  467. assert(pattern_size >= big_pattern_size_lower_bound);
  468. constexpr bool use_16bytes_chunk = big_pattern_size_lower_bound == 16;
  469. // Copy 1x 16 bytes (or 2x 8 bytes in non-SSE) at a time. Because op - src can
  470. // be < 16 in non-SSE, a single UnalignedCopy128 might overwrite data in op.
  471. // UnalignedCopy64 is safe because expanding the pattern to at least 8 bytes
  472. // guarantees that op - src >= 8.
  473. //
  474. // Typically, the op_limit is the gating factor so try to simplify the loop
  475. // based on that.
  476. if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 15)) {
  477. // There is at least one, and at most four 16-byte blocks. Writing four
  478. // conditionals instead of a loop allows FDO to layout the code with respect
  479. // to the actual probabilities of each length.
  480. // TODO: Replace with loop with trip count hint.
  481. ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
  482. if (op + 16 < op_limit) {
  483. ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 16, op + 16);
  484. }
  485. if (op + 32 < op_limit) {
  486. ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 32, op + 32);
  487. }
  488. if (op + 48 < op_limit) {
  489. ConditionalUnalignedCopy128<use_16bytes_chunk>(src + 48, op + 48);
  490. }
  491. return op_limit;
  492. }
  493. // Fall back to doing as much as we can with the available slop in the
  494. // buffer. This code path is relatively cold however so we save code size by
  495. // avoiding unrolling and vectorizing.
  496. //
  497. // TODO: Remove pragma when when cold regions don't get vectorized
  498. // or unrolled.
  499. #ifdef __clang__
  500. #pragma clang loop unroll(disable)
  501. #endif
  502. for (char* op_end = buf_limit - 16; op < op_end; op += 16, src += 16) {
  503. ConditionalUnalignedCopy128<use_16bytes_chunk>(src, op);
  504. }
  505. if (op >= op_limit) return op_limit;
  506. // We only take this branch if we didn't have enough slop and we can do a
  507. // single 8 byte copy.
  508. if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) {
  509. UnalignedCopy64(src, op);
  510. src += 8;
  511. op += 8;
  512. }
  513. return IncrementalCopySlow(src, op, op_limit);
  514. }
  515. } // namespace
  516. template <bool allow_fast_path>
  517. static inline char* EmitLiteral(char* op, const char* literal, int len) {
  518. // The vast majority of copies are below 16 bytes, for which a
  519. // call to std::memcpy() is overkill. This fast path can sometimes
  520. // copy up to 15 bytes too much, but that is okay in the
  521. // main loop, since we have a bit to go on for both sides:
  522. //
  523. // - The input will always have kInputMarginBytes = 15 extra
  524. // available bytes, as long as we're in the main loop, and
  525. // if not, allow_fast_path = false.
  526. // - The output will always have 32 spare bytes (see
  527. // MaxCompressedLength).
  528. assert(len > 0); // Zero-length literals are disallowed
  529. int n = len - 1;
  530. if (allow_fast_path && len <= 16) {
  531. // Fits in tag byte
  532. *op++ = LITERAL | (n << 2);
  533. UnalignedCopy128(literal, op);
  534. return op + len;
  535. }
  536. if (n < 60) {
  537. // Fits in tag byte
  538. *op++ = LITERAL | (n << 2);
  539. } else {
  540. int count = (Bits::Log2Floor(n) >> 3) + 1;
  541. assert(count >= 1);
  542. assert(count <= 4);
  543. *op++ = LITERAL | ((59 + count) << 2);
  544. // Encode in upcoming bytes.
  545. // Write 4 bytes, though we may care about only 1 of them. The output buffer
  546. // is guaranteed to have at least 3 more spaces left as 'len >= 61' holds
  547. // here and there is a std::memcpy() of size 'len' below.
  548. LittleEndian::Store32(op, n);
  549. op += count;
  550. }
  551. std::memcpy(op, literal, len);
  552. return op + len;
  553. }
  554. template <bool len_less_than_12>
  555. static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
  556. assert(len <= 64);
  557. assert(len >= 4);
  558. assert(offset < 65536);
  559. assert(len_less_than_12 == (len < 12));
  560. if (len_less_than_12) {
  561. uint32_t u = (len << 2) + (offset << 8);
  562. uint32_t copy1 = COPY_1_BYTE_OFFSET - (4 << 2) + ((offset >> 3) & 0xe0);
  563. uint32_t copy2 = COPY_2_BYTE_OFFSET - (1 << 2);
  564. // It turns out that offset < 2048 is a difficult to predict branch.
  565. // `perf record` shows this is the highest percentage of branch misses in
  566. // benchmarks. This code produces branch free code, the data dependency
  567. // chain that bottlenecks the throughput is so long that a few extra
  568. // instructions are completely free (IPC << 6 because of data deps).
  569. u += offset < 2048 ? copy1 : copy2;
  570. LittleEndian::Store32(op, u);
  571. op += offset < 2048 ? 2 : 3;
  572. } else {
  573. // Write 4 bytes, though we only care about 3 of them. The output buffer
  574. // is required to have some slack, so the extra byte won't overrun it.
  575. uint32_t u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
  576. LittleEndian::Store32(op, u);
  577. op += 3;
  578. }
  579. return op;
  580. }
  581. template <bool len_less_than_12>
  582. static inline char* EmitCopy(char* op, size_t offset, size_t len) {
  583. assert(len_less_than_12 == (len < 12));
  584. if (len_less_than_12) {
  585. return EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
  586. } else {
  587. // A special case for len <= 64 might help, but so far measurements suggest
  588. // it's in the noise.
  589. // Emit 64 byte copies but make sure to keep at least four bytes reserved.
  590. while (SNAPPY_PREDICT_FALSE(len >= 68)) {
  591. op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 64);
  592. len -= 64;
  593. }
  594. // One or two copies will now finish the job.
  595. if (len > 64) {
  596. op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, 60);
  597. len -= 60;
  598. }
  599. // Emit remainder.
  600. if (len < 12) {
  601. op = EmitCopyAtMost64</*len_less_than_12=*/true>(op, offset, len);
  602. } else {
  603. op = EmitCopyAtMost64</*len_less_than_12=*/false>(op, offset, len);
  604. }
  605. return op;
  606. }
  607. }
  608. bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
  609. uint32_t v = 0;
  610. const char* limit = start + n;
  611. if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
  612. *result = v;
  613. return true;
  614. } else {
  615. return false;
  616. }
  617. }
  618. namespace {
  619. uint32_t CalculateTableSize(uint32_t input_size) {
  620. static_assert(
  621. kMaxHashTableSize >= kMinHashTableSize,
  622. "kMaxHashTableSize should be greater or equal to kMinHashTableSize.");
  623. if (input_size > kMaxHashTableSize) {
  624. return kMaxHashTableSize;
  625. }
  626. if (input_size < kMinHashTableSize) {
  627. return kMinHashTableSize;
  628. }
  629. // This is equivalent to Log2Ceiling(input_size), assuming input_size > 1.
  630. // 2 << Log2Floor(x - 1) is equivalent to 1 << (1 + Log2Floor(x - 1)).
  631. return 2u << Bits::Log2Floor(input_size - 1);
  632. }
  633. } // namespace
  634. namespace internal {
  635. WorkingMemory::WorkingMemory(size_t input_size) {
  636. const size_t max_fragment_size = std::min(input_size, kBlockSize);
  637. const size_t table_size = CalculateTableSize(max_fragment_size);
  638. size_ = table_size * sizeof(*table_) + max_fragment_size +
  639. MaxCompressedLength(max_fragment_size);
  640. mem_ = std::allocator<char>().allocate(size_);
  641. table_ = reinterpret_cast<uint16_t*>(mem_);
  642. input_ = mem_ + table_size * sizeof(*table_);
  643. output_ = input_ + max_fragment_size;
  644. }
  645. WorkingMemory::~WorkingMemory() {
  646. std::allocator<char>().deallocate(mem_, size_);
  647. }
  648. uint16_t* WorkingMemory::GetHashTable(size_t fragment_size,
  649. int* table_size) const {
  650. const size_t htsize = CalculateTableSize(fragment_size);
  651. memset(table_, 0, htsize * sizeof(*table_));
  652. *table_size = htsize;
  653. return table_;
  654. }
  655. } // end namespace internal
  656. // Flat array compression that does not emit the "uncompressed length"
  657. // prefix. Compresses "input" string to the "*op" buffer.
  658. //
  659. // REQUIRES: "input" is at most "kBlockSize" bytes long.
  660. // REQUIRES: "op" points to an array of memory that is at least
  661. // "MaxCompressedLength(input.size())" in size.
  662. // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
  663. // REQUIRES: "table_size" is a power of two
  664. //
  665. // Returns an "end" pointer into "op" buffer.
  666. // "end - op" is the compressed size of "input".
  667. namespace internal {
  668. char* CompressFragment(const char* input, size_t input_size, char* op,
  669. uint16_t* table, const int table_size) {
  670. // "ip" is the input pointer, and "op" is the output pointer.
  671. const char* ip = input;
  672. assert(input_size <= kBlockSize);
  673. assert((table_size & (table_size - 1)) == 0); // table must be power of two
  674. const uint32_t mask = table_size - 1;
  675. const char* ip_end = input + input_size;
  676. const char* base_ip = ip;
  677. const size_t kInputMarginBytes = 15;
  678. if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
  679. const char* ip_limit = input + input_size - kInputMarginBytes;
  680. for (uint32_t preload = LittleEndian::Load32(ip + 1);;) {
  681. // Bytes in [next_emit, ip) will be emitted as literal bytes. Or
  682. // [next_emit, ip_end) after the main loop.
  683. const char* next_emit = ip++;
  684. uint64_t data = LittleEndian::Load64(ip);
  685. // The body of this loop calls EmitLiteral once and then EmitCopy one or
  686. // more times. (The exception is that when we're close to exhausting
  687. // the input we goto emit_remainder.)
  688. //
  689. // In the first iteration of this loop we're just starting, so
  690. // there's nothing to copy, so calling EmitLiteral once is
  691. // necessary. And we only start a new iteration when the
  692. // current iteration has determined that a call to EmitLiteral will
  693. // precede the next call to EmitCopy (if any).
  694. //
  695. // Step 1: Scan forward in the input looking for a 4-byte-long match.
  696. // If we get close to exhausting the input then goto emit_remainder.
  697. //
  698. // Heuristic match skipping: If 32 bytes are scanned with no matches
  699. // found, start looking only at every other byte. If 32 more bytes are
  700. // scanned (or skipped), look at every third byte, etc.. When a match is
  701. // found, immediately go back to looking at every byte. This is a small
  702. // loss (~5% performance, ~0.1% density) for compressible data due to more
  703. // bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  704. // win since the compressor quickly "realizes" the data is incompressible
  705. // and doesn't bother looking for matches everywhere.
  706. //
  707. // The "skip" variable keeps track of how many bytes there are since the
  708. // last match; dividing it by 32 (ie. right-shifting by five) gives the
  709. // number of bytes to move ahead for each iteration.
  710. uint32_t skip = 32;
  711. const char* candidate;
  712. if (ip_limit - ip >= 16) {
  713. auto delta = ip - base_ip;
  714. for (int j = 0; j < 4; ++j) {
  715. for (int k = 0; k < 4; ++k) {
  716. int i = 4 * j + k;
  717. // These for-loops are meant to be unrolled. So we can freely
  718. // special case the first iteration to use the value already
  719. // loaded in preload.
  720. uint32_t dword = i == 0 ? preload : static_cast<uint32_t>(data);
  721. assert(dword == LittleEndian::Load32(ip + i));
  722. uint32_t hash = HashBytes(dword, mask);
  723. candidate = base_ip + table[hash];
  724. assert(candidate >= base_ip);
  725. assert(candidate < ip + i);
  726. table[hash] = delta + i;
  727. if (SNAPPY_PREDICT_FALSE(LittleEndian::Load32(candidate) == dword)) {
  728. *op = LITERAL | (i << 2);
  729. UnalignedCopy128(next_emit, op + 1);
  730. ip += i;
  731. op = op + i + 2;
  732. goto emit_match;
  733. }
  734. data >>= 8;
  735. }
  736. data = LittleEndian::Load64(ip + 4 * j + 4);
  737. }
  738. ip += 16;
  739. skip += 16;
  740. }
  741. while (true) {
  742. assert(static_cast<uint32_t>(data) == LittleEndian::Load32(ip));
  743. uint32_t hash = HashBytes(data, mask);
  744. uint32_t bytes_between_hash_lookups = skip >> 5;
  745. skip += bytes_between_hash_lookups;
  746. const char* next_ip = ip + bytes_between_hash_lookups;
  747. if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
  748. ip = next_emit;
  749. goto emit_remainder;
  750. }
  751. candidate = base_ip + table[hash];
  752. assert(candidate >= base_ip);
  753. assert(candidate < ip);
  754. table[hash] = ip - base_ip;
  755. if (SNAPPY_PREDICT_FALSE(static_cast<uint32_t>(data) ==
  756. LittleEndian::Load32(candidate))) {
  757. break;
  758. }
  759. data = LittleEndian::Load32(next_ip);
  760. ip = next_ip;
  761. }
  762. // Step 2: A 4-byte match has been found. We'll later see if more
  763. // than 4 bytes match. But, prior to the match, input
  764. // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes."
  765. assert(next_emit + 16 <= ip_end);
  766. op = EmitLiteral</*allow_fast_path=*/true>(op, next_emit, ip - next_emit);
  767. // Step 3: Call EmitCopy, and then see if another EmitCopy could
  768. // be our next move. Repeat until we find no match for the
  769. // input immediately after what was consumed by the last EmitCopy call.
  770. //
  771. // If we exit this loop normally then we need to call EmitLiteral next,
  772. // though we don't yet know how big the literal will be. We handle that
  773. // by proceeding to the next iteration of the main loop. We also can exit
  774. // this loop via goto if we get close to exhausting the input.
  775. emit_match:
  776. do {
  777. // We have a 4-byte match at ip, and no need to emit any
  778. // "literal bytes" prior to ip.
  779. const char* base = ip;
  780. std::pair<size_t, bool> p =
  781. FindMatchLength(candidate + 4, ip + 4, ip_end, &data);
  782. size_t matched = 4 + p.first;
  783. ip += matched;
  784. size_t offset = base - candidate;
  785. assert(0 == memcmp(base, candidate, matched));
  786. if (p.second) {
  787. op = EmitCopy</*len_less_than_12=*/true>(op, offset, matched);
  788. } else {
  789. op = EmitCopy</*len_less_than_12=*/false>(op, offset, matched);
  790. }
  791. if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
  792. goto emit_remainder;
  793. }
  794. // Expect 5 bytes to match
  795. assert((data & 0xFFFFFFFFFF) ==
  796. (LittleEndian::Load64(ip) & 0xFFFFFFFFFF));
  797. // We are now looking for a 4-byte match again. We read
  798. // table[Hash(ip, shift)] for that. To improve compression,
  799. // we also update table[Hash(ip - 1, mask)] and table[Hash(ip, mask)].
  800. table[HashBytes(LittleEndian::Load32(ip - 1), mask)] = ip - base_ip - 1;
  801. uint32_t hash = HashBytes(data, mask);
  802. candidate = base_ip + table[hash];
  803. table[hash] = ip - base_ip;
  804. // Measurements on the benchmarks have shown the following probabilities
  805. // for the loop to exit (ie. avg. number of iterations is reciprocal).
  806. // BM_Flat/6 txt1 p = 0.3-0.4
  807. // BM_Flat/7 txt2 p = 0.35
  808. // BM_Flat/8 txt3 p = 0.3-0.4
  809. // BM_Flat/9 txt3 p = 0.34-0.4
  810. // BM_Flat/10 pb p = 0.4
  811. // BM_Flat/11 gaviota p = 0.1
  812. // BM_Flat/12 cp p = 0.5
  813. // BM_Flat/13 c p = 0.3
  814. } while (static_cast<uint32_t>(data) == LittleEndian::Load32(candidate));
  815. // Because the least significant 5 bytes matched, we can utilize data
  816. // for the next iteration.
  817. preload = data >> 8;
  818. }
  819. }
  820. emit_remainder:
  821. // Emit the remaining bytes as a literal
  822. if (ip < ip_end) {
  823. op = EmitLiteral</*allow_fast_path=*/false>(op, ip, ip_end - ip);
  824. }
  825. return op;
  826. }
  827. } // end namespace internal
  828. // Called back at avery compression call to trace parameters and sizes.
  829. static inline void Report(const char *algorithm, size_t compressed_size,
  830. size_t uncompressed_size) {
  831. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  832. (void)algorithm;
  833. (void)compressed_size;
  834. (void)uncompressed_size;
  835. }
  836. // Signature of output types needed by decompression code.
  837. // The decompression code is templatized on a type that obeys this
  838. // signature so that we do not pay virtual function call overhead in
  839. // the middle of a tight decompression loop.
  840. //
  841. // class DecompressionWriter {
  842. // public:
  843. // // Called before decompression
  844. // void SetExpectedLength(size_t length);
  845. //
  846. // // For performance a writer may choose to donate the cursor variable to the
  847. // // decompression function. The decompression will inject it in all its
  848. // // function calls to the writer. Keeping the important output cursor as a
  849. // // function local stack variable allows the compiler to keep it in
  850. // // register, which greatly aids performance by avoiding loads and stores of
  851. // // this variable in the fast path loop iterations.
  852. // T GetOutputPtr() const;
  853. //
  854. // // At end of decompression the loop donates the ownership of the cursor
  855. // // variable back to the writer by calling this function.
  856. // void SetOutputPtr(T op);
  857. //
  858. // // Called after decompression
  859. // bool CheckLength() const;
  860. //
  861. // // Called repeatedly during decompression
  862. // // Each function get a pointer to the op (output pointer), that the writer
  863. // // can use and update. Note it's important that these functions get fully
  864. // // inlined so that no actual address of the local variable needs to be
  865. // // taken.
  866. // bool Append(const char* ip, size_t length, T* op);
  867. // bool AppendFromSelf(uint32_t offset, size_t length, T* op);
  868. //
  869. // // The rules for how TryFastAppend differs from Append are somewhat
  870. // // convoluted:
  871. // //
  872. // // - TryFastAppend is allowed to decline (return false) at any
  873. // // time, for any reason -- just "return false" would be
  874. // // a perfectly legal implementation of TryFastAppend.
  875. // // The intention is for TryFastAppend to allow a fast path
  876. // // in the common case of a small append.
  877. // // - TryFastAppend is allowed to read up to <available> bytes
  878. // // from the input buffer, whereas Append is allowed to read
  879. // // <length>. However, if it returns true, it must leave
  880. // // at least five (kMaximumTagLength) bytes in the input buffer
  881. // // afterwards, so that there is always enough space to read the
  882. // // next tag without checking for a refill.
  883. // // - TryFastAppend must always return decline (return false)
  884. // // if <length> is 61 or more, as in this case the literal length is not
  885. // // decoded fully. In practice, this should not be a big problem,
  886. // // as it is unlikely that one would implement a fast path accepting
  887. // // this much data.
  888. // //
  889. // bool TryFastAppend(const char* ip, size_t available, size_t length, T* op);
  890. // };
  891. static inline uint32_t ExtractLowBytes(uint32_t v, int n) {
  892. assert(n >= 0);
  893. assert(n <= 4);
  894. #if SNAPPY_HAVE_BMI2
  895. return _bzhi_u32(v, 8 * n);
  896. #else
  897. // This needs to be wider than uint32_t otherwise `mask << 32` will be
  898. // undefined.
  899. uint64_t mask = 0xffffffff;
  900. return v & ~(mask << (8 * n));
  901. #endif
  902. }
  903. static inline bool LeftShiftOverflows(uint8_t value, uint32_t shift) {
  904. assert(shift < 32);
  905. static const uint8_t masks[] = {
  906. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
  907. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
  908. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
  909. 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
  910. return (value & masks[shift]) != 0;
  911. }
  912. inline bool Copy64BytesWithPatternExtension(ptrdiff_t dst, size_t offset) {
  913. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  914. (void)dst;
  915. return offset != 0;
  916. }
  917. void MemCopy(char* dst, const uint8_t* src, size_t size) {
  918. std::memcpy(dst, src, size);
  919. }
  920. void MemCopy(ptrdiff_t dst, const uint8_t* src, size_t size) {
  921. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  922. (void)dst;
  923. (void)src;
  924. (void)size;
  925. }
  926. void MemMove(char* dst, const void* src, size_t size) {
  927. std::memmove(dst, src, size);
  928. }
  929. void MemMove(ptrdiff_t dst, const void* src, size_t size) {
  930. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  931. (void)dst;
  932. (void)src;
  933. (void)size;
  934. }
  935. SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  936. size_t AdvanceToNextTag(const uint8_t** ip_p, size_t* tag) {
  937. const uint8_t*& ip = *ip_p;
  938. // This section is crucial for the throughput of the decompression loop.
  939. // The latency of an iteration is fundamentally constrained by the
  940. // following data chain on ip.
  941. // ip -> c = Load(ip) -> ip1 = ip + 1 + (c & 3) -> ip = ip1 or ip2
  942. // ip2 = ip + 2 + (c >> 2)
  943. // This amounts to 8 cycles.
  944. // 5 (load) + 1 (c & 3) + 1 (lea ip1, [ip + (c & 3) + 1]) + 1 (cmov)
  945. size_t literal_len = *tag >> 2;
  946. size_t tag_type = *tag;
  947. bool is_literal;
  948. #if defined(__GNUC__) && defined(__x86_64__)
  949. // TODO clang misses the fact that the (c & 3) already correctly
  950. // sets the zero flag.
  951. asm("and $3, %k[tag_type]\n\t"
  952. : [tag_type] "+r"(tag_type), "=@ccz"(is_literal));
  953. #else
  954. tag_type &= 3;
  955. is_literal = (tag_type == 0);
  956. #endif
  957. // TODO
  958. // This is code is subtle. Loading the values first and then cmov has less
  959. // latency then cmov ip and then load. However clang would move the loads
  960. // in an optimization phase, volatile prevents this transformation.
  961. // Note that we have enough slop bytes (64) that the loads are always valid.
  962. size_t tag_literal =
  963. static_cast<const volatile uint8_t*>(ip)[1 + literal_len];
  964. size_t tag_copy = static_cast<const volatile uint8_t*>(ip)[tag_type];
  965. *tag = is_literal ? tag_literal : tag_copy;
  966. const uint8_t* ip_copy = ip + 1 + tag_type;
  967. const uint8_t* ip_literal = ip + 2 + literal_len;
  968. ip = is_literal ? ip_literal : ip_copy;
  969. #if defined(__GNUC__) && defined(__x86_64__)
  970. // TODO Clang is "optimizing" zero-extension (a totally free
  971. // operation) this means that after the cmov of tag, it emits another movzb
  972. // tag, byte(tag). It really matters as it's on the core chain. This dummy
  973. // asm, persuades clang to do the zero-extension at the load (it's automatic)
  974. // removing the expensive movzb.
  975. asm("" ::"r"(tag_copy));
  976. #endif
  977. return tag_type;
  978. }
  979. // Extract the offset for copy-1 and copy-2 returns 0 for literals or copy-4.
  980. inline uint32_t ExtractOffset(uint32_t val, size_t tag_type) {
  981. return val & table.extract_masks[tag_type];
  982. };
  983. // Core decompression loop, when there is enough data available.
  984. // Decompresses the input buffer [ip, ip_limit) into the output buffer
  985. // [op, op_limit_min_slop). Returning when either we are too close to the end
  986. // of the input buffer, or we exceed op_limit_min_slop or when a exceptional
  987. // tag is encountered (literal of length > 60) or a copy-4.
  988. // Returns {ip, op} at the points it stopped decoding.
  989. // TODO This function probably does not need to be inlined, as it
  990. // should decode large chunks at a time. This allows runtime dispatch to
  991. // implementations based on CPU capability (BMI2 / perhaps 32 / 64 byte memcpy).
  992. template <typename T>
  993. std::pair<const uint8_t*, ptrdiff_t> DecompressBranchless(
  994. const uint8_t* ip, const uint8_t* ip_limit, ptrdiff_t op, T op_base,
  995. ptrdiff_t op_limit_min_slop) {
  996. // We unroll the inner loop twice so we need twice the spare room.
  997. op_limit_min_slop -= kSlopBytes;
  998. if (2 * (kSlopBytes + 1) < ip_limit - ip && op < op_limit_min_slop) {
  999. const uint8_t* const ip_limit_min_slop = ip_limit - 2 * kSlopBytes - 1;
  1000. ip++;
  1001. // ip points just past the tag and we are touching at maximum kSlopBytes
  1002. // in an iteration.
  1003. size_t tag = ip[-1];
  1004. do {
  1005. // The throughput is limited by instructions, unrolling the inner loop
  1006. // twice reduces the amount of instructions checking limits and also
  1007. // leads to reduced mov's.
  1008. for (int i = 0; i < 2; i++) {
  1009. const uint8_t* old_ip = ip;
  1010. assert(tag == ip[-1]);
  1011. // For literals tag_type = 0, hence we will always obtain 0 from
  1012. // ExtractLowBytes. For literals offset will thus be kLiteralOffset.
  1013. ptrdiff_t len_min_offset = table.length_minus_offset[tag];
  1014. size_t tag_type = AdvanceToNextTag(&ip, &tag);
  1015. uint32_t next = LittleEndian::Load32(old_ip);
  1016. size_t len = len_min_offset & 0xFF;
  1017. len_min_offset -= ExtractOffset(next, tag_type);
  1018. if (SNAPPY_PREDICT_FALSE(len_min_offset > 0)) {
  1019. if (SNAPPY_PREDICT_FALSE(len & 0x80)) {
  1020. // Exceptional case (long literal or copy 4).
  1021. // Actually doing the copy here is negatively impacting the main
  1022. // loop due to compiler incorrectly allocating a register for
  1023. // this fallback. Hence we just break.
  1024. break_loop:
  1025. ip = old_ip;
  1026. goto exit;
  1027. }
  1028. // Only copy-1 or copy-2 tags can get here.
  1029. assert(tag_type == 1 || tag_type == 2);
  1030. std::ptrdiff_t delta = op + len_min_offset - len;
  1031. // Guard against copies before the buffer start.
  1032. if (SNAPPY_PREDICT_FALSE(delta < 0 ||
  1033. !Copy64BytesWithPatternExtension(
  1034. op_base + op, len - len_min_offset))) {
  1035. goto break_loop;
  1036. }
  1037. op += len;
  1038. continue;
  1039. }
  1040. std::ptrdiff_t delta = op + len_min_offset - len;
  1041. if (SNAPPY_PREDICT_FALSE(delta < 0)) {
  1042. #if defined(__GNUC__) && defined(__x86_64__)
  1043. // TODO
  1044. // When validating, both code path reduced to `op += len`. Ie. this
  1045. // becomes effectively
  1046. //
  1047. // if (delta < 0) if (tag_type != 0) goto break_loop;
  1048. // op += len;
  1049. //
  1050. // The compiler interchanges the predictable and almost always false
  1051. // first if-statement with the completely unpredictable second
  1052. // if-statement, putting an unpredictable branch on every iteration.
  1053. // This empty asm is worth almost 2x, which I think qualifies for an
  1054. // award for the most load-bearing empty statement.
  1055. asm("");
  1056. #endif
  1057. // Due to the spurious offset in literals have this will trigger
  1058. // at the start of a block when op is still smaller than 256.
  1059. if (tag_type != 0) goto break_loop;
  1060. MemCopy(op_base + op, old_ip, 64);
  1061. op += len;
  1062. continue;
  1063. }
  1064. // For copies we need to copy from op_base + delta, for literals
  1065. // we need to copy from ip instead of from the stream.
  1066. const void* from =
  1067. tag_type ? reinterpret_cast<void*>(op_base + delta) : old_ip;
  1068. MemMove(op_base + op, from, 64);
  1069. op += len;
  1070. }
  1071. } while (ip < ip_limit_min_slop && op < op_limit_min_slop);
  1072. exit:
  1073. ip--;
  1074. assert(ip <= ip_limit);
  1075. }
  1076. return {ip, op};
  1077. }
  1078. // Helper class for decompression
  1079. class SnappyDecompressor {
  1080. private:
  1081. Source* reader_; // Underlying source of bytes to decompress
  1082. const char* ip_; // Points to next buffered byte
  1083. const char* ip_limit_; // Points just past buffered bytes
  1084. // If ip < ip_limit_min_maxtaglen_ it's safe to read kMaxTagLength from
  1085. // buffer.
  1086. const char* ip_limit_min_maxtaglen_;
  1087. uint32_t peeked_; // Bytes peeked from reader (need to skip)
  1088. bool eof_; // Hit end of input without an error?
  1089. char scratch_[kMaximumTagLength]; // See RefillTag().
  1090. // Ensure that all of the tag metadata for the next tag is available
  1091. // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even
  1092. // if (ip_limit_ - ip_ < 5).
  1093. //
  1094. // Returns true on success, false on error or end of input.
  1095. bool RefillTag();
  1096. void ResetLimit(const char* ip) {
  1097. ip_limit_min_maxtaglen_ =
  1098. ip_limit_ - std::min<ptrdiff_t>(ip_limit_ - ip, kMaximumTagLength - 1);
  1099. }
  1100. public:
  1101. explicit SnappyDecompressor(Source* reader)
  1102. : reader_(reader), ip_(NULL), ip_limit_(NULL), peeked_(0), eof_(false) {}
  1103. ~SnappyDecompressor() {
  1104. // Advance past any bytes we peeked at from the reader
  1105. reader_->Skip(peeked_);
  1106. }
  1107. // Returns true iff we have hit the end of the input without an error.
  1108. bool eof() const { return eof_; }
  1109. // Read the uncompressed length stored at the start of the compressed data.
  1110. // On success, stores the length in *result and returns true.
  1111. // On failure, returns false.
  1112. bool ReadUncompressedLength(uint32_t* result) {
  1113. assert(ip_ == NULL); // Must not have read anything yet
  1114. // Length is encoded in 1..5 bytes
  1115. *result = 0;
  1116. uint32_t shift = 0;
  1117. while (true) {
  1118. if (shift >= 32) return false;
  1119. size_t n;
  1120. const char* ip = reader_->Peek(&n);
  1121. if (n == 0) return false;
  1122. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  1123. reader_->Skip(1);
  1124. uint32_t val = c & 0x7f;
  1125. if (LeftShiftOverflows(static_cast<uint8_t>(val), shift)) return false;
  1126. *result |= val << shift;
  1127. if (c < 128) {
  1128. break;
  1129. }
  1130. shift += 7;
  1131. }
  1132. return true;
  1133. }
  1134. // Process the next item found in the input.
  1135. // Returns true if successful, false on error or end of input.
  1136. template <class Writer>
  1137. #if defined(__GNUC__) && defined(__x86_64__)
  1138. __attribute__((aligned(32)))
  1139. #endif
  1140. void
  1141. DecompressAllTags(Writer* writer) {
  1142. const char* ip = ip_;
  1143. ResetLimit(ip);
  1144. auto op = writer->GetOutputPtr();
  1145. // We could have put this refill fragment only at the beginning of the loop.
  1146. // However, duplicating it at the end of each branch gives the compiler more
  1147. // scope to optimize the <ip_limit_ - ip> expression based on the local
  1148. // context, which overall increases speed.
  1149. #define MAYBE_REFILL() \
  1150. if (SNAPPY_PREDICT_FALSE(ip >= ip_limit_min_maxtaglen_)) { \
  1151. ip_ = ip; \
  1152. if (SNAPPY_PREDICT_FALSE(!RefillTag())) goto exit; \
  1153. ip = ip_; \
  1154. ResetLimit(ip); \
  1155. } \
  1156. preload = static_cast<uint8_t>(*ip)
  1157. // At the start of the for loop below the least significant byte of preload
  1158. // contains the tag.
  1159. uint32_t preload;
  1160. MAYBE_REFILL();
  1161. for (;;) {
  1162. {
  1163. ptrdiff_t op_limit_min_slop;
  1164. auto op_base = writer->GetBase(&op_limit_min_slop);
  1165. if (op_base) {
  1166. auto res =
  1167. DecompressBranchless(reinterpret_cast<const uint8_t*>(ip),
  1168. reinterpret_cast<const uint8_t*>(ip_limit_),
  1169. op - op_base, op_base, op_limit_min_slop);
  1170. ip = reinterpret_cast<const char*>(res.first);
  1171. op = op_base + res.second;
  1172. MAYBE_REFILL();
  1173. }
  1174. }
  1175. const uint8_t c = static_cast<uint8_t>(preload);
  1176. ip++;
  1177. // Ratio of iterations that have LITERAL vs non-LITERAL for different
  1178. // inputs.
  1179. //
  1180. // input LITERAL NON_LITERAL
  1181. // -----------------------------------
  1182. // html|html4|cp 23% 77%
  1183. // urls 36% 64%
  1184. // jpg 47% 53%
  1185. // pdf 19% 81%
  1186. // txt[1-4] 25% 75%
  1187. // pb 24% 76%
  1188. // bin 24% 76%
  1189. if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
  1190. size_t literal_length = (c >> 2) + 1u;
  1191. if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length, &op)) {
  1192. assert(literal_length < 61);
  1193. ip += literal_length;
  1194. // NOTE: There is no MAYBE_REFILL() here, as TryFastAppend()
  1195. // will not return true unless there's already at least five spare
  1196. // bytes in addition to the literal.
  1197. preload = static_cast<uint8_t>(*ip);
  1198. continue;
  1199. }
  1200. if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
  1201. // Long literal.
  1202. const size_t literal_length_length = literal_length - 60;
  1203. literal_length =
  1204. ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
  1205. 1;
  1206. ip += literal_length_length;
  1207. }
  1208. size_t avail = ip_limit_ - ip;
  1209. while (avail < literal_length) {
  1210. if (!writer->Append(ip, avail, &op)) goto exit;
  1211. literal_length -= avail;
  1212. reader_->Skip(peeked_);
  1213. size_t n;
  1214. ip = reader_->Peek(&n);
  1215. avail = n;
  1216. peeked_ = avail;
  1217. if (avail == 0) goto exit;
  1218. ip_limit_ = ip + avail;
  1219. ResetLimit(ip);
  1220. }
  1221. if (!writer->Append(ip, literal_length, &op)) goto exit;
  1222. ip += literal_length;
  1223. MAYBE_REFILL();
  1224. } else {
  1225. if (SNAPPY_PREDICT_FALSE((c & 3) == COPY_4_BYTE_OFFSET)) {
  1226. const size_t copy_offset = LittleEndian::Load32(ip);
  1227. const size_t length = (c >> 2) + 1;
  1228. ip += 4;
  1229. if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
  1230. } else {
  1231. const ptrdiff_t entry = table.length_minus_offset[c];
  1232. preload = LittleEndian::Load32(ip);
  1233. const uint32_t trailer = ExtractLowBytes(preload, c & 3);
  1234. const uint32_t length = entry & 0xff;
  1235. assert(length > 0);
  1236. // copy_offset/256 is encoded in bits 8..10. By just fetching
  1237. // those bits, we get copy_offset (since the bit-field starts at
  1238. // bit 8).
  1239. const uint32_t copy_offset = trailer - entry + length;
  1240. if (!writer->AppendFromSelf(copy_offset, length, &op)) goto exit;
  1241. ip += (c & 3);
  1242. // By using the result of the previous load we reduce the critical
  1243. // dependency chain of ip to 4 cycles.
  1244. preload >>= (c & 3) * 8;
  1245. if (ip < ip_limit_min_maxtaglen_) continue;
  1246. }
  1247. MAYBE_REFILL();
  1248. }
  1249. }
  1250. #undef MAYBE_REFILL
  1251. exit:
  1252. writer->SetOutputPtr(op);
  1253. }
  1254. };
  1255. constexpr uint32_t CalculateNeeded(uint8_t tag) {
  1256. return ((tag & 3) == 0 && tag >= (60 * 4))
  1257. ? (tag >> 2) - 58
  1258. : (0x05030201 >> ((tag * 8) & 31)) & 0xFF;
  1259. }
  1260. #if __cplusplus >= 201402L
  1261. constexpr bool VerifyCalculateNeeded() {
  1262. for (int i = 0; i < 1; i++) {
  1263. if (CalculateNeeded(i) != (char_table[i] >> 11) + 1) return false;
  1264. }
  1265. return true;
  1266. }
  1267. // Make sure CalculateNeeded is correct by verifying it against the established
  1268. // table encoding the number of added bytes needed.
  1269. static_assert(VerifyCalculateNeeded(), "");
  1270. #endif // c++14
  1271. bool SnappyDecompressor::RefillTag() {
  1272. const char* ip = ip_;
  1273. if (ip == ip_limit_) {
  1274. // Fetch a new fragment from the reader
  1275. reader_->Skip(peeked_); // All peeked bytes are used up
  1276. size_t n;
  1277. ip = reader_->Peek(&n);
  1278. peeked_ = n;
  1279. eof_ = (n == 0);
  1280. if (eof_) return false;
  1281. ip_limit_ = ip + n;
  1282. }
  1283. // Read the tag character
  1284. assert(ip < ip_limit_);
  1285. const unsigned char c = *(reinterpret_cast<const unsigned char*>(ip));
  1286. // At this point make sure that the data for the next tag is consecutive.
  1287. // For copy 1 this means the next 2 bytes (tag and 1 byte offset)
  1288. // For copy 2 the next 3 bytes (tag and 2 byte offset)
  1289. // For copy 4 the next 5 bytes (tag and 4 byte offset)
  1290. // For all small literals we only need 1 byte buf for literals 60...63 the
  1291. // length is encoded in 1...4 extra bytes.
  1292. const uint32_t needed = CalculateNeeded(c);
  1293. assert(needed <= sizeof(scratch_));
  1294. // Read more bytes from reader if needed
  1295. uint32_t nbuf = ip_limit_ - ip;
  1296. if (nbuf < needed) {
  1297. // Stitch together bytes from ip and reader to form the word
  1298. // contents. We store the needed bytes in "scratch_". They
  1299. // will be consumed immediately by the caller since we do not
  1300. // read more than we need.
  1301. std::memmove(scratch_, ip, nbuf);
  1302. reader_->Skip(peeked_); // All peeked bytes are used up
  1303. peeked_ = 0;
  1304. while (nbuf < needed) {
  1305. size_t length;
  1306. const char* src = reader_->Peek(&length);
  1307. if (length == 0) return false;
  1308. uint32_t to_add = std::min<uint32_t>(needed - nbuf, length);
  1309. std::memcpy(scratch_ + nbuf, src, to_add);
  1310. nbuf += to_add;
  1311. reader_->Skip(to_add);
  1312. }
  1313. assert(nbuf == needed);
  1314. ip_ = scratch_;
  1315. ip_limit_ = scratch_ + needed;
  1316. } else if (nbuf < kMaximumTagLength) {
  1317. // Have enough bytes, but move into scratch_ so that we do not
  1318. // read past end of input
  1319. std::memmove(scratch_, ip, nbuf);
  1320. reader_->Skip(peeked_); // All peeked bytes are used up
  1321. peeked_ = 0;
  1322. ip_ = scratch_;
  1323. ip_limit_ = scratch_ + nbuf;
  1324. } else {
  1325. // Pass pointer to buffer returned by reader_.
  1326. ip_ = ip;
  1327. }
  1328. return true;
  1329. }
  1330. template <typename Writer>
  1331. static bool InternalUncompress(Source* r, Writer* writer) {
  1332. // Read the uncompressed length from the front of the compressed input
  1333. SnappyDecompressor decompressor(r);
  1334. uint32_t uncompressed_len = 0;
  1335. if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
  1336. return InternalUncompressAllTags(&decompressor, writer, r->Available(),
  1337. uncompressed_len);
  1338. }
  1339. template <typename Writer>
  1340. static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
  1341. Writer* writer, uint32_t compressed_len,
  1342. uint32_t uncompressed_len) {
  1343. Report("snappy_uncompress", compressed_len, uncompressed_len);
  1344. writer->SetExpectedLength(uncompressed_len);
  1345. // Process the entire input
  1346. decompressor->DecompressAllTags(writer);
  1347. writer->Flush();
  1348. return (decompressor->eof() && writer->CheckLength());
  1349. }
  1350. bool GetUncompressedLength(Source* source, uint32_t* result) {
  1351. SnappyDecompressor decompressor(source);
  1352. return decompressor.ReadUncompressedLength(result);
  1353. }
  1354. size_t Compress(Source* reader, Sink* writer) {
  1355. size_t written = 0;
  1356. size_t N = reader->Available();
  1357. const size_t uncompressed_size = N;
  1358. char ulength[Varint::kMax32];
  1359. char* p = Varint::Encode32(ulength, N);
  1360. writer->Append(ulength, p - ulength);
  1361. written += (p - ulength);
  1362. internal::WorkingMemory wmem(N);
  1363. while (N > 0) {
  1364. // Get next block to compress (without copying if possible)
  1365. size_t fragment_size;
  1366. const char* fragment = reader->Peek(&fragment_size);
  1367. assert(fragment_size != 0); // premature end of input
  1368. const size_t num_to_read = std::min(N, kBlockSize);
  1369. size_t bytes_read = fragment_size;
  1370. size_t pending_advance = 0;
  1371. if (bytes_read >= num_to_read) {
  1372. // Buffer returned by reader is large enough
  1373. pending_advance = num_to_read;
  1374. fragment_size = num_to_read;
  1375. } else {
  1376. char* scratch = wmem.GetScratchInput();
  1377. std::memcpy(scratch, fragment, bytes_read);
  1378. reader->Skip(bytes_read);
  1379. while (bytes_read < num_to_read) {
  1380. fragment = reader->Peek(&fragment_size);
  1381. size_t n = std::min<size_t>(fragment_size, num_to_read - bytes_read);
  1382. std::memcpy(scratch + bytes_read, fragment, n);
  1383. bytes_read += n;
  1384. reader->Skip(n);
  1385. }
  1386. assert(bytes_read == num_to_read);
  1387. fragment = scratch;
  1388. fragment_size = num_to_read;
  1389. }
  1390. assert(fragment_size == num_to_read);
  1391. // Get encoding table for compression
  1392. int table_size;
  1393. uint16_t* table = wmem.GetHashTable(num_to_read, &table_size);
  1394. // Compress input_fragment and append to dest
  1395. const int max_output = MaxCompressedLength(num_to_read);
  1396. // Need a scratch buffer for the output, in case the byte sink doesn't
  1397. // have room for us directly.
  1398. // Since we encode kBlockSize regions followed by a region
  1399. // which is <= kBlockSize in length, a previously allocated
  1400. // scratch_output[] region is big enough for this iteration.
  1401. char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput());
  1402. char* end = internal::CompressFragment(fragment, fragment_size, dest, table,
  1403. table_size);
  1404. writer->Append(dest, end - dest);
  1405. written += (end - dest);
  1406. N -= num_to_read;
  1407. reader->Skip(pending_advance);
  1408. }
  1409. Report("snappy_compress", written, uncompressed_size);
  1410. return written;
  1411. }
  1412. // -----------------------------------------------------------------------
  1413. // IOVec interfaces
  1414. // -----------------------------------------------------------------------
  1415. // A type that writes to an iovec.
  1416. // Note that this is not a "ByteSink", but a type that matches the
  1417. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  1418. class SnappyIOVecWriter {
  1419. private:
  1420. // output_iov_end_ is set to iov + count and used to determine when
  1421. // the end of the iovs is reached.
  1422. const struct iovec* output_iov_end_;
  1423. #if !defined(NDEBUG)
  1424. const struct iovec* output_iov_;
  1425. #endif // !defined(NDEBUG)
  1426. // Current iov that is being written into.
  1427. const struct iovec* curr_iov_;
  1428. // Pointer to current iov's write location.
  1429. char* curr_iov_output_;
  1430. // Remaining bytes to write into curr_iov_output.
  1431. size_t curr_iov_remaining_;
  1432. // Total bytes decompressed into output_iov_ so far.
  1433. size_t total_written_;
  1434. // Maximum number of bytes that will be decompressed into output_iov_.
  1435. size_t output_limit_;
  1436. static inline char* GetIOVecPointer(const struct iovec* iov, size_t offset) {
  1437. return reinterpret_cast<char*>(iov->iov_base) + offset;
  1438. }
  1439. public:
  1440. // Does not take ownership of iov. iov must be valid during the
  1441. // entire lifetime of the SnappyIOVecWriter.
  1442. inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count)
  1443. : output_iov_end_(iov + iov_count),
  1444. #if !defined(NDEBUG)
  1445. output_iov_(iov),
  1446. #endif // !defined(NDEBUG)
  1447. curr_iov_(iov),
  1448. curr_iov_output_(iov_count ? reinterpret_cast<char*>(iov->iov_base)
  1449. : nullptr),
  1450. curr_iov_remaining_(iov_count ? iov->iov_len : 0),
  1451. total_written_(0),
  1452. output_limit_(-1) {
  1453. }
  1454. inline void SetExpectedLength(size_t len) { output_limit_ = len; }
  1455. inline bool CheckLength() const { return total_written_ == output_limit_; }
  1456. inline bool Append(const char* ip, size_t len, char**) {
  1457. if (total_written_ + len > output_limit_) {
  1458. return false;
  1459. }
  1460. return AppendNoCheck(ip, len);
  1461. }
  1462. char* GetOutputPtr() { return nullptr; }
  1463. char* GetBase(ptrdiff_t*) { return nullptr; }
  1464. void SetOutputPtr(char* op) {
  1465. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  1466. (void)op;
  1467. }
  1468. inline bool AppendNoCheck(const char* ip, size_t len) {
  1469. while (len > 0) {
  1470. if (curr_iov_remaining_ == 0) {
  1471. // This iovec is full. Go to the next one.
  1472. if (curr_iov_ + 1 >= output_iov_end_) {
  1473. return false;
  1474. }
  1475. ++curr_iov_;
  1476. curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
  1477. curr_iov_remaining_ = curr_iov_->iov_len;
  1478. }
  1479. const size_t to_write = std::min(len, curr_iov_remaining_);
  1480. std::memcpy(curr_iov_output_, ip, to_write);
  1481. curr_iov_output_ += to_write;
  1482. curr_iov_remaining_ -= to_write;
  1483. total_written_ += to_write;
  1484. ip += to_write;
  1485. len -= to_write;
  1486. }
  1487. return true;
  1488. }
  1489. inline bool TryFastAppend(const char* ip, size_t available, size_t len,
  1490. char**) {
  1491. const size_t space_left = output_limit_ - total_written_;
  1492. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
  1493. curr_iov_remaining_ >= 16) {
  1494. // Fast path, used for the majority (about 95%) of invocations.
  1495. UnalignedCopy128(ip, curr_iov_output_);
  1496. curr_iov_output_ += len;
  1497. curr_iov_remaining_ -= len;
  1498. total_written_ += len;
  1499. return true;
  1500. }
  1501. return false;
  1502. }
  1503. inline bool AppendFromSelf(size_t offset, size_t len, char**) {
  1504. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1505. // the "offset - 1u" trick.
  1506. if (offset - 1u >= total_written_) {
  1507. return false;
  1508. }
  1509. const size_t space_left = output_limit_ - total_written_;
  1510. if (len > space_left) {
  1511. return false;
  1512. }
  1513. // Locate the iovec from which we need to start the copy.
  1514. const iovec* from_iov = curr_iov_;
  1515. size_t from_iov_offset = curr_iov_->iov_len - curr_iov_remaining_;
  1516. while (offset > 0) {
  1517. if (from_iov_offset >= offset) {
  1518. from_iov_offset -= offset;
  1519. break;
  1520. }
  1521. offset -= from_iov_offset;
  1522. --from_iov;
  1523. #if !defined(NDEBUG)
  1524. assert(from_iov >= output_iov_);
  1525. #endif // !defined(NDEBUG)
  1526. from_iov_offset = from_iov->iov_len;
  1527. }
  1528. // Copy <len> bytes starting from the iovec pointed to by from_iov_index to
  1529. // the current iovec.
  1530. while (len > 0) {
  1531. assert(from_iov <= curr_iov_);
  1532. if (from_iov != curr_iov_) {
  1533. const size_t to_copy =
  1534. std::min(from_iov->iov_len - from_iov_offset, len);
  1535. AppendNoCheck(GetIOVecPointer(from_iov, from_iov_offset), to_copy);
  1536. len -= to_copy;
  1537. if (len > 0) {
  1538. ++from_iov;
  1539. from_iov_offset = 0;
  1540. }
  1541. } else {
  1542. size_t to_copy = curr_iov_remaining_;
  1543. if (to_copy == 0) {
  1544. // This iovec is full. Go to the next one.
  1545. if (curr_iov_ + 1 >= output_iov_end_) {
  1546. return false;
  1547. }
  1548. ++curr_iov_;
  1549. curr_iov_output_ = reinterpret_cast<char*>(curr_iov_->iov_base);
  1550. curr_iov_remaining_ = curr_iov_->iov_len;
  1551. continue;
  1552. }
  1553. if (to_copy > len) {
  1554. to_copy = len;
  1555. }
  1556. assert(to_copy > 0);
  1557. IncrementalCopy(GetIOVecPointer(from_iov, from_iov_offset),
  1558. curr_iov_output_, curr_iov_output_ + to_copy,
  1559. curr_iov_output_ + curr_iov_remaining_);
  1560. curr_iov_output_ += to_copy;
  1561. curr_iov_remaining_ -= to_copy;
  1562. from_iov_offset += to_copy;
  1563. total_written_ += to_copy;
  1564. len -= to_copy;
  1565. }
  1566. }
  1567. return true;
  1568. }
  1569. inline void Flush() {}
  1570. };
  1571. bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
  1572. const struct iovec* iov, size_t iov_cnt) {
  1573. ByteArraySource reader(compressed, compressed_length);
  1574. return RawUncompressToIOVec(&reader, iov, iov_cnt);
  1575. }
  1576. bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
  1577. size_t iov_cnt) {
  1578. SnappyIOVecWriter output(iov, iov_cnt);
  1579. return InternalUncompress(compressed, &output);
  1580. }
  1581. // -----------------------------------------------------------------------
  1582. // Flat array interfaces
  1583. // -----------------------------------------------------------------------
  1584. // A type that writes to a flat array.
  1585. // Note that this is not a "ByteSink", but a type that matches the
  1586. // Writer template argument to SnappyDecompressor::DecompressAllTags().
  1587. class SnappyArrayWriter {
  1588. private:
  1589. char* base_;
  1590. char* op_;
  1591. char* op_limit_;
  1592. // If op < op_limit_min_slop_ then it's safe to unconditionally write
  1593. // kSlopBytes starting at op.
  1594. char* op_limit_min_slop_;
  1595. public:
  1596. inline explicit SnappyArrayWriter(char* dst)
  1597. : base_(dst),
  1598. op_(dst),
  1599. op_limit_(dst),
  1600. op_limit_min_slop_(dst) {} // Safe default see invariant.
  1601. inline void SetExpectedLength(size_t len) {
  1602. op_limit_ = op_ + len;
  1603. // Prevent pointer from being past the buffer.
  1604. op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, len);
  1605. }
  1606. inline bool CheckLength() const { return op_ == op_limit_; }
  1607. char* GetOutputPtr() { return op_; }
  1608. char* GetBase(ptrdiff_t* op_limit_min_slop) {
  1609. *op_limit_min_slop = op_limit_min_slop_ - base_;
  1610. return base_;
  1611. }
  1612. void SetOutputPtr(char* op) { op_ = op; }
  1613. inline bool Append(const char* ip, size_t len, char** op_p) {
  1614. char* op = *op_p;
  1615. const size_t space_left = op_limit_ - op;
  1616. if (space_left < len) return false;
  1617. std::memcpy(op, ip, len);
  1618. *op_p = op + len;
  1619. return true;
  1620. }
  1621. inline bool TryFastAppend(const char* ip, size_t available, size_t len,
  1622. char** op_p) {
  1623. char* op = *op_p;
  1624. const size_t space_left = op_limit_ - op;
  1625. if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
  1626. // Fast path, used for the majority (about 95%) of invocations.
  1627. UnalignedCopy128(ip, op);
  1628. *op_p = op + len;
  1629. return true;
  1630. } else {
  1631. return false;
  1632. }
  1633. }
  1634. SNAPPY_ATTRIBUTE_ALWAYS_INLINE
  1635. inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
  1636. assert(len > 0);
  1637. char* const op = *op_p;
  1638. assert(op >= base_);
  1639. char* const op_end = op + len;
  1640. // Check if we try to append from before the start of the buffer.
  1641. if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - base_) < offset))
  1642. return false;
  1643. if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
  1644. op >= op_limit_min_slop_ || offset < len)) {
  1645. if (op_end > op_limit_ || offset == 0) return false;
  1646. *op_p = IncrementalCopy(op - offset, op, op_end, op_limit_);
  1647. return true;
  1648. }
  1649. std::memmove(op, op - offset, kSlopBytes);
  1650. *op_p = op_end;
  1651. return true;
  1652. }
  1653. inline size_t Produced() const {
  1654. assert(op_ >= base_);
  1655. return op_ - base_;
  1656. }
  1657. inline void Flush() {}
  1658. };
  1659. bool RawUncompress(const char* compressed, size_t compressed_length,
  1660. char* uncompressed) {
  1661. ByteArraySource reader(compressed, compressed_length);
  1662. return RawUncompress(&reader, uncompressed);
  1663. }
  1664. bool RawUncompress(Source* compressed, char* uncompressed) {
  1665. SnappyArrayWriter output(uncompressed);
  1666. return InternalUncompress(compressed, &output);
  1667. }
  1668. bool Uncompress(const char* compressed, size_t compressed_length,
  1669. std::string* uncompressed) {
  1670. size_t ulength;
  1671. if (!GetUncompressedLength(compressed, compressed_length, &ulength)) {
  1672. return false;
  1673. }
  1674. // On 32-bit builds: max_size() < kuint32max. Check for that instead
  1675. // of crashing (e.g., consider externally specified compressed data).
  1676. if (ulength > uncompressed->max_size()) {
  1677. return false;
  1678. }
  1679. STLStringResizeUninitialized(uncompressed, ulength);
  1680. return RawUncompress(compressed, compressed_length,
  1681. string_as_array(uncompressed));
  1682. }
  1683. bool Uncompress(const char* compressed, size_t n, TString* uncompressed) {
  1684. size_t ulength;
  1685. if (!GetUncompressedLength(compressed, n, &ulength)) {
  1686. return false;
  1687. }
  1688. // On 32-bit builds: max_size() < kuint32max. Check for that instead
  1689. // of crashing (e.g., consider externally specified compressed data).
  1690. if (ulength > uncompressed->max_size()) {
  1691. return false;
  1692. }
  1693. uncompressed->ReserveAndResize(ulength);
  1694. return RawUncompress(compressed, n, uncompressed->begin());
  1695. }
  1696. // A Writer that drops everything on the floor and just does validation
  1697. class SnappyDecompressionValidator {
  1698. private:
  1699. size_t expected_;
  1700. size_t produced_;
  1701. public:
  1702. inline SnappyDecompressionValidator() : expected_(0), produced_(0) {}
  1703. inline void SetExpectedLength(size_t len) { expected_ = len; }
  1704. size_t GetOutputPtr() { return produced_; }
  1705. size_t GetBase(ptrdiff_t* op_limit_min_slop) {
  1706. *op_limit_min_slop = std::numeric_limits<ptrdiff_t>::max() - kSlopBytes + 1;
  1707. return 1;
  1708. }
  1709. void SetOutputPtr(size_t op) { produced_ = op; }
  1710. inline bool CheckLength() const { return expected_ == produced_; }
  1711. inline bool Append(const char* ip, size_t len, size_t* produced) {
  1712. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  1713. (void)ip;
  1714. *produced += len;
  1715. return *produced <= expected_;
  1716. }
  1717. inline bool TryFastAppend(const char* ip, size_t available, size_t length,
  1718. size_t* produced) {
  1719. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  1720. (void)ip;
  1721. (void)available;
  1722. (void)length;
  1723. (void)produced;
  1724. return false;
  1725. }
  1726. inline bool AppendFromSelf(size_t offset, size_t len, size_t* produced) {
  1727. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1728. // the "offset - 1u" trick.
  1729. if (*produced <= offset - 1u) return false;
  1730. *produced += len;
  1731. return *produced <= expected_;
  1732. }
  1733. inline void Flush() {}
  1734. };
  1735. bool IsValidCompressedBuffer(const char* compressed, size_t compressed_length) {
  1736. ByteArraySource reader(compressed, compressed_length);
  1737. SnappyDecompressionValidator writer;
  1738. return InternalUncompress(&reader, &writer);
  1739. }
  1740. bool IsValidCompressed(Source* compressed) {
  1741. SnappyDecompressionValidator writer;
  1742. return InternalUncompress(compressed, &writer);
  1743. }
  1744. void RawCompress(const char* input, size_t input_length, char* compressed,
  1745. size_t* compressed_length) {
  1746. ByteArraySource reader(input, input_length);
  1747. UncheckedByteArraySink writer(compressed);
  1748. Compress(&reader, &writer);
  1749. // Compute how many bytes were added
  1750. *compressed_length = (writer.CurrentDestination() - compressed);
  1751. }
  1752. size_t Compress(const char* input, size_t input_length,
  1753. std::string* compressed) {
  1754. // Pre-grow the buffer to the max length of the compressed output
  1755. STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
  1756. size_t compressed_length;
  1757. RawCompress(input, input_length, string_as_array(compressed),
  1758. &compressed_length);
  1759. compressed->resize(compressed_length);
  1760. return compressed_length;
  1761. }
  1762. size_t Compress(const char* input, size_t input_length,
  1763. TString* compressed) {
  1764. // Pre-grow the buffer to the max length of the compressed output
  1765. compressed->ReserveAndResize(MaxCompressedLength(input_length));
  1766. size_t compressed_length;
  1767. RawCompress(input, input_length, compressed->begin(),
  1768. &compressed_length);
  1769. compressed->resize(compressed_length);
  1770. return compressed_length;
  1771. }
  1772. // -----------------------------------------------------------------------
  1773. // Sink interface
  1774. // -----------------------------------------------------------------------
  1775. // A type that decompresses into a Sink. The template parameter
  1776. // Allocator must export one method "char* Allocate(int size);", which
  1777. // allocates a buffer of "size" and appends that to the destination.
  1778. template <typename Allocator>
  1779. class SnappyScatteredWriter {
  1780. Allocator allocator_;
  1781. // We need random access into the data generated so far. Therefore
  1782. // we keep track of all of the generated data as an array of blocks.
  1783. // All of the blocks except the last have length kBlockSize.
  1784. std::vector<char*> blocks_;
  1785. size_t expected_;
  1786. // Total size of all fully generated blocks so far
  1787. size_t full_size_;
  1788. // Pointer into current output block
  1789. char* op_base_; // Base of output block
  1790. char* op_ptr_; // Pointer to next unfilled byte in block
  1791. char* op_limit_; // Pointer just past block
  1792. // If op < op_limit_min_slop_ then it's safe to unconditionally write
  1793. // kSlopBytes starting at op.
  1794. char* op_limit_min_slop_;
  1795. inline size_t Size() const { return full_size_ + (op_ptr_ - op_base_); }
  1796. bool SlowAppend(const char* ip, size_t len);
  1797. bool SlowAppendFromSelf(size_t offset, size_t len);
  1798. public:
  1799. inline explicit SnappyScatteredWriter(const Allocator& allocator)
  1800. : allocator_(allocator),
  1801. full_size_(0),
  1802. op_base_(NULL),
  1803. op_ptr_(NULL),
  1804. op_limit_(NULL),
  1805. op_limit_min_slop_(NULL) {}
  1806. char* GetOutputPtr() { return op_ptr_; }
  1807. char* GetBase(ptrdiff_t* op_limit_min_slop) {
  1808. *op_limit_min_slop = op_limit_min_slop_ - op_base_;
  1809. return op_base_;
  1810. }
  1811. void SetOutputPtr(char* op) { op_ptr_ = op; }
  1812. inline void SetExpectedLength(size_t len) {
  1813. assert(blocks_.empty());
  1814. expected_ = len;
  1815. }
  1816. inline bool CheckLength() const { return Size() == expected_; }
  1817. // Return the number of bytes actually uncompressed so far
  1818. inline size_t Produced() const { return Size(); }
  1819. inline bool Append(const char* ip, size_t len, char** op_p) {
  1820. char* op = *op_p;
  1821. size_t avail = op_limit_ - op;
  1822. if (len <= avail) {
  1823. // Fast path
  1824. std::memcpy(op, ip, len);
  1825. *op_p = op + len;
  1826. return true;
  1827. } else {
  1828. op_ptr_ = op;
  1829. bool res = SlowAppend(ip, len);
  1830. *op_p = op_ptr_;
  1831. return res;
  1832. }
  1833. }
  1834. inline bool TryFastAppend(const char* ip, size_t available, size_t length,
  1835. char** op_p) {
  1836. char* op = *op_p;
  1837. const int space_left = op_limit_ - op;
  1838. if (length <= 16 && available >= 16 + kMaximumTagLength &&
  1839. space_left >= 16) {
  1840. // Fast path, used for the majority (about 95%) of invocations.
  1841. UnalignedCopy128(ip, op);
  1842. *op_p = op + length;
  1843. return true;
  1844. } else {
  1845. return false;
  1846. }
  1847. }
  1848. inline bool AppendFromSelf(size_t offset, size_t len, char** op_p) {
  1849. char* op = *op_p;
  1850. assert(op >= op_base_);
  1851. // Check if we try to append from before the start of the buffer.
  1852. if (SNAPPY_PREDICT_FALSE((kSlopBytes < 64 && len > kSlopBytes) ||
  1853. static_cast<size_t>(op - op_base_) < offset ||
  1854. op >= op_limit_min_slop_ || offset < len)) {
  1855. if (offset == 0) return false;
  1856. if (SNAPPY_PREDICT_FALSE(static_cast<size_t>(op - op_base_) < offset ||
  1857. op + len > op_limit_)) {
  1858. op_ptr_ = op;
  1859. bool res = SlowAppendFromSelf(offset, len);
  1860. *op_p = op_ptr_;
  1861. return res;
  1862. }
  1863. *op_p = IncrementalCopy(op - offset, op, op + len, op_limit_);
  1864. return true;
  1865. }
  1866. // Fast path
  1867. char* const op_end = op + len;
  1868. std::memmove(op, op - offset, kSlopBytes);
  1869. *op_p = op_end;
  1870. return true;
  1871. }
  1872. // Called at the end of the decompress. We ask the allocator
  1873. // write all blocks to the sink.
  1874. inline void Flush() { allocator_.Flush(Produced()); }
  1875. };
  1876. template <typename Allocator>
  1877. bool SnappyScatteredWriter<Allocator>::SlowAppend(const char* ip, size_t len) {
  1878. size_t avail = op_limit_ - op_ptr_;
  1879. while (len > avail) {
  1880. // Completely fill this block
  1881. std::memcpy(op_ptr_, ip, avail);
  1882. op_ptr_ += avail;
  1883. assert(op_limit_ - op_ptr_ == 0);
  1884. full_size_ += (op_ptr_ - op_base_);
  1885. len -= avail;
  1886. ip += avail;
  1887. // Bounds check
  1888. if (full_size_ + len > expected_) return false;
  1889. // Make new block
  1890. size_t bsize = std::min<size_t>(kBlockSize, expected_ - full_size_);
  1891. op_base_ = allocator_.Allocate(bsize);
  1892. op_ptr_ = op_base_;
  1893. op_limit_ = op_base_ + bsize;
  1894. op_limit_min_slop_ = op_limit_ - std::min<size_t>(kSlopBytes - 1, bsize);
  1895. blocks_.push_back(op_base_);
  1896. avail = bsize;
  1897. }
  1898. std::memcpy(op_ptr_, ip, len);
  1899. op_ptr_ += len;
  1900. return true;
  1901. }
  1902. template <typename Allocator>
  1903. bool SnappyScatteredWriter<Allocator>::SlowAppendFromSelf(size_t offset,
  1904. size_t len) {
  1905. // Overflow check
  1906. // See SnappyArrayWriter::AppendFromSelf for an explanation of
  1907. // the "offset - 1u" trick.
  1908. const size_t cur = Size();
  1909. if (offset - 1u >= cur) return false;
  1910. if (expected_ - cur < len) return false;
  1911. // Currently we shouldn't ever hit this path because Compress() chops the
  1912. // input into blocks and does not create cross-block copies. However, it is
  1913. // nice if we do not rely on that, since we can get better compression if we
  1914. // allow cross-block copies and thus might want to change the compressor in
  1915. // the future.
  1916. // TODO Replace this with a properly optimized path. This is not
  1917. // triggered right now. But this is so super slow, that it would regress
  1918. // performance unacceptably if triggered.
  1919. size_t src = cur - offset;
  1920. char* op = op_ptr_;
  1921. while (len-- > 0) {
  1922. char c = blocks_[src >> kBlockLog][src & (kBlockSize - 1)];
  1923. if (!Append(&c, 1, &op)) {
  1924. op_ptr_ = op;
  1925. return false;
  1926. }
  1927. src++;
  1928. }
  1929. op_ptr_ = op;
  1930. return true;
  1931. }
  1932. class SnappySinkAllocator {
  1933. public:
  1934. explicit SnappySinkAllocator(Sink* dest) : dest_(dest) {}
  1935. ~SnappySinkAllocator() {}
  1936. char* Allocate(int size) {
  1937. Datablock block(new char[size], size);
  1938. blocks_.push_back(block);
  1939. return block.data;
  1940. }
  1941. // We flush only at the end, because the writer wants
  1942. // random access to the blocks and once we hand the
  1943. // block over to the sink, we can't access it anymore.
  1944. // Also we don't write more than has been actually written
  1945. // to the blocks.
  1946. void Flush(size_t size) {
  1947. size_t size_written = 0;
  1948. for (Datablock& block : blocks_) {
  1949. size_t block_size = std::min<size_t>(block.size, size - size_written);
  1950. dest_->AppendAndTakeOwnership(block.data, block_size,
  1951. &SnappySinkAllocator::Deleter, NULL);
  1952. size_written += block_size;
  1953. }
  1954. blocks_.clear();
  1955. }
  1956. private:
  1957. struct Datablock {
  1958. char* data;
  1959. size_t size;
  1960. Datablock(char* p, size_t s) : data(p), size(s) {}
  1961. };
  1962. static void Deleter(void* arg, const char* bytes, size_t size) {
  1963. // TODO: Switch to [[maybe_unused]] when we can assume C++17.
  1964. (void)arg;
  1965. (void)size;
  1966. delete[] bytes;
  1967. }
  1968. Sink* dest_;
  1969. std::vector<Datablock> blocks_;
  1970. // Note: copying this object is allowed
  1971. };
  1972. size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) {
  1973. SnappySinkAllocator allocator(uncompressed);
  1974. SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
  1975. InternalUncompress(compressed, &writer);
  1976. return writer.Produced();
  1977. }
  1978. bool Uncompress(Source* compressed, Sink* uncompressed) {
  1979. // Read the uncompressed length from the front of the compressed input
  1980. SnappyDecompressor decompressor(compressed);
  1981. uint32_t uncompressed_len = 0;
  1982. if (!decompressor.ReadUncompressedLength(&uncompressed_len)) {
  1983. return false;
  1984. }
  1985. char c;
  1986. size_t allocated_size;
  1987. char* buf = uncompressed->GetAppendBufferVariable(1, uncompressed_len, &c, 1,
  1988. &allocated_size);
  1989. const size_t compressed_len = compressed->Available();
  1990. // If we can get a flat buffer, then use it, otherwise do block by block
  1991. // uncompression
  1992. if (allocated_size >= uncompressed_len) {
  1993. SnappyArrayWriter writer(buf);
  1994. bool result = InternalUncompressAllTags(&decompressor, &writer,
  1995. compressed_len, uncompressed_len);
  1996. uncompressed->Append(buf, writer.Produced());
  1997. return result;
  1998. } else {
  1999. SnappySinkAllocator allocator(uncompressed);
  2000. SnappyScatteredWriter<SnappySinkAllocator> writer(allocator);
  2001. return InternalUncompressAllTags(&decompressor, &writer, compressed_len,
  2002. uncompressed_len);
  2003. }
  2004. }
  2005. } // namespace snappy