snappy.cc 90 KB

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