deflate_stream.ipp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. // This is a derivative work based on Zlib, copyright below:
  10. /*
  11. Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
  12. This software is provided 'as-is', without any express or implied
  13. warranty. In no event will the authors be held liable for any damages
  14. arising from the use of this software.
  15. Permission is granted to anyone to use this software for any purpose,
  16. including commercial applications, and to alter it and redistribute it
  17. freely, subject to the following restrictions:
  18. 1. The origin of this software must not be misrepresented; you must not
  19. claim that you wrote the original software. If you use this software
  20. in a product, an acknowledgment in the product documentation would be
  21. appreciated but is not required.
  22. 2. Altered source versions must be plainly marked as such, and must not be
  23. misrepresented as being the original software.
  24. 3. This notice may not be removed or altered from any source distribution.
  25. Jean-loup Gailly Mark Adler
  26. jloup@gzip.org madler@alumni.caltech.edu
  27. The data format used by the zlib library is described by RFCs (Request for
  28. Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
  29. (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
  30. */
  31. #ifndef BOOST_BEAST_ZLIB_DETAIL_DEFLATE_STREAM_IPP
  32. #define BOOST_BEAST_ZLIB_DETAIL_DEFLATE_STREAM_IPP
  33. #include <boost/beast/zlib/detail/deflate_stream.hpp>
  34. #include <boost/beast/zlib/detail/ranges.hpp>
  35. #include <boost/assert.hpp>
  36. #include <boost/config.hpp>
  37. #include <boost/make_unique.hpp>
  38. #include <boost/optional.hpp>
  39. #include <boost/throw_exception.hpp>
  40. #include <cstdint>
  41. #include <cstdlib>
  42. #include <cstring>
  43. #include <memory>
  44. #include <stdexcept>
  45. #include <type_traits>
  46. namespace boost {
  47. namespace beast {
  48. namespace zlib {
  49. namespace detail {
  50. /*
  51. * ALGORITHM
  52. *
  53. * The "deflation" process depends on being able to identify portions
  54. * of the input text which are identical to earlier input (within a
  55. * sliding window trailing behind the input currently being processed).
  56. *
  57. * Each code tree is stored in a compressed form which is itself
  58. * a Huffman encoding of the lengths of all the code strings (in
  59. * ascending order by source values). The actual code strings are
  60. * reconstructed from the lengths in the inflate process, as described
  61. * in the deflate specification.
  62. *
  63. * The most straightforward technique turns out to be the fastest for
  64. * most input files: try all possible matches and select the longest.
  65. * The key feature of this algorithm is that insertions into the string
  66. * dictionary are very simple and thus fast, and deletions are avoided
  67. * completely. Insertions are performed at each input character, whereas
  68. * string matches are performed only when the previous match ends. So it
  69. * is preferable to spend more time in matches to allow very fast string
  70. * insertions and avoid deletions. The matching algorithm for small
  71. * strings is inspired from that of Rabin & Karp. A brute force approach
  72. * is used to find longer strings when a small match has been found.
  73. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  74. * (by Leonid Broukhis).
  75. * A previous version of this file used a more sophisticated algorithm
  76. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  77. * time, but has a larger average cost, uses more memory and is patented.
  78. * However the F&G algorithm may be faster for some highly redundant
  79. * files if the parameter max_chain_length (described below) is too large.
  80. *
  81. * ACKNOWLEDGEMENTS
  82. *
  83. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  84. * I found it in 'freeze' written by Leonid Broukhis.
  85. * Thanks to many people for bug reports and testing.
  86. *
  87. * REFERENCES
  88. *
  89. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  90. * Available in http://tools.ietf.org/html/rfc1951
  91. *
  92. * A description of the Rabin and Karp algorithm is given in the book
  93. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  94. *
  95. * Fiala,E.R., and Greene,D.H.
  96. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  97. *
  98. */
  99. /* Generate the codes for a given tree and bit counts (which need not be optimal).
  100. IN assertion: the array bl_count contains the bit length statistics for
  101. the given tree and the field len is set for all tree elements.
  102. OUT assertion: the field code is set for all tree elements of non
  103. zero code length.
  104. */
  105. void
  106. deflate_stream::
  107. gen_codes(ct_data *tree, int max_code, std::uint16_t *bl_count)
  108. {
  109. std::uint16_t next_code[maxBits+1]; /* next code value for each bit length */
  110. std::uint16_t code = 0; /* running code value */
  111. int bits; /* bit index */
  112. int n; /* code index */
  113. // The distribution counts are first used to
  114. // generate the code values without bit reversal.
  115. for(bits = 1; bits <= maxBits; bits++)
  116. {
  117. code = (code + bl_count[bits-1]) << 1;
  118. next_code[bits] = code;
  119. }
  120. // Check that the bit counts in bl_count are consistent.
  121. // The last code must be all ones.
  122. BOOST_ASSERT(code + bl_count[maxBits]-1 == (1<<maxBits)-1);
  123. for(n = 0; n <= max_code; n++)
  124. {
  125. int len = tree[n].dl;
  126. if(len == 0)
  127. continue;
  128. tree[n].fc = bi_reverse(next_code[len]++, len);
  129. }
  130. }
  131. auto
  132. deflate_stream::get_lut() ->
  133. lut_type const&
  134. {
  135. struct init
  136. {
  137. lut_type tables;
  138. init()
  139. {
  140. // number of codes at each bit length for an optimal tree
  141. //std::uint16_t bl_count[maxBits+1];
  142. // Initialize the mapping length (0..255) -> length code (0..28)
  143. std::uint8_t length = 0;
  144. for(std::uint8_t code = 0; code < lengthCodes-1; ++code)
  145. {
  146. tables.base_length[code] = length;
  147. auto const run = 1U << tables.extra_lbits[code];
  148. for(unsigned n = 0; n < run; ++n)
  149. tables.length_code[length++] = code;
  150. }
  151. BOOST_ASSERT(length == 0);
  152. // Note that the length 255 (match length 258) can be represented
  153. // in two different ways: code 284 + 5 bits or code 285, so we
  154. // overwrite length_code[255] to use the best encoding:
  155. tables.length_code[255] = lengthCodes-1;
  156. // Initialize the mapping dist (0..32K) -> dist code (0..29)
  157. {
  158. std::uint8_t code;
  159. std::uint16_t dist = 0;
  160. for(code = 0; code < 16; code++)
  161. {
  162. tables.base_dist[code] = dist;
  163. auto const run = 1U << tables.extra_dbits[code];
  164. for(unsigned n = 0; n < run; ++n)
  165. tables.dist_code[dist++] = code;
  166. }
  167. BOOST_ASSERT(dist == 256);
  168. // from now on, all distances are divided by 128
  169. dist >>= 7;
  170. for(; code < dCodes; ++code)
  171. {
  172. tables.base_dist[code] = dist << 7;
  173. auto const run = 1U << (tables.extra_dbits[code]-7);
  174. for(std::size_t n = 0; n < run; ++n)
  175. tables.dist_code[256 + dist++] = code;
  176. }
  177. BOOST_ASSERT(dist == 256);
  178. }
  179. // Construct the codes of the static literal tree
  180. std::uint16_t bl_count[maxBits+1];
  181. std::memset(bl_count, 0, sizeof(bl_count));
  182. unsigned n = 0;
  183. while (n <= 143)
  184. tables.ltree[n++].dl = 8;
  185. bl_count[8] += 144;
  186. while (n <= 255)
  187. tables.ltree[n++].dl = 9;
  188. bl_count[9] += 112;
  189. while (n <= 279)
  190. tables.ltree[n++].dl = 7;
  191. bl_count[7] += 24;
  192. while (n <= 287)
  193. tables.ltree[n++].dl = 8;
  194. bl_count[8] += 8;
  195. // Codes 286 and 287 do not exist, but we must include them in the tree
  196. // construction to get a canonical Huffman tree (longest code all ones)
  197. gen_codes(tables.ltree, lCodes+1, bl_count);
  198. for(n = 0; n < dCodes; ++n)
  199. {
  200. tables.dtree[n].dl = 5;
  201. tables.dtree[n].fc =
  202. static_cast<std::uint16_t>(bi_reverse(n, 5));
  203. }
  204. }
  205. };
  206. static init const data;
  207. return data.tables;
  208. }
  209. void
  210. deflate_stream::
  211. doReset(
  212. int level,
  213. int windowBits,
  214. int memLevel,
  215. Strategy strategy)
  216. {
  217. if(level == default_size)
  218. level = 6;
  219. // VFALCO What do we do about this?
  220. // until 256-byte window bug fixed
  221. if(windowBits == 8)
  222. windowBits = 9;
  223. if(level < 0 || level > 9)
  224. BOOST_THROW_EXCEPTION(std::invalid_argument{
  225. "invalid level"});
  226. if(windowBits < 8 || windowBits > 15)
  227. BOOST_THROW_EXCEPTION(std::invalid_argument{
  228. "invalid windowBits"});
  229. if(memLevel < 1 || memLevel > max_mem_level)
  230. BOOST_THROW_EXCEPTION(std::invalid_argument{
  231. "invalid memLevel"});
  232. w_bits_ = windowBits;
  233. hash_bits_ = memLevel + 7;
  234. // 16K elements by default
  235. lit_bufsize_ = 1 << (memLevel + 6);
  236. level_ = level;
  237. strategy_ = strategy;
  238. inited_ = false;
  239. }
  240. void
  241. deflate_stream::
  242. doReset()
  243. {
  244. inited_ = false;
  245. }
  246. void
  247. deflate_stream::
  248. doClear()
  249. {
  250. inited_ = false;
  251. buf_.reset();
  252. }
  253. std::size_t
  254. deflate_stream::
  255. doUpperBound(std::size_t sourceLen) const
  256. {
  257. std::size_t complen;
  258. std::size_t wraplen;
  259. /* conservative upper bound for compressed data */
  260. complen = sourceLen +
  261. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
  262. /* compute wrapper length */
  263. wraplen = 0;
  264. /* if not default parameters, return conservative bound */
  265. if(w_bits_ != 15 || hash_bits_ != 8 + 7)
  266. return complen + wraplen;
  267. /* default settings: return tight bound for that case */
  268. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
  269. (sourceLen >> 25) + 13 - 6 + wraplen;
  270. }
  271. void
  272. deflate_stream::
  273. doTune(
  274. int good_length,
  275. int max_lazy,
  276. int nice_length,
  277. int max_chain)
  278. {
  279. good_match_ = good_length;
  280. nice_match_ = nice_length;
  281. max_lazy_match_ = max_lazy;
  282. max_chain_length_ = max_chain;
  283. }
  284. void
  285. deflate_stream::
  286. doParams(z_params& zs, int level, Strategy strategy, error_code& ec)
  287. {
  288. compress_func func;
  289. if(level == default_size)
  290. level = 6;
  291. if(level < 0 || level > 9)
  292. {
  293. ec = error::stream_error;
  294. return;
  295. }
  296. func = get_config(level_).func;
  297. if((strategy != strategy_ || func != get_config(level).func) &&
  298. zs.total_in != 0)
  299. {
  300. // Flush the last buffer:
  301. doWrite(zs, Flush::block, ec);
  302. if(ec == error::need_buffers && pending_ == 0)
  303. ec = {};
  304. }
  305. if(level_ != level)
  306. {
  307. level_ = level;
  308. max_lazy_match_ = get_config(level).max_lazy;
  309. good_match_ = get_config(level).good_length;
  310. nice_match_ = get_config(level).nice_length;
  311. max_chain_length_ = get_config(level).max_chain;
  312. }
  313. strategy_ = strategy;
  314. }
  315. // VFALCO boost::optional param is a workaround for
  316. // gcc "maybe uninitialized" warning
  317. // https://github.com/boostorg/beast/issues/532
  318. //
  319. void
  320. deflate_stream::
  321. doWrite(z_params& zs, boost::optional<Flush> flush, error_code& ec)
  322. {
  323. maybe_init();
  324. if(zs.next_in == nullptr && zs.avail_in != 0)
  325. BOOST_THROW_EXCEPTION(std::invalid_argument{"invalid input"});
  326. if(zs.next_out == nullptr ||
  327. (status_ == FINISH_STATE && flush != Flush::finish))
  328. {
  329. ec = error::stream_error;
  330. return;
  331. }
  332. if(zs.avail_out == 0)
  333. {
  334. ec = error::need_buffers;
  335. return;
  336. }
  337. // value of flush param for previous deflate call
  338. auto old_flush = boost::make_optional<Flush>(
  339. last_flush_.is_initialized(),
  340. last_flush_ ? *last_flush_ : Flush::none);
  341. last_flush_ = flush;
  342. // Flush as much pending output as possible
  343. if(pending_ != 0)
  344. {
  345. flush_pending(zs);
  346. if(zs.avail_out == 0)
  347. {
  348. /* Since avail_out is 0, deflate will be called again with
  349. * more output space, but possibly with both pending and
  350. * avail_in equal to zero. There won't be anything to do,
  351. * but this is not an error situation so make sure we
  352. * return OK instead of BUF_ERROR at next call of deflate:
  353. */
  354. last_flush_ = boost::none;
  355. return;
  356. }
  357. }
  358. else if(zs.avail_in == 0 && (
  359. old_flush && flush <= *old_flush // Caution: depends on enum order
  360. ) && flush != Flush::finish)
  361. {
  362. /* Make sure there is something to do and avoid duplicate consecutive
  363. * flushes. For repeated and useless calls with Flush::finish, we keep
  364. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  365. */
  366. ec = error::need_buffers;
  367. return;
  368. }
  369. // User must not provide more input after the first FINISH:
  370. if(status_ == FINISH_STATE && zs.avail_in != 0)
  371. {
  372. ec = error::need_buffers;
  373. return;
  374. }
  375. /* Start a new block or continue the current one.
  376. */
  377. if(zs.avail_in != 0 || lookahead_ != 0 ||
  378. (flush != Flush::none && status_ != FINISH_STATE))
  379. {
  380. block_state bstate;
  381. switch(strategy_)
  382. {
  383. case Strategy::huffman:
  384. bstate = deflate_huff(zs, flush.get());
  385. break;
  386. case Strategy::rle:
  387. bstate = deflate_rle(zs, flush.get());
  388. break;
  389. default:
  390. {
  391. bstate = (this->*(get_config(level_).func))(zs, flush.get());
  392. break;
  393. }
  394. }
  395. if(bstate == finish_started || bstate == finish_done)
  396. {
  397. status_ = FINISH_STATE;
  398. }
  399. if(bstate == need_more || bstate == finish_started)
  400. {
  401. if(zs.avail_out == 0)
  402. {
  403. last_flush_ = boost::none; /* avoid BUF_ERROR next call, see above */
  404. }
  405. return;
  406. /* If flush != Flush::none && avail_out == 0, the next call
  407. of deflate should use the same flush parameter to make sure
  408. that the flush is complete. So we don't have to output an
  409. empty block here, this will be done at next call. This also
  410. ensures that for a very small output buffer, we emit at most
  411. one empty block.
  412. */
  413. }
  414. if(bstate == block_done)
  415. {
  416. if(flush == Flush::partial)
  417. {
  418. tr_align();
  419. }
  420. else if(flush != Flush::block)
  421. {
  422. /* FULL_FLUSH or SYNC_FLUSH */
  423. tr_stored_block(nullptr, 0L, 0);
  424. /* For a full flush, this empty block will be recognized
  425. * as a special marker by inflate_sync().
  426. */
  427. if(flush == Flush::full)
  428. {
  429. clear_hash(); // forget history
  430. if(lookahead_ == 0)
  431. {
  432. strstart_ = 0;
  433. block_start_ = 0L;
  434. insert_ = 0;
  435. }
  436. }
  437. }
  438. flush_pending(zs);
  439. if(zs.avail_out == 0)
  440. {
  441. last_flush_ = boost::none; /* avoid BUF_ERROR at next call, see above */
  442. return;
  443. }
  444. }
  445. }
  446. if(flush == Flush::finish)
  447. {
  448. ec = error::end_of_stream;
  449. return;
  450. }
  451. }
  452. // VFALCO Warning: untested
  453. void
  454. deflate_stream::
  455. doDictionary(Byte const* dict, uInt dictLength, error_code& ec)
  456. {
  457. if(lookahead_)
  458. {
  459. ec = error::stream_error;
  460. return;
  461. }
  462. maybe_init();
  463. /* if dict would fill window, just replace the history */
  464. if(dictLength >= w_size_)
  465. {
  466. clear_hash();
  467. strstart_ = 0;
  468. block_start_ = 0L;
  469. insert_ = 0;
  470. dict += dictLength - w_size_; /* use the tail */
  471. dictLength = w_size_;
  472. }
  473. /* insert dict into window and hash */
  474. z_params zs;
  475. zs.avail_in = dictLength;
  476. zs.next_in = (const Byte *)dict;
  477. zs.avail_out = 0;
  478. zs.next_out = 0;
  479. fill_window(zs);
  480. while(lookahead_ >= minMatch)
  481. {
  482. uInt str = strstart_;
  483. uInt n = lookahead_ - (minMatch-1);
  484. do
  485. {
  486. update_hash(ins_h_, window_[str + minMatch-1]);
  487. prev_[str & w_mask_] = head_[ins_h_];
  488. head_[ins_h_] = (std::uint16_t)str;
  489. str++;
  490. }
  491. while(--n);
  492. strstart_ = str;
  493. lookahead_ = minMatch-1;
  494. fill_window(zs);
  495. }
  496. strstart_ += lookahead_;
  497. block_start_ = (long)strstart_;
  498. insert_ = lookahead_;
  499. lookahead_ = 0;
  500. match_length_ = prev_length_ = minMatch-1;
  501. match_available_ = 0;
  502. }
  503. void
  504. deflate_stream::
  505. doPrime(int bits, int value, error_code& ec)
  506. {
  507. maybe_init();
  508. if((Byte *)(d_buf_) < pending_out_ + ((Buf_size + 7) >> 3))
  509. {
  510. ec = error::need_buffers;
  511. return;
  512. }
  513. do
  514. {
  515. int put = Buf_size - bi_valid_;
  516. if(put > bits)
  517. put = bits;
  518. bi_buf_ |= (std::uint16_t)((value & ((1 << put) - 1)) << bi_valid_);
  519. bi_valid_ += put;
  520. tr_flush_bits();
  521. value >>= put;
  522. bits -= put;
  523. }
  524. while(bits);
  525. }
  526. void
  527. deflate_stream::
  528. doPending(unsigned* value, int* bits)
  529. {
  530. if(value != 0)
  531. *value = pending_;
  532. if(bits != 0)
  533. *bits = bi_valid_;
  534. }
  535. //--------------------------------------------------------------------------
  536. // Do lazy initialization
  537. void
  538. deflate_stream::
  539. init()
  540. {
  541. // Caller must set these:
  542. // w_bits_
  543. // hash_bits_
  544. // lit_bufsize_
  545. // level_
  546. // strategy_
  547. w_size_ = 1 << w_bits_;
  548. w_mask_ = w_size_ - 1;
  549. hash_size_ = 1 << hash_bits_;
  550. hash_mask_ = hash_size_ - 1;
  551. hash_shift_ = ((hash_bits_+minMatch-1)/minMatch);
  552. auto const nwindow = w_size_ * 2*sizeof(Byte);
  553. auto const nprev = w_size_ * sizeof(std::uint16_t);
  554. auto const nhead = hash_size_ * sizeof(std::uint16_t);
  555. auto const noverlay = lit_bufsize_ * (sizeof(std::uint16_t)+2);
  556. auto const needed = nwindow + nprev + nhead + noverlay;
  557. if(! buf_ || buf_size_ != needed)
  558. {
  559. buf_ = boost::make_unique_noinit<
  560. std::uint8_t[]>(needed);
  561. buf_size_ = needed;
  562. }
  563. window_ = reinterpret_cast<Byte*>(buf_.get());
  564. prev_ = reinterpret_cast<std::uint16_t*>(buf_.get() + nwindow);
  565. std::memset(prev_, 0, nprev);
  566. head_ = reinterpret_cast<std::uint16_t*>(buf_.get() + nwindow + nprev);
  567. /* We overlay pending_buf_ and d_buf_ + l_buf_. This works
  568. since the average output size for(length, distance)
  569. codes is <= 24 bits.
  570. */
  571. auto overlay = reinterpret_cast<std::uint16_t*>(
  572. buf_.get() + nwindow + nprev + nhead);
  573. // nothing written to window_ yet
  574. high_water_ = 0;
  575. pending_buf_ =
  576. reinterpret_cast<std::uint8_t*>(overlay);
  577. pending_buf_size_ =
  578. static_cast<std::uint32_t>(lit_bufsize_) *
  579. (sizeof(std::uint16_t) + 2L);
  580. d_buf_ = overlay + lit_bufsize_ / sizeof(std::uint16_t);
  581. l_buf_ = pending_buf_ + (1 + sizeof(std::uint16_t)) * lit_bufsize_;
  582. pending_ = 0;
  583. pending_out_ = pending_buf_;
  584. status_ = BUSY_STATE;
  585. last_flush_ = Flush::none;
  586. tr_init();
  587. lm_init();
  588. inited_ = true;
  589. }
  590. /* Initialize the "longest match" routines for a new zlib stream
  591. */
  592. void
  593. deflate_stream::
  594. lm_init()
  595. {
  596. window_size_ = (std::uint32_t)2L*w_size_;
  597. clear_hash();
  598. /* Set the default configuration parameters:
  599. */
  600. // VFALCO TODO just copy the config struct
  601. max_lazy_match_ = get_config(level_).max_lazy;
  602. good_match_ = get_config(level_).good_length;
  603. nice_match_ = get_config(level_).nice_length;
  604. max_chain_length_ = get_config(level_).max_chain;
  605. strstart_ = 0;
  606. block_start_ = 0L;
  607. lookahead_ = 0;
  608. insert_ = 0;
  609. match_length_ = prev_length_ = minMatch-1;
  610. match_available_ = 0;
  611. ins_h_ = 0;
  612. }
  613. // Initialize a new block.
  614. //
  615. void
  616. deflate_stream::
  617. init_block()
  618. {
  619. for(int n = 0; n < lCodes; n++)
  620. dyn_ltree_[n].fc = 0;
  621. for(int n = 0; n < dCodes; n++)
  622. dyn_dtree_[n].fc = 0;
  623. for(int n = 0; n < blCodes; n++)
  624. bl_tree_[n].fc = 0;
  625. dyn_ltree_[END_BLOCK].fc = 1;
  626. opt_len_ = 0L;
  627. static_len_ = 0L;
  628. last_lit_ = 0;
  629. matches_ = 0;
  630. }
  631. /* Restore the heap property by moving down the tree starting at node k,
  632. exchanging a node with the smallest of its two sons if necessary,
  633. stopping when the heap property is re-established (each father smaller
  634. than its two sons).
  635. */
  636. void
  637. deflate_stream::
  638. pqdownheap(
  639. ct_data const* tree, // the tree to restore
  640. int k) // node to move down
  641. {
  642. int v = heap_[k];
  643. int j = k << 1; // left son of k
  644. while(j <= heap_len_)
  645. {
  646. // Set j to the smallest of the two sons:
  647. if(j < heap_len_ &&
  648. smaller(tree, heap_[j+1], heap_[j]))
  649. j++;
  650. // Exit if v is smaller than both sons
  651. if(smaller(tree, v, heap_[j]))
  652. break;
  653. // Exchange v with the smallest son
  654. heap_[k] = heap_[j];
  655. k = j;
  656. // And continue down the tree,
  657. // setting j to the left son of k
  658. j <<= 1;
  659. }
  660. heap_[k] = v;
  661. }
  662. /* Remove the smallest element from the heap and recreate the heap
  663. with one less element. Updates heap and heap_len.
  664. */
  665. void
  666. deflate_stream::
  667. pqremove(ct_data const* tree, int& top)
  668. {
  669. top = heap_[kSmallest];
  670. heap_[kSmallest] = heap_[heap_len_--];
  671. pqdownheap(tree, kSmallest);
  672. }
  673. /* Compute the optimal bit lengths for a tree and update the total bit length
  674. for the current block.
  675. IN assertion: the fields freq and dad are set, heap[heap_max] and
  676. above are the tree nodes sorted by increasing frequency.
  677. OUT assertions: the field len is set to the optimal bit length, the
  678. array bl_count contains the frequencies for each bit length.
  679. The length opt_len is updated; static_len is also updated if stree is
  680. not null.
  681. */
  682. void
  683. deflate_stream::
  684. gen_bitlen(tree_desc *desc)
  685. {
  686. ct_data *tree = desc->dyn_tree;
  687. int max_code = desc->max_code;
  688. ct_data const* stree = desc->stat_desc->static_tree;
  689. std::uint8_t const *extra = desc->stat_desc->extra_bits;
  690. int base = desc->stat_desc->extra_base;
  691. int max_length = desc->stat_desc->max_length;
  692. int h; // heap index
  693. int n, m; // iterate over the tree elements
  694. int bits; // bit length
  695. int xbits; // extra bits
  696. std::uint16_t f; // frequency
  697. int overflow = 0; // number of elements with bit length too large
  698. std::fill(&bl_count_[0], &bl_count_[maxBits+1], std::uint16_t{0});
  699. /* In a first pass, compute the optimal bit lengths (which may
  700. * overflow in the case of the bit length tree).
  701. */
  702. tree[heap_[heap_max_]].dl = 0; // root of the heap
  703. for(h = heap_max_+1; h < HEAP_SIZE; h++) {
  704. n = heap_[h];
  705. bits = tree[tree[n].dl].dl + 1;
  706. if(bits > max_length) bits = max_length, overflow++;
  707. // We overwrite tree[n].dl which is no longer needed
  708. tree[n].dl = (std::uint16_t)bits;
  709. if(n > max_code)
  710. continue; // not a leaf node
  711. bl_count_[bits]++;
  712. xbits = 0;
  713. if(n >= base)
  714. xbits = extra[n-base];
  715. f = tree[n].fc;
  716. opt_len_ += (std::uint32_t)f * (bits + xbits);
  717. if(stree)
  718. static_len_ += (std::uint32_t)f * (stree[n].dl + xbits);
  719. }
  720. if(overflow == 0)
  721. return;
  722. // Find the first bit length which could increase:
  723. do
  724. {
  725. bits = max_length-1;
  726. while(bl_count_[bits] == 0)
  727. bits--;
  728. bl_count_[bits]--; // move one leaf down the tree
  729. bl_count_[bits+1] += 2; // move one overflow item as its brother
  730. bl_count_[max_length]--;
  731. /* The brother of the overflow item also moves one step up,
  732. * but this does not affect bl_count[max_length]
  733. */
  734. overflow -= 2;
  735. }
  736. while(overflow > 0);
  737. /* Now recompute all bit lengths, scanning in increasing frequency.
  738. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  739. * lengths instead of fixing only the wrong ones. This idea is taken
  740. * from 'ar' written by Haruhiko Okumura.)
  741. */
  742. for(bits = max_length; bits != 0; bits--)
  743. {
  744. n = bl_count_[bits];
  745. while(n != 0)
  746. {
  747. m = heap_[--h];
  748. if(m > max_code)
  749. continue;
  750. if((unsigned) tree[m].dl != (unsigned) bits)
  751. {
  752. opt_len_ += ((long)bits - (long)tree[m].dl) *(long)tree[m].fc;
  753. tree[m].dl = (std::uint16_t)bits;
  754. }
  755. n--;
  756. }
  757. }
  758. }
  759. /* Construct one Huffman tree and assigns the code bit strings and lengths.
  760. Update the total bit length for the current block.
  761. IN assertion: the field freq is set for all tree elements.
  762. OUT assertions: the fields len and code are set to the optimal bit length
  763. and corresponding code. The length opt_len is updated; static_len is
  764. also updated if stree is not null. The field max_code is set.
  765. */
  766. void
  767. deflate_stream::
  768. build_tree(tree_desc *desc)
  769. {
  770. ct_data *tree = desc->dyn_tree;
  771. ct_data const* stree = desc->stat_desc->static_tree;
  772. int elems = desc->stat_desc->elems;
  773. int n, m; // iterate over heap elements
  774. int max_code = -1; // largest code with non zero frequency
  775. int node; // new node being created
  776. /* Construct the initial heap, with least frequent element in
  777. * heap[kSmallest]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  778. * heap[0] is not used.
  779. */
  780. heap_len_ = 0;
  781. heap_max_ = HEAP_SIZE;
  782. for(n = 0; n < elems; n++)
  783. {
  784. if(tree[n].fc != 0)
  785. {
  786. heap_[++(heap_len_)] = max_code = n;
  787. depth_[n] = 0;
  788. }
  789. else
  790. {
  791. tree[n].dl = 0;
  792. }
  793. }
  794. /* The pkzip format requires that at least one distance code exists,
  795. * and that at least one bit should be sent even if there is only one
  796. * possible code. So to avoid special checks later on we force at least
  797. * two codes of non zero frequency.
  798. */
  799. while(heap_len_ < 2)
  800. {
  801. node = heap_[++(heap_len_)] = (max_code < 2 ? ++max_code : 0);
  802. tree[node].fc = 1;
  803. depth_[node] = 0;
  804. opt_len_--;
  805. if(stree)
  806. static_len_ -= stree[node].dl;
  807. // node is 0 or 1 so it does not have extra bits
  808. }
  809. desc->max_code = max_code;
  810. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  811. * establish sub-heaps of increasing lengths:
  812. */
  813. for(n = heap_len_/2; n >= 1; n--)
  814. pqdownheap(tree, n);
  815. /* Construct the Huffman tree by repeatedly combining the least two
  816. * frequent nodes.
  817. */
  818. node = elems; /* next internal node of the tree */
  819. do
  820. {
  821. pqremove(tree, n); /* n = node of least frequency */
  822. m = heap_[kSmallest]; /* m = node of next least frequency */
  823. heap_[--(heap_max_)] = n; /* keep the nodes sorted by frequency */
  824. heap_[--(heap_max_)] = m;
  825. /* Create a new node father of n and m */
  826. tree[node].fc = tree[n].fc + tree[m].fc;
  827. depth_[node] = (std::uint8_t)((depth_[n] >= depth_[m] ?
  828. depth_[n] : depth_[m]) + 1);
  829. tree[n].dl = tree[m].dl = (std::uint16_t)node;
  830. /* and insert the new node in the heap */
  831. heap_[kSmallest] = node++;
  832. pqdownheap(tree, kSmallest);
  833. }
  834. while(heap_len_ >= 2);
  835. heap_[--(heap_max_)] = heap_[kSmallest];
  836. /* At this point, the fields freq and dad are set. We can now
  837. * generate the bit lengths.
  838. */
  839. gen_bitlen((tree_desc *)desc);
  840. /* The field len is now set, we can generate the bit codes */
  841. gen_codes(tree, max_code, bl_count_);
  842. }
  843. /* Scan a literal or distance tree to determine the frequencies
  844. of the codes in the bit length tree.
  845. */
  846. void
  847. deflate_stream::
  848. scan_tree(
  849. ct_data *tree, // the tree to be scanned
  850. int max_code) // and its largest code of non zero frequency
  851. {
  852. int n; // iterates over all tree elements
  853. int prevlen = -1; // last emitted length
  854. int curlen; // length of current code
  855. int nextlen = tree[0].dl; // length of next code
  856. std::uint16_t count = 0; // repeat count of the current code
  857. int max_count = 7; // max repeat count
  858. int min_count = 4; // min repeat count
  859. if(nextlen == 0)
  860. {
  861. max_count = 138;
  862. min_count = 3;
  863. }
  864. tree[max_code+1].dl = (std::uint16_t)0xffff; // guard
  865. for(n = 0; n <= max_code; n++)
  866. {
  867. curlen = nextlen; nextlen = tree[n+1].dl;
  868. if(++count < max_count && curlen == nextlen)
  869. {
  870. continue;
  871. }
  872. else if(count < min_count)
  873. {
  874. bl_tree_[curlen].fc += count;
  875. }
  876. else if(curlen != 0)
  877. {
  878. if(curlen != prevlen) bl_tree_[curlen].fc++;
  879. bl_tree_[REP_3_6].fc++;
  880. }
  881. else if(count <= 10)
  882. {
  883. bl_tree_[REPZ_3_10].fc++;
  884. }
  885. else
  886. {
  887. bl_tree_[REPZ_11_138].fc++;
  888. }
  889. count = 0;
  890. prevlen = curlen;
  891. if(nextlen == 0)
  892. {
  893. max_count = 138;
  894. min_count = 3;
  895. }
  896. else if(curlen == nextlen)
  897. {
  898. max_count = 6;
  899. min_count = 3;
  900. }
  901. else
  902. {
  903. max_count = 7;
  904. min_count = 4;
  905. }
  906. }
  907. }
  908. /* Send a literal or distance tree in compressed form,
  909. using the codes in bl_tree.
  910. */
  911. void
  912. deflate_stream::
  913. send_tree(
  914. ct_data *tree, // the tree to be scanned
  915. int max_code) // and its largest code of non zero frequency
  916. {
  917. int n; // iterates over all tree elements
  918. int prevlen = -1; // last emitted length
  919. int curlen; // length of current code
  920. int nextlen = tree[0].dl; // length of next code
  921. int count = 0; // repeat count of the current code
  922. int max_count = 7; // max repeat count
  923. int min_count = 4; // min repeat count
  924. // tree[max_code+1].dl = -1; // guard already set
  925. if(nextlen == 0)
  926. {
  927. max_count = 138;
  928. min_count = 3;
  929. }
  930. for(n = 0; n <= max_code; n++)
  931. {
  932. curlen = nextlen;
  933. nextlen = tree[n+1].dl;
  934. if(++count < max_count && curlen == nextlen)
  935. {
  936. continue;
  937. }
  938. else if(count < min_count)
  939. {
  940. do
  941. {
  942. send_code(curlen, bl_tree_);
  943. }
  944. while (--count != 0);
  945. }
  946. else if(curlen != 0)
  947. {
  948. if(curlen != prevlen)
  949. {
  950. send_code(curlen, bl_tree_);
  951. count--;
  952. }
  953. BOOST_ASSERT(count >= 3 && count <= 6);
  954. send_code(REP_3_6, bl_tree_);
  955. send_bits(count-3, 2);
  956. }
  957. else if(count <= 10)
  958. {
  959. send_code(REPZ_3_10, bl_tree_);
  960. send_bits(count-3, 3);
  961. }
  962. else
  963. {
  964. send_code(REPZ_11_138, bl_tree_);
  965. send_bits(count-11, 7);
  966. }
  967. count = 0;
  968. prevlen = curlen;
  969. if(nextlen == 0)
  970. {
  971. max_count = 138;
  972. min_count = 3;
  973. }
  974. else if(curlen == nextlen)
  975. {
  976. max_count = 6;
  977. min_count = 3;
  978. }
  979. else
  980. {
  981. max_count = 7;
  982. min_count = 4;
  983. }
  984. }
  985. }
  986. /* Construct the Huffman tree for the bit lengths and return
  987. the index in bl_order of the last bit length code to send.
  988. */
  989. int
  990. deflate_stream::
  991. build_bl_tree()
  992. {
  993. int max_blindex; // index of last bit length code of non zero freq
  994. // Determine the bit length frequencies for literal and distance trees
  995. scan_tree((ct_data *)dyn_ltree_, l_desc_.max_code);
  996. scan_tree((ct_data *)dyn_dtree_, d_desc_.max_code);
  997. // Build the bit length tree:
  998. build_tree((tree_desc *)(&(bl_desc_)));
  999. /* opt_len now includes the length of the tree representations, except
  1000. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1001. */
  1002. /* Determine the number of bit length codes to send. The pkzip format
  1003. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1004. * 3 but the actual value used is 4.)
  1005. */
  1006. for(max_blindex = blCodes-1; max_blindex >= 3; max_blindex--)
  1007. {
  1008. if(bl_tree_[lut_.bl_order[max_blindex]].dl != 0)
  1009. break;
  1010. }
  1011. // Update opt_len to include the bit length tree and counts
  1012. opt_len_ += 3*(max_blindex+1) + 5+5+4;
  1013. return max_blindex;
  1014. }
  1015. /* Send the header for a block using dynamic Huffman trees: the counts,
  1016. the lengths of the bit length codes, the literal tree and the distance
  1017. tree.
  1018. IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1019. */
  1020. void
  1021. deflate_stream::
  1022. send_all_trees(
  1023. int lcodes,
  1024. int dcodes,
  1025. int blcodes) // number of codes for each tree
  1026. {
  1027. int rank; // index in bl_order
  1028. BOOST_ASSERT(lcodes >= 257 && dcodes >= 1 && blcodes >= 4);
  1029. BOOST_ASSERT(lcodes <= lCodes && dcodes <= dCodes && blcodes <= blCodes);
  1030. send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
  1031. send_bits(dcodes-1, 5);
  1032. send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
  1033. for(rank = 0; rank < blcodes; rank++)
  1034. send_bits(bl_tree_[lut_.bl_order[rank]].dl, 3);
  1035. send_tree((ct_data *)dyn_ltree_, lcodes-1); // literal tree
  1036. send_tree((ct_data *)dyn_dtree_, dcodes-1); // distance tree
  1037. }
  1038. /* Send the block data compressed using the given Huffman trees
  1039. */
  1040. void
  1041. deflate_stream::
  1042. compress_block(
  1043. ct_data const* ltree, // literal tree
  1044. ct_data const* dtree) // distance tree
  1045. {
  1046. unsigned dist; /* distance of matched string */
  1047. int lc; /* match length or unmatched char (if dist == 0) */
  1048. unsigned lx = 0; /* running index in l_buf */
  1049. unsigned code; /* the code to send */
  1050. int extra; /* number of extra bits to send */
  1051. if(last_lit_ != 0)
  1052. {
  1053. do
  1054. {
  1055. dist = d_buf_[lx];
  1056. lc = l_buf_[lx++];
  1057. if(dist == 0)
  1058. {
  1059. send_code(lc, ltree); /* send a literal byte */
  1060. }
  1061. else
  1062. {
  1063. /* Here, lc is the match length - minMatch */
  1064. code = lut_.length_code[lc];
  1065. send_code(code+literals+1, ltree); /* send the length code */
  1066. extra = lut_.extra_lbits[code];
  1067. if(extra != 0)
  1068. {
  1069. lc -= lut_.base_length[code];
  1070. send_bits(lc, extra); /* send the extra length bits */
  1071. }
  1072. dist--; /* dist is now the match distance - 1 */
  1073. code = d_code(dist);
  1074. BOOST_ASSERT(code < dCodes);
  1075. send_code(code, dtree); /* send the distance code */
  1076. extra = lut_.extra_dbits[code];
  1077. if(extra != 0)
  1078. {
  1079. dist -= lut_.base_dist[code];
  1080. send_bits(dist, extra); /* send the extra distance bits */
  1081. }
  1082. } /* literal or match pair ? */
  1083. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  1084. BOOST_ASSERT((uInt)(pending_) < lit_bufsize_ + 2*lx);
  1085. }
  1086. while(lx < last_lit_);
  1087. }
  1088. send_code(END_BLOCK, ltree);
  1089. }
  1090. /* Check if the data type is TEXT or BINARY, using the following algorithm:
  1091. - TEXT if the two conditions below are satisfied:
  1092. a) There are no non-portable control characters belonging to the
  1093. "black list" (0..6, 14..25, 28..31).
  1094. b) There is at least one printable character belonging to the
  1095. "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  1096. - BINARY otherwise.
  1097. - The following partially-portable control characters form a
  1098. "gray list" that is ignored in this detection algorithm:
  1099. (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  1100. IN assertion: the fields fc of dyn_ltree are set.
  1101. */
  1102. int
  1103. deflate_stream::
  1104. detect_data_type()
  1105. {
  1106. /* black_mask is the bit mask of black-listed bytes
  1107. * set bits 0..6, 14..25, and 28..31
  1108. * 0xf3ffc07f = binary 11110011111111111100000001111111
  1109. */
  1110. unsigned long black_mask = 0xf3ffc07fUL;
  1111. int n;
  1112. // Check for non-textual ("black-listed") bytes.
  1113. for(n = 0; n <= 31; n++, black_mask >>= 1)
  1114. if((black_mask & 1) && (dyn_ltree_[n].fc != 0))
  1115. return binary;
  1116. // Check for textual ("white-listed") bytes. */
  1117. if(dyn_ltree_[9].fc != 0 || dyn_ltree_[10].fc != 0
  1118. || dyn_ltree_[13].fc != 0)
  1119. return text;
  1120. for(n = 32; n < literals; n++)
  1121. if(dyn_ltree_[n].fc != 0)
  1122. return text;
  1123. /* There are no "black-listed" or "white-listed" bytes:
  1124. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  1125. */
  1126. return binary;
  1127. }
  1128. /* Flush the bit buffer and align the output on a byte boundary
  1129. */
  1130. void
  1131. deflate_stream::
  1132. bi_windup()
  1133. {
  1134. if(bi_valid_ > 8)
  1135. put_short(bi_buf_);
  1136. else if(bi_valid_ > 0)
  1137. put_byte((Byte)bi_buf_);
  1138. bi_buf_ = 0;
  1139. bi_valid_ = 0;
  1140. }
  1141. /* Flush the bit buffer, keeping at most 7 bits in it.
  1142. */
  1143. void
  1144. deflate_stream::
  1145. bi_flush()
  1146. {
  1147. if(bi_valid_ == 16)
  1148. {
  1149. put_short(bi_buf_);
  1150. bi_buf_ = 0;
  1151. bi_valid_ = 0;
  1152. }
  1153. else if(bi_valid_ >= 8)
  1154. {
  1155. put_byte((Byte)bi_buf_);
  1156. bi_buf_ >>= 8;
  1157. bi_valid_ -= 8;
  1158. }
  1159. }
  1160. /* Copy a stored block, storing first the length and its
  1161. one's complement if requested.
  1162. */
  1163. void
  1164. deflate_stream::
  1165. copy_block(
  1166. char *buf, // the input data
  1167. unsigned len, // its length
  1168. int header) // true if block header must be written
  1169. {
  1170. bi_windup(); // align on byte boundary
  1171. if(header)
  1172. {
  1173. put_short((std::uint16_t)len);
  1174. put_short((std::uint16_t)~len);
  1175. }
  1176. if(buf)
  1177. std::memcpy(&pending_buf_[pending_], buf, len);
  1178. pending_ += len;
  1179. }
  1180. //------------------------------------------------------------------------------
  1181. /* Initialize the tree data structures for a new zlib stream.
  1182. */
  1183. void
  1184. deflate_stream::
  1185. tr_init()
  1186. {
  1187. l_desc_.dyn_tree = dyn_ltree_;
  1188. l_desc_.stat_desc = &lut_.l_desc;
  1189. d_desc_.dyn_tree = dyn_dtree_;
  1190. d_desc_.stat_desc = &lut_.d_desc;
  1191. bl_desc_.dyn_tree = bl_tree_;
  1192. bl_desc_.stat_desc = &lut_.bl_desc;
  1193. bi_buf_ = 0;
  1194. bi_valid_ = 0;
  1195. // Initialize the first block of the first file:
  1196. init_block();
  1197. }
  1198. /* Send one empty static block to give enough lookahead for inflate.
  1199. This takes 10 bits, of which 7 may remain in the bit buffer.
  1200. */
  1201. void
  1202. deflate_stream::
  1203. tr_align()
  1204. {
  1205. send_bits(STATIC_TREES<<1, 3);
  1206. send_code(END_BLOCK, lut_.ltree);
  1207. bi_flush();
  1208. }
  1209. /* Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
  1210. */
  1211. void
  1212. deflate_stream::
  1213. tr_flush_bits()
  1214. {
  1215. bi_flush();
  1216. }
  1217. /* Send a stored block
  1218. */
  1219. void
  1220. deflate_stream::
  1221. tr_stored_block(
  1222. char *buf, // input block
  1223. std::uint32_t stored_len, // length of input block
  1224. int last) // one if this is the last block for a file
  1225. {
  1226. send_bits((STORED_BLOCK<<1)+last, 3); // send block type
  1227. copy_block(buf, (unsigned)stored_len, 1); // with header
  1228. }
  1229. void
  1230. deflate_stream::
  1231. tr_tally_dist(std::uint16_t dist, std::uint8_t len, bool& flush)
  1232. {
  1233. d_buf_[last_lit_] = dist;
  1234. l_buf_[last_lit_++] = len;
  1235. dist--;
  1236. dyn_ltree_[lut_.length_code[len]+literals+1].fc++;
  1237. dyn_dtree_[d_code(dist)].fc++;
  1238. flush = (last_lit_ == lit_bufsize_-1);
  1239. }
  1240. void
  1241. deflate_stream::
  1242. tr_tally_lit(std::uint8_t c, bool& flush)
  1243. {
  1244. d_buf_[last_lit_] = 0;
  1245. l_buf_[last_lit_++] = c;
  1246. dyn_ltree_[c].fc++;
  1247. flush = (last_lit_ == lit_bufsize_-1);
  1248. }
  1249. //------------------------------------------------------------------------------
  1250. /* Determine the best encoding for the current block: dynamic trees,
  1251. static trees or store, and output the encoded block to the zip file.
  1252. */
  1253. void
  1254. deflate_stream::
  1255. tr_flush_block(
  1256. z_params& zs,
  1257. char *buf, // input block, or NULL if too old
  1258. std::uint32_t stored_len, // length of input block
  1259. int last) // one if this is the last block for a file
  1260. {
  1261. std::uint32_t opt_lenb;
  1262. std::uint32_t static_lenb; // opt_len and static_len in bytes
  1263. int max_blindex = 0; // index of last bit length code of non zero freq
  1264. // Build the Huffman trees unless a stored block is forced
  1265. if(level_ > 0)
  1266. {
  1267. // Check if the file is binary or text
  1268. if(zs.data_type == unknown)
  1269. zs.data_type = detect_data_type();
  1270. // Construct the literal and distance trees
  1271. build_tree((tree_desc *)(&(l_desc_)));
  1272. build_tree((tree_desc *)(&(d_desc_)));
  1273. /* At this point, opt_len and static_len are the total bit lengths of
  1274. * the compressed block data, excluding the tree representations.
  1275. */
  1276. /* Build the bit length tree for the above two trees, and get the index
  1277. * in bl_order of the last bit length code to send.
  1278. */
  1279. max_blindex = build_bl_tree();
  1280. /* Determine the best encoding. Compute the block lengths in bytes. */
  1281. opt_lenb = (opt_len_+3+7)>>3;
  1282. static_lenb = (static_len_+3+7)>>3;
  1283. if(static_lenb <= opt_lenb)
  1284. opt_lenb = static_lenb;
  1285. }
  1286. else
  1287. {
  1288. // VFALCO This assertion fails even in the original ZLib,
  1289. // happens with strategy == Z_HUFFMAN_ONLY, see:
  1290. // https://github.com/madler/zlib/issues/172
  1291. #if 0
  1292. BOOST_ASSERT(buf);
  1293. #endif
  1294. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  1295. }
  1296. #ifdef FORCE_STORED
  1297. if(buf != (char*)0) { /* force stored block */
  1298. #else
  1299. if(stored_len+4 <= opt_lenb && buf != (char*)0) {
  1300. /* 4: two words for the lengths */
  1301. #endif
  1302. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1303. * Otherwise we can't have processed more than WSIZE input bytes since
  1304. * the last block flush, because compression would have been
  1305. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1306. * transform a block into a stored block.
  1307. */
  1308. tr_stored_block(buf, stored_len, last);
  1309. #ifdef FORCE_STATIC
  1310. }
  1311. else if(static_lenb >= 0)
  1312. {
  1313. // force static trees
  1314. #else
  1315. }
  1316. else if(strategy_ == Strategy::fixed || static_lenb == opt_lenb)
  1317. {
  1318. #endif
  1319. send_bits((STATIC_TREES<<1)+last, 3);
  1320. compress_block(lut_.ltree, lut_.dtree);
  1321. }
  1322. else
  1323. {
  1324. send_bits((DYN_TREES<<1)+last, 3);
  1325. send_all_trees(l_desc_.max_code+1, d_desc_.max_code+1,
  1326. max_blindex+1);
  1327. compress_block((const ct_data *)dyn_ltree_,
  1328. (const ct_data *)dyn_dtree_);
  1329. }
  1330. /* The above check is made mod 2^32, for files larger than 512 MB
  1331. * and std::size_t implemented on 32 bits.
  1332. */
  1333. init_block();
  1334. if(last)
  1335. bi_windup();
  1336. }
  1337. void
  1338. deflate_stream::
  1339. fill_window(z_params& zs)
  1340. {
  1341. unsigned n, m;
  1342. unsigned more; // Amount of free space at the end of the window.
  1343. std::uint16_t *p;
  1344. uInt wsize = w_size_;
  1345. do
  1346. {
  1347. more = (unsigned)(window_size_ -
  1348. (std::uint32_t)lookahead_ -(std::uint32_t)strstart_);
  1349. // VFALCO We don't support systems below 32-bit
  1350. #if 0
  1351. // Deal with !@#$% 64K limit:
  1352. if(sizeof(int) <= 2)
  1353. {
  1354. if(more == 0 && strstart_ == 0 && lookahead_ == 0)
  1355. {
  1356. more = wsize;
  1357. }
  1358. else if(more == (unsigned)(-1))
  1359. {
  1360. /* Very unlikely, but possible on 16 bit machine if
  1361. * strstart == 0 && lookahead == 1 (input done a byte at time)
  1362. */
  1363. more--;
  1364. }
  1365. }
  1366. #endif
  1367. /* If the window is almost full and there is insufficient lookahead,
  1368. move the upper half to the lower one to make room in the upper half.
  1369. */
  1370. if(strstart_ >= wsize+max_dist())
  1371. {
  1372. std::memcpy(window_, window_+wsize, (unsigned)wsize);
  1373. match_start_ -= wsize;
  1374. strstart_ -= wsize; // we now have strstart >= max_dist
  1375. block_start_ -= (long) wsize;
  1376. /* Slide the hash table (could be avoided with 32 bit values
  1377. at the expense of memory usage). We slide even when level == 0
  1378. to keep the hash table consistent if we switch back to level > 0
  1379. later. (Using level 0 permanently is not an optimal usage of
  1380. zlib, so we don't care about this pathological case.)
  1381. */
  1382. n = hash_size_;
  1383. p = &head_[n];
  1384. do
  1385. {
  1386. m = *--p;
  1387. *p = (std::uint16_t)(m >= wsize ? m-wsize : 0);
  1388. }
  1389. while(--n);
  1390. n = wsize;
  1391. p = &prev_[n];
  1392. do
  1393. {
  1394. m = *--p;
  1395. *p = (std::uint16_t)(m >= wsize ? m-wsize : 0);
  1396. /* If n is not on any hash chain, prev[n] is garbage but
  1397. its value will never be used.
  1398. */
  1399. }
  1400. while(--n);
  1401. more += wsize;
  1402. }
  1403. if(zs.avail_in == 0)
  1404. break;
  1405. /* If there was no sliding:
  1406. strstart <= WSIZE+max_dist-1 && lookahead <= kMinLookahead - 1 &&
  1407. more == window_size - lookahead - strstart
  1408. => more >= window_size - (kMinLookahead-1 + WSIZE + max_dist-1)
  1409. => more >= window_size - 2*WSIZE + 2
  1410. In the BIG_MEM or MMAP case (not yet supported),
  1411. window_size == input_size + kMinLookahead &&
  1412. strstart + lookahead_ <= input_size => more >= kMinLookahead.
  1413. Otherwise, window_size == 2*WSIZE so more >= 2.
  1414. If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1415. */
  1416. n = read_buf(zs, window_ + strstart_ + lookahead_, more);
  1417. lookahead_ += n;
  1418. // Initialize the hash value now that we have some input:
  1419. if(lookahead_ + insert_ >= minMatch)
  1420. {
  1421. uInt str = strstart_ - insert_;
  1422. ins_h_ = window_[str];
  1423. update_hash(ins_h_, window_[str + 1]);
  1424. while(insert_)
  1425. {
  1426. update_hash(ins_h_, window_[str + minMatch-1]);
  1427. prev_[str & w_mask_] = head_[ins_h_];
  1428. head_[ins_h_] = (std::uint16_t)str;
  1429. str++;
  1430. insert_--;
  1431. if(lookahead_ + insert_ < minMatch)
  1432. break;
  1433. }
  1434. }
  1435. /* If the whole input has less than minMatch bytes, ins_h is garbage,
  1436. but this is not important since only literal bytes will be emitted.
  1437. */
  1438. }
  1439. while(lookahead_ < kMinLookahead && zs.avail_in != 0);
  1440. /* If the kWinInit bytes after the end of the current data have never been
  1441. written, then zero those bytes in order to avoid memory check reports of
  1442. the use of uninitialized (or uninitialised as Julian writes) bytes by
  1443. the longest match routines. Update the high water mark for the next
  1444. time through here. kWinInit is set to maxMatch since the longest match
  1445. routines allow scanning to strstart + maxMatch, ignoring lookahead.
  1446. */
  1447. if(high_water_ < window_size_)
  1448. {
  1449. std::uint32_t curr = strstart_ + (std::uint32_t)(lookahead_);
  1450. std::uint32_t winit;
  1451. if(high_water_ < curr)
  1452. {
  1453. /* Previous high water mark below current data -- zero kWinInit
  1454. bytes or up to end of window, whichever is less.
  1455. */
  1456. winit = window_size_ - curr;
  1457. if(winit > kWinInit)
  1458. winit = kWinInit;
  1459. std::memset(window_ + curr, 0, (unsigned)winit);
  1460. high_water_ = curr + winit;
  1461. }
  1462. else if(high_water_ < (std::uint32_t)curr + kWinInit)
  1463. {
  1464. /* High water mark at or above current data, but below current data
  1465. plus kWinInit -- zero out to current data plus kWinInit, or up
  1466. to end of window, whichever is less.
  1467. */
  1468. winit = (std::uint32_t)curr + kWinInit - high_water_;
  1469. if(winit > window_size_ - high_water_)
  1470. winit = window_size_ - high_water_;
  1471. std::memset(window_ + high_water_, 0, (unsigned)winit);
  1472. high_water_ += winit;
  1473. }
  1474. }
  1475. }
  1476. /* Flush as much pending output as possible. All write() output goes
  1477. through this function so some applications may wish to modify it
  1478. to avoid allocating a large strm->next_out buffer and copying into it.
  1479. (See also read_buf()).
  1480. */
  1481. void
  1482. deflate_stream::
  1483. flush_pending(z_params& zs)
  1484. {
  1485. tr_flush_bits();
  1486. auto len = clamp(pending_, zs.avail_out);
  1487. if(len == 0)
  1488. return;
  1489. std::memcpy(zs.next_out, pending_out_, len);
  1490. zs.next_out =
  1491. static_cast<std::uint8_t*>(zs.next_out) + len;
  1492. pending_out_ += len;
  1493. zs.total_out += len;
  1494. zs.avail_out -= len;
  1495. pending_ -= len;
  1496. if(pending_ == 0)
  1497. pending_out_ = pending_buf_;
  1498. }
  1499. /* Flush the current block, with given end-of-file flag.
  1500. IN assertion: strstart is set to the end of the current match.
  1501. */
  1502. void
  1503. deflate_stream::
  1504. flush_block(z_params& zs, bool last)
  1505. {
  1506. tr_flush_block(zs,
  1507. (block_start_ >= 0L ?
  1508. (char *)&window_[(unsigned)block_start_] :
  1509. (char *)0),
  1510. (std::uint32_t)((long)strstart_ - block_start_),
  1511. last);
  1512. block_start_ = strstart_;
  1513. flush_pending(zs);
  1514. }
  1515. /* Read a new buffer from the current input stream, update the adler32
  1516. and total number of bytes read. All write() input goes through
  1517. this function so some applications may wish to modify it to avoid
  1518. allocating a large strm->next_in buffer and copying from it.
  1519. (See also flush_pending()).
  1520. */
  1521. int
  1522. deflate_stream::
  1523. read_buf(z_params& zs, Byte *buf, unsigned size)
  1524. {
  1525. auto len = clamp(zs.avail_in, size);
  1526. if(len == 0)
  1527. return 0;
  1528. zs.avail_in -= len;
  1529. std::memcpy(buf, zs.next_in, len);
  1530. zs.next_in = static_cast<
  1531. std::uint8_t const*>(zs.next_in) + len;
  1532. zs.total_in += len;
  1533. return (int)len;
  1534. }
  1535. /* Set match_start to the longest match starting at the given string and
  1536. return its length. Matches shorter or equal to prev_length are discarded,
  1537. in which case the result is equal to prev_length and match_start is
  1538. garbage.
  1539. IN assertions: cur_match is the head of the hash chain for the current
  1540. string (strstart) and its distance is <= max_dist, and prev_length >= 1
  1541. OUT assertion: the match length is not greater than s->lookahead_.
  1542. For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1543. match.S. The code will be functionally equivalent.
  1544. */
  1545. uInt
  1546. deflate_stream::
  1547. longest_match(IPos cur_match)
  1548. {
  1549. unsigned chain_length = max_chain_length_;/* max hash chain length */
  1550. Byte *scan = window_ + strstart_; /* current string */
  1551. Byte *match; /* matched string */
  1552. int len; /* length of current match */
  1553. int best_len = prev_length_; /* best match length so far */
  1554. int nice_match = nice_match_; /* stop if match long enough */
  1555. IPos limit = strstart_ > (IPos)max_dist() ?
  1556. strstart_ - (IPos)max_dist() : 0;
  1557. /* Stop when cur_match becomes <= limit. To simplify the code,
  1558. * we prevent matches with the string of window index 0.
  1559. */
  1560. std::uint16_t *prev = prev_;
  1561. uInt wmask = w_mask_;
  1562. Byte *strend = window_ + strstart_ + maxMatch;
  1563. Byte scan_end1 = scan[best_len-1];
  1564. Byte scan_end = scan[best_len];
  1565. /* The code is optimized for HASH_BITS >= 8 and maxMatch-2 multiple of 16.
  1566. * It is easy to get rid of this optimization if necessary.
  1567. */
  1568. BOOST_ASSERT(hash_bits_ >= 8 && maxMatch == 258);
  1569. /* Do not waste too much time if we already have a good match: */
  1570. if(prev_length_ >= good_match_) {
  1571. chain_length >>= 2;
  1572. }
  1573. /* Do not look for matches beyond the end of the input. This is necessary
  1574. * to make deflate deterministic.
  1575. */
  1576. if((uInt)nice_match > lookahead_)
  1577. nice_match = lookahead_;
  1578. BOOST_ASSERT((std::uint32_t)strstart_ <= window_size_-kMinLookahead);
  1579. do {
  1580. BOOST_ASSERT(cur_match < strstart_);
  1581. match = window_ + cur_match;
  1582. /* Skip to next match if the match length cannot increase
  1583. * or if the match length is less than 2. Note that the checks below
  1584. * for insufficient lookahead only occur occasionally for performance
  1585. * reasons. Therefore uninitialized memory will be accessed, and
  1586. * conditional jumps will be made that depend on those values.
  1587. * However the length of the match is limited to the lookahead, so
  1588. * the output of deflate is not affected by the uninitialized values.
  1589. */
  1590. if( match[best_len] != scan_end ||
  1591. match[best_len-1] != scan_end1 ||
  1592. *match != *scan ||
  1593. *++match != scan[1])
  1594. continue;
  1595. /* The check at best_len-1 can be removed because it will be made
  1596. * again later. (This heuristic is not always a win.)
  1597. * It is not necessary to compare scan[2] and match[2] since they
  1598. * are always equal when the other bytes match, given that
  1599. * the hash keys are equal and that HASH_BITS >= 8.
  1600. */
  1601. scan += 2, match++;
  1602. BOOST_ASSERT(*scan == *match);
  1603. /* We check for insufficient lookahead only every 8th comparison;
  1604. * the 256th check will be made at strstart+258.
  1605. */
  1606. do
  1607. {
  1608. }
  1609. while( *++scan == *++match && *++scan == *++match &&
  1610. *++scan == *++match && *++scan == *++match &&
  1611. *++scan == *++match && *++scan == *++match &&
  1612. *++scan == *++match && *++scan == *++match &&
  1613. scan < strend);
  1614. BOOST_ASSERT(scan <= window_+(unsigned)(window_size_-1));
  1615. len = maxMatch - (int)(strend - scan);
  1616. scan = strend - maxMatch;
  1617. if(len > best_len) {
  1618. match_start_ = cur_match;
  1619. best_len = len;
  1620. if(len >= nice_match) break;
  1621. scan_end1 = scan[best_len-1];
  1622. scan_end = scan[best_len];
  1623. }
  1624. }
  1625. while((cur_match = prev[cur_match & wmask]) > limit
  1626. && --chain_length != 0);
  1627. if((uInt)best_len <= lookahead_)
  1628. return (uInt)best_len;
  1629. return lookahead_;
  1630. }
  1631. //------------------------------------------------------------------------------
  1632. /* Copy without compression as much as possible from the input stream, return
  1633. the current block state.
  1634. This function does not insert new strings in the dictionary since
  1635. uncompressible data is probably not useful. This function is used
  1636. only for the level=0 compression option.
  1637. NOTE: this function should be optimized to avoid extra copying from
  1638. window to pending_buf.
  1639. */
  1640. auto
  1641. deflate_stream::
  1642. f_stored(z_params& zs, Flush flush) ->
  1643. block_state
  1644. {
  1645. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1646. * to pending_buf_size, and each stored block has a 5 byte header:
  1647. */
  1648. std::uint32_t max_block_size = 0xffff;
  1649. std::uint32_t max_start;
  1650. if(max_block_size > pending_buf_size_ - 5) {
  1651. max_block_size = pending_buf_size_ - 5;
  1652. }
  1653. /* Copy as much as possible from input to output: */
  1654. for(;;) {
  1655. /* Fill the window as much as possible: */
  1656. if(lookahead_ <= 1) {
  1657. BOOST_ASSERT(strstart_ < w_size_+max_dist() ||
  1658. block_start_ >= (long)w_size_);
  1659. fill_window(zs);
  1660. if(lookahead_ == 0 && flush == Flush::none)
  1661. return need_more;
  1662. if(lookahead_ == 0) break; /* flush the current block */
  1663. }
  1664. BOOST_ASSERT(block_start_ >= 0L);
  1665. strstart_ += lookahead_;
  1666. lookahead_ = 0;
  1667. /* Emit a stored block if pending_buf will be full: */
  1668. max_start = block_start_ + max_block_size;
  1669. if(strstart_ == 0 || (std::uint32_t)strstart_ >= max_start) {
  1670. /* strstart == 0 is possible when wraparound on 16-bit machine */
  1671. lookahead_ = (uInt)(strstart_ - max_start);
  1672. strstart_ = (uInt)max_start;
  1673. flush_block(zs, false);
  1674. if(zs.avail_out == 0)
  1675. return need_more;
  1676. }
  1677. /* Flush if we may have to slide, otherwise block_start may become
  1678. * negative and the data will be gone:
  1679. */
  1680. if(strstart_ - (uInt)block_start_ >= max_dist()) {
  1681. flush_block(zs, false);
  1682. if(zs.avail_out == 0)
  1683. return need_more;
  1684. }
  1685. }
  1686. insert_ = 0;
  1687. if(flush == Flush::finish)
  1688. {
  1689. flush_block(zs, true);
  1690. if(zs.avail_out == 0)
  1691. return finish_started;
  1692. return finish_done;
  1693. }
  1694. if((long)strstart_ > block_start_)
  1695. {
  1696. flush_block(zs, false);
  1697. if(zs.avail_out == 0)
  1698. return need_more;
  1699. }
  1700. return block_done;
  1701. }
  1702. /* Compress as much as possible from the input stream, return the current
  1703. block state.
  1704. This function does not perform lazy evaluation of matches and inserts
  1705. new strings in the dictionary only for unmatched strings or for short
  1706. matches. It is used only for the fast compression options.
  1707. */
  1708. auto
  1709. deflate_stream::
  1710. f_fast(z_params& zs, Flush flush) ->
  1711. block_state
  1712. {
  1713. IPos hash_head; /* head of the hash chain */
  1714. bool bflush; /* set if current block must be flushed */
  1715. for(;;)
  1716. {
  1717. /* Make sure that we always have enough lookahead, except
  1718. * at the end of the input file. We need maxMatch bytes
  1719. * for the next match, plus minMatch bytes to insert the
  1720. * string following the next match.
  1721. */
  1722. if(lookahead_ < kMinLookahead)
  1723. {
  1724. fill_window(zs);
  1725. if(lookahead_ < kMinLookahead && flush == Flush::none)
  1726. return need_more;
  1727. if(lookahead_ == 0)
  1728. break; /* flush the current block */
  1729. }
  1730. /* Insert the string window[strstart .. strstart+2] in the
  1731. * dictionary, and set hash_head to the head of the hash chain:
  1732. */
  1733. hash_head = 0;
  1734. if(lookahead_ >= minMatch) {
  1735. insert_string(hash_head);
  1736. }
  1737. /* Find the longest match, discarding those <= prev_length.
  1738. * At this point we have always match_length < minMatch
  1739. */
  1740. if(hash_head != 0 && strstart_ - hash_head <= max_dist()) {
  1741. /* To simplify the code, we prevent matches with the string
  1742. * of window index 0 (in particular we have to avoid a match
  1743. * of the string with itself at the start of the input file).
  1744. */
  1745. match_length_ = longest_match (hash_head);
  1746. /* longest_match() sets match_start */
  1747. }
  1748. if(match_length_ >= minMatch)
  1749. {
  1750. tr_tally_dist(static_cast<std::uint16_t>(strstart_ - match_start_),
  1751. static_cast<std::uint8_t>(match_length_ - minMatch), bflush);
  1752. lookahead_ -= match_length_;
  1753. /* Insert new strings in the hash table only if the match length
  1754. * is not too large. This saves time but degrades compression.
  1755. */
  1756. if(match_length_ <= max_lazy_match_ &&
  1757. lookahead_ >= minMatch) {
  1758. match_length_--; /* string at strstart already in table */
  1759. do
  1760. {
  1761. strstart_++;
  1762. insert_string(hash_head);
  1763. /* strstart never exceeds WSIZE-maxMatch, so there are
  1764. * always minMatch bytes ahead.
  1765. */
  1766. }
  1767. while(--match_length_ != 0);
  1768. strstart_++;
  1769. }
  1770. else
  1771. {
  1772. strstart_ += match_length_;
  1773. match_length_ = 0;
  1774. ins_h_ = window_[strstart_];
  1775. update_hash(ins_h_, window_[strstart_+1]);
  1776. /* If lookahead < minMatch, ins_h is garbage, but it does not
  1777. * matter since it will be recomputed at next deflate call.
  1778. */
  1779. }
  1780. }
  1781. else
  1782. {
  1783. /* No match, output a literal byte */
  1784. tr_tally_lit(window_[strstart_], bflush);
  1785. lookahead_--;
  1786. strstart_++;
  1787. }
  1788. if(bflush)
  1789. {
  1790. flush_block(zs, false);
  1791. if(zs.avail_out == 0)
  1792. return need_more;
  1793. }
  1794. }
  1795. insert_ = strstart_ < minMatch-1 ? strstart_ : minMatch-1;
  1796. if(flush == Flush::finish)
  1797. {
  1798. flush_block(zs, true);
  1799. if(zs.avail_out == 0)
  1800. return finish_started;
  1801. return finish_done;
  1802. }
  1803. if(last_lit_)
  1804. {
  1805. flush_block(zs, false);
  1806. if(zs.avail_out == 0)
  1807. return need_more;
  1808. }
  1809. return block_done;
  1810. }
  1811. /* Same as above, but achieves better compression. We use a lazy
  1812. evaluation for matches: a match is finally adopted only if there is
  1813. no better match at the next window position.
  1814. */
  1815. auto
  1816. deflate_stream::
  1817. f_slow(z_params& zs, Flush flush) ->
  1818. block_state
  1819. {
  1820. IPos hash_head; /* head of hash chain */
  1821. bool bflush; /* set if current block must be flushed */
  1822. /* Process the input block. */
  1823. for(;;)
  1824. {
  1825. /* Make sure that we always have enough lookahead, except
  1826. * at the end of the input file. We need maxMatch bytes
  1827. * for the next match, plus minMatch bytes to insert the
  1828. * string following the next match.
  1829. */
  1830. if(lookahead_ < kMinLookahead)
  1831. {
  1832. fill_window(zs);
  1833. if(lookahead_ < kMinLookahead && flush == Flush::none)
  1834. return need_more;
  1835. if(lookahead_ == 0)
  1836. break; /* flush the current block */
  1837. }
  1838. /* Insert the string window[strstart .. strstart+2] in the
  1839. * dictionary, and set hash_head to the head of the hash chain:
  1840. */
  1841. hash_head = 0;
  1842. if(lookahead_ >= minMatch)
  1843. insert_string(hash_head);
  1844. /* Find the longest match, discarding those <= prev_length.
  1845. */
  1846. prev_length_ = match_length_, prev_match_ = match_start_;
  1847. match_length_ = minMatch-1;
  1848. if(hash_head != 0 && prev_length_ < max_lazy_match_ &&
  1849. strstart_ - hash_head <= max_dist())
  1850. {
  1851. /* To simplify the code, we prevent matches with the string
  1852. * of window index 0 (in particular we have to avoid a match
  1853. * of the string with itself at the start of the input file).
  1854. */
  1855. match_length_ = longest_match(hash_head);
  1856. /* longest_match() sets match_start */
  1857. if(match_length_ <= 5 && (strategy_ == Strategy::filtered
  1858. || (match_length_ == minMatch &&
  1859. strstart_ - match_start_ > kTooFar)
  1860. ))
  1861. {
  1862. /* If prev_match is also minMatch, match_start is garbage
  1863. * but we will ignore the current match anyway.
  1864. */
  1865. match_length_ = minMatch-1;
  1866. }
  1867. }
  1868. /* If there was a match at the previous step and the current
  1869. * match is not better, output the previous match:
  1870. */
  1871. if(prev_length_ >= minMatch && match_length_ <= prev_length_)
  1872. {
  1873. /* Do not insert strings in hash table beyond this. */
  1874. uInt max_insert = strstart_ + lookahead_ - minMatch;
  1875. tr_tally_dist(
  1876. static_cast<std::uint16_t>(strstart_ -1 - prev_match_),
  1877. static_cast<std::uint8_t>(prev_length_ - minMatch), bflush);
  1878. /* Insert in hash table all strings up to the end of the match.
  1879. * strstart-1 and strstart are already inserted. If there is not
  1880. * enough lookahead, the last two strings are not inserted in
  1881. * the hash table.
  1882. */
  1883. lookahead_ -= prev_length_-1;
  1884. prev_length_ -= 2;
  1885. do {
  1886. if(++strstart_ <= max_insert)
  1887. insert_string(hash_head);
  1888. }
  1889. while(--prev_length_ != 0);
  1890. match_available_ = 0;
  1891. match_length_ = minMatch-1;
  1892. strstart_++;
  1893. if(bflush)
  1894. {
  1895. flush_block(zs, false);
  1896. if(zs.avail_out == 0)
  1897. return need_more;
  1898. }
  1899. }
  1900. else if(match_available_)
  1901. {
  1902. /* If there was no match at the previous position, output a
  1903. * single literal. If there was a match but the current match
  1904. * is longer, truncate the previous match to a single literal.
  1905. */
  1906. tr_tally_lit(window_[strstart_-1], bflush);
  1907. if(bflush)
  1908. flush_block(zs, false);
  1909. strstart_++;
  1910. lookahead_--;
  1911. if(zs.avail_out == 0)
  1912. return need_more;
  1913. }
  1914. else
  1915. {
  1916. /* There is no previous match to compare with, wait for
  1917. * the next step to decide.
  1918. */
  1919. match_available_ = 1;
  1920. strstart_++;
  1921. lookahead_--;
  1922. }
  1923. }
  1924. BOOST_ASSERT(flush != Flush::none);
  1925. if(match_available_)
  1926. {
  1927. tr_tally_lit(window_[strstart_-1], bflush);
  1928. match_available_ = 0;
  1929. }
  1930. insert_ = strstart_ < minMatch-1 ? strstart_ : minMatch-1;
  1931. if(flush == Flush::finish)
  1932. {
  1933. flush_block(zs, true);
  1934. if(zs.avail_out == 0)
  1935. return finish_started;
  1936. return finish_done;
  1937. }
  1938. if(last_lit_)
  1939. {
  1940. flush_block(zs, false);
  1941. if(zs.avail_out == 0)
  1942. return need_more;
  1943. }
  1944. return block_done;
  1945. }
  1946. /* For Strategy::rle, simply look for runs of bytes, generate matches only of distance
  1947. one. Do not maintain a hash table. (It will be regenerated if this run of
  1948. deflate switches away from Strategy::rle.)
  1949. */
  1950. auto
  1951. deflate_stream::
  1952. f_rle(z_params& zs, Flush flush) ->
  1953. block_state
  1954. {
  1955. bool bflush; // set if current block must be flushed
  1956. uInt prev; // byte at distance one to match
  1957. Byte *scan, *strend; // scan goes up to strend for length of run
  1958. for(;;)
  1959. {
  1960. /* Make sure that we always have enough lookahead, except
  1961. * at the end of the input file. We need maxMatch bytes
  1962. * for the longest run, plus one for the unrolled loop.
  1963. */
  1964. if(lookahead_ <= maxMatch) {
  1965. fill_window(zs);
  1966. if(lookahead_ <= maxMatch && flush == Flush::none) {
  1967. return need_more;
  1968. }
  1969. if(lookahead_ == 0) break; /* flush the current block */
  1970. }
  1971. /* See how many times the previous byte repeats */
  1972. match_length_ = 0;
  1973. if(lookahead_ >= minMatch && strstart_ > 0) {
  1974. scan = window_ + strstart_ - 1;
  1975. prev = *scan;
  1976. if(prev == *++scan && prev == *++scan && prev == *++scan) {
  1977. strend = window_ + strstart_ + maxMatch;
  1978. do {
  1979. } while(prev == *++scan && prev == *++scan &&
  1980. prev == *++scan && prev == *++scan &&
  1981. prev == *++scan && prev == *++scan &&
  1982. prev == *++scan && prev == *++scan &&
  1983. scan < strend);
  1984. match_length_ = maxMatch - (int)(strend - scan);
  1985. if(match_length_ > lookahead_)
  1986. match_length_ = lookahead_;
  1987. }
  1988. BOOST_ASSERT(scan <= window_+(uInt)(window_size_-1));
  1989. }
  1990. /* Emit match if have run of minMatch or longer, else emit literal */
  1991. if(match_length_ >= minMatch) {
  1992. tr_tally_dist(std::uint16_t{1},
  1993. static_cast<std::uint8_t>(match_length_ - minMatch),
  1994. bflush);
  1995. lookahead_ -= match_length_;
  1996. strstart_ += match_length_;
  1997. match_length_ = 0;
  1998. } else {
  1999. /* No match, output a literal byte */
  2000. tr_tally_lit(window_[strstart_], bflush);
  2001. lookahead_--;
  2002. strstart_++;
  2003. }
  2004. if(bflush)
  2005. {
  2006. flush_block(zs, false);
  2007. if(zs.avail_out == 0)
  2008. return need_more;
  2009. }
  2010. }
  2011. insert_ = 0;
  2012. if(flush == Flush::finish)
  2013. {
  2014. flush_block(zs, true);
  2015. if(zs.avail_out == 0)
  2016. return finish_started;
  2017. return finish_done;
  2018. }
  2019. if(last_lit_)
  2020. {
  2021. flush_block(zs, false);
  2022. if(zs.avail_out == 0)
  2023. return need_more;
  2024. }
  2025. return block_done;
  2026. }
  2027. /* ===========================================================================
  2028. * For Strategy::huffman, do not look for matches. Do not maintain a hash table.
  2029. * (It will be regenerated if this run of deflate switches away from Huffman.)
  2030. */
  2031. auto
  2032. deflate_stream::
  2033. f_huff(z_params& zs, Flush flush) ->
  2034. block_state
  2035. {
  2036. bool bflush; // set if current block must be flushed
  2037. for(;;)
  2038. {
  2039. // Make sure that we have a literal to write.
  2040. if(lookahead_ == 0)
  2041. {
  2042. fill_window(zs);
  2043. if(lookahead_ == 0)
  2044. {
  2045. if(flush == Flush::none)
  2046. return need_more;
  2047. break; // flush the current block
  2048. }
  2049. }
  2050. // Output a literal byte
  2051. match_length_ = 0;
  2052. tr_tally_lit(window_[strstart_], bflush);
  2053. lookahead_--;
  2054. strstart_++;
  2055. if(bflush)
  2056. {
  2057. flush_block(zs, false);
  2058. if(zs.avail_out == 0)
  2059. return need_more;
  2060. }
  2061. }
  2062. insert_ = 0;
  2063. if(flush == Flush::finish)
  2064. {
  2065. flush_block(zs, true);
  2066. if(zs.avail_out == 0)
  2067. return finish_started;
  2068. return finish_done;
  2069. }
  2070. if(last_lit_)
  2071. {
  2072. flush_block(zs, false);
  2073. if(zs.avail_out == 0)
  2074. return need_more;
  2075. }
  2076. return block_done;
  2077. }
  2078. } // detail
  2079. } // zlib
  2080. } // beast
  2081. } // boost
  2082. #endif