snappy.cc 99 KB

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