deflate_stream.hpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007
  1. //
  2. // Copyright (c) 2016-2017 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_HPP
  32. #define BOOST_BEAST_ZLIB_DETAIL_DEFLATE_STREAM_HPP
  33. #include <boost/beast/zlib/zlib.hpp>
  34. #include <boost/beast/zlib/detail/ranges.hpp>
  35. #include <boost/beast/core/detail/type_traits.hpp>
  36. #include <boost/assert.hpp>
  37. #include <boost/config.hpp>
  38. #include <boost/make_unique.hpp>
  39. #include <boost/optional.hpp>
  40. #include <boost/throw_exception.hpp>
  41. #include <cstdint>
  42. #include <cstdlib>
  43. #include <cstring>
  44. #include <memory>
  45. #include <stdexcept>
  46. #include <type_traits>
  47. namespace boost {
  48. namespace beast {
  49. namespace zlib {
  50. namespace detail {
  51. /*
  52. * ALGORITHM
  53. *
  54. * The "deflation" process depends on being able to identify portions
  55. * of the input text which are identical to earlier input (within a
  56. * sliding window trailing behind the input currently being processed).
  57. *
  58. * Each code tree is stored in a compressed form which is itself
  59. * a Huffman encoding of the lengths of all the code strings (in
  60. * ascending order by source values). The actual code strings are
  61. * reconstructed from the lengths in the inflate process, as described
  62. * in the deflate specification.
  63. *
  64. * The most straightforward technique turns out to be the fastest for
  65. * most input files: try all possible matches and select the longest.
  66. * The key feature of this algorithm is that insertions into the string
  67. * dictionary are very simple and thus fast, and deletions are avoided
  68. * completely. Insertions are performed at each input character, whereas
  69. * string matches are performed only when the previous match ends. So it
  70. * is preferable to spend more time in matches to allow very fast string
  71. * insertions and avoid deletions. The matching algorithm for small
  72. * strings is inspired from that of Rabin & Karp. A brute force approach
  73. * is used to find longer strings when a small match has been found.
  74. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  75. * (by Leonid Broukhis).
  76. * A previous version of this file used a more sophisticated algorithm
  77. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  78. * time, but has a larger average cost, uses more memory and is patented.
  79. * However the F&G algorithm may be faster for some highly redundant
  80. * files if the parameter max_chain_length (described below) is too large.
  81. *
  82. * ACKNOWLEDGEMENTS
  83. *
  84. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  85. * I found it in 'freeze' written by Leonid Broukhis.
  86. * Thanks to many people for bug reports and testing.
  87. *
  88. * REFERENCES
  89. *
  90. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  91. * Available in http://tools.ietf.org/html/rfc1951
  92. *
  93. * A description of the Rabin and Karp algorithm is given in the book
  94. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  95. *
  96. * Fiala,E.R., and Greene,D.H.
  97. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  98. *
  99. */
  100. class deflate_stream
  101. {
  102. protected:
  103. // Upper limit on code length
  104. static std::uint8_t constexpr maxBits = 15;
  105. // Number of length codes, not counting the special END_BLOCK code
  106. static std::uint16_t constexpr lengthCodes = 29;
  107. // Number of literal bytes 0..255
  108. static std::uint16_t constexpr literals = 256;
  109. // Number of Literal or Length codes, including the END_BLOCK code
  110. static std::uint16_t constexpr lCodes = literals + 1 + lengthCodes;
  111. // Number of distance code lengths
  112. static std::uint16_t constexpr dCodes = 30;
  113. // Number of codes used to transfer the bit lengths
  114. static std::uint16_t constexpr blCodes = 19;
  115. // Number of distance codes
  116. static std::uint16_t constexpr distCodeLen = 512;
  117. // Size limit on bit length codes
  118. static std::uint8_t constexpr maxBlBits= 7;
  119. static std::uint16_t constexpr minMatch = 3;
  120. static std::uint16_t constexpr maxMatch = 258;
  121. // Can't change minMatch without also changing code, see original zlib
  122. BOOST_STATIC_ASSERT(minMatch == 3);
  123. // end of block literal code
  124. static std::uint16_t constexpr END_BLOCK = 256;
  125. // repeat previous bit length 3-6 times (2 bits of repeat count)
  126. static std::uint8_t constexpr REP_3_6 = 16;
  127. // repeat a zero length 3-10 times (3 bits of repeat count)
  128. static std::uint8_t constexpr REPZ_3_10 = 17;
  129. // repeat a zero length 11-138 times (7 bits of repeat count)
  130. static std::uint8_t constexpr REPZ_11_138 = 18;
  131. // The three kinds of block type
  132. static std::uint8_t constexpr STORED_BLOCK = 0;
  133. static std::uint8_t constexpr STATIC_TREES = 1;
  134. static std::uint8_t constexpr DYN_TREES = 2;
  135. // Maximum value for memLevel in deflateInit2
  136. static std::uint8_t constexpr max_mem_level = 9;
  137. // Default memLevel
  138. static std::uint8_t constexpr DEF_MEM_LEVEL = max_mem_level;
  139. /* Note: the deflate() code requires max_lazy >= minMatch and max_chain >= 4
  140. For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  141. meaning.
  142. */
  143. // maximum heap size
  144. static std::uint16_t constexpr HEAP_SIZE = 2 * lCodes + 1;
  145. // size of bit buffer in bi_buf
  146. static std::uint8_t constexpr Buf_size = 16;
  147. // Matches of length 3 are discarded if their distance exceeds kTooFar
  148. static std::size_t constexpr kTooFar = 4096;
  149. /* Minimum amount of lookahead, except at the end of the input file.
  150. See deflate.c for comments about the minMatch+1.
  151. */
  152. static std::size_t constexpr kMinLookahead = maxMatch + minMatch+1;
  153. /* Number of bytes after end of data in window to initialize in order
  154. to avoid memory checker errors from longest match routines
  155. */
  156. static std::size_t constexpr kWinInit = maxMatch;
  157. // Describes a single value and its code string.
  158. struct ct_data
  159. {
  160. std::uint16_t fc; // frequency count or bit string
  161. std::uint16_t dl; // parent node in tree or length of bit string
  162. bool
  163. operator==(ct_data const& rhs) const
  164. {
  165. return fc == rhs.fc && dl == rhs.dl;
  166. }
  167. };
  168. struct static_desc
  169. {
  170. ct_data const* static_tree;// static tree or NULL
  171. std::uint8_t const* extra_bits; // extra bits for each code or NULL
  172. std::uint16_t extra_base; // base index for extra_bits
  173. std::uint16_t elems; // max number of elements in the tree
  174. std::uint8_t max_length; // max bit length for the codes
  175. };
  176. struct lut_type
  177. {
  178. // Number of extra bits for each length code
  179. std::uint8_t const extra_lbits[lengthCodes] = {
  180. 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
  181. };
  182. // Number of extra bits for each distance code
  183. std::uint8_t const extra_dbits[dCodes] = {
  184. 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
  185. };
  186. // Number of extra bits for each bit length code
  187. std::uint8_t const extra_blbits[blCodes] = {
  188. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
  189. };
  190. // The lengths of the bit length codes are sent in order
  191. // of decreasing probability, to avoid transmitting the
  192. // lengths for unused bit length codes.
  193. std::uint8_t const bl_order[blCodes] = {
  194. 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15
  195. };
  196. ct_data ltree[lCodes + 2];
  197. ct_data dtree[dCodes];
  198. // Distance codes. The first 256 values correspond to the distances
  199. // 3 .. 258, the last 256 values correspond to the top 8 bits of
  200. // the 15 bit distances.
  201. std::uint8_t dist_code[distCodeLen];
  202. std::uint8_t length_code[maxMatch-minMatch+1];
  203. std::uint8_t base_length[lengthCodes];
  204. std::uint16_t base_dist[dCodes];
  205. static_desc l_desc = {
  206. ltree, extra_lbits, literals+1, lCodes, maxBits
  207. };
  208. static_desc d_desc = {
  209. dtree, extra_dbits, 0, dCodes, maxBits
  210. };
  211. static_desc bl_desc =
  212. {
  213. nullptr, extra_blbits, 0, blCodes, maxBlBits
  214. };
  215. };
  216. struct tree_desc
  217. {
  218. ct_data *dyn_tree; /* the dynamic tree */
  219. int max_code; /* largest code with non zero frequency */
  220. static_desc const* stat_desc; /* the corresponding static tree */
  221. };
  222. enum block_state
  223. {
  224. need_more, /* block not completed, need more input or more output */
  225. block_done, /* block flush performed */
  226. finish_started, /* finish started, need only more output at next deflate */
  227. finish_done /* finish done, accept no more input or output */
  228. };
  229. // VFALCO This might not be needed, e.g. for zip/gzip
  230. enum StreamStatus
  231. {
  232. EXTRA_STATE = 69,
  233. NAME_STATE = 73,
  234. COMMENT_STATE = 91,
  235. HCRC_STATE = 103,
  236. BUSY_STATE = 113,
  237. FINISH_STATE = 666
  238. };
  239. /* A std::uint16_t is an index in the character window. We use short instead of int to
  240. * save space in the various tables. IPos is used only for parameter passing.
  241. */
  242. using IPos = unsigned;
  243. using self = deflate_stream;
  244. typedef block_state(self::*compress_func)(z_params& zs, Flush flush);
  245. //--------------------------------------------------------------------------
  246. lut_type const& lut_;
  247. bool inited_ = false;
  248. std::size_t buf_size_;
  249. std::unique_ptr<std::uint8_t[]> buf_;
  250. int status_; // as the name implies
  251. Byte* pending_buf_; // output still pending
  252. std::uint32_t
  253. pending_buf_size_; // size of pending_buf
  254. Byte* pending_out_; // next pending byte to output to the stream
  255. uInt pending_; // nb of bytes in the pending buffer
  256. boost::optional<Flush>
  257. last_flush_; // value of flush param for previous deflate call
  258. uInt w_size_; // LZ77 window size (32K by default)
  259. uInt w_bits_; // log2(w_size) (8..16)
  260. uInt w_mask_; // w_size - 1
  261. /* Sliding window. Input bytes are read into the second half of the window,
  262. and move to the first half later to keep a dictionary of at least wSize
  263. bytes. With this organization, matches are limited to a distance of
  264. wSize-maxMatch bytes, but this ensures that IO is always
  265. performed with a length multiple of the block size. Also, it limits
  266. the window size to 64K.
  267. To do: use the user input buffer as sliding window.
  268. */
  269. Byte *window_ = nullptr;
  270. /* Actual size of window: 2*wSize, except when the user input buffer
  271. is directly used as sliding window.
  272. */
  273. std::uint32_t window_size_;
  274. /* Link to older string with same hash index. To limit the size of this
  275. array to 64K, this link is maintained only for the last 32K strings.
  276. An index in this array is thus a window index modulo 32K.
  277. */
  278. std::uint16_t* prev_;
  279. std::uint16_t* head_; // Heads of the hash chains or 0
  280. uInt ins_h_; // hash index of string to be inserted
  281. uInt hash_size_; // number of elements in hash table
  282. uInt hash_bits_; // log2(hash_size)
  283. uInt hash_mask_; // hash_size-1
  284. /* Number of bits by which ins_h must be shifted at each input
  285. step. It must be such that after minMatch steps,
  286. the oldest byte no longer takes part in the hash key, that is:
  287. hash_shift * minMatch >= hash_bits
  288. */
  289. uInt hash_shift_;
  290. /* Window position at the beginning of the current output block.
  291. Gets negative when the window is moved backwards.
  292. */
  293. long block_start_;
  294. uInt match_length_; // length of best match
  295. IPos prev_match_; // previous match
  296. int match_available_; // set if previous match exists
  297. uInt strstart_; // start of string to insert
  298. uInt match_start_; // start of matching string
  299. uInt lookahead_; // number of valid bytes ahead in window
  300. /* Length of the best match at previous step. Matches not greater
  301. than this are discarded. This is used in the lazy match evaluation.
  302. */
  303. uInt prev_length_;
  304. /* To speed up deflation, hash chains are never searched beyond
  305. this length. A higher limit improves compression ratio but
  306. degrades the speed.
  307. */
  308. uInt max_chain_length_;
  309. /* Attempt to find a better match only when the current match is strictly
  310. smaller than this value. This mechanism is used only for compression
  311. levels >= 4.
  312. OR Insert new strings in the hash table only if the match length is not
  313. greater than this length. This saves time but degrades compression.
  314. used only for compression levels <= 3.
  315. */
  316. uInt max_lazy_match_;
  317. int level_; // compression level (1..9)
  318. Strategy strategy_; // favor or force Huffman coding
  319. // Use a faster search when the previous match is longer than this
  320. uInt good_match_;
  321. int nice_match_; // Stop searching when current match exceeds this
  322. ct_data dyn_ltree_[
  323. HEAP_SIZE]; // literal and length tree
  324. ct_data dyn_dtree_[
  325. 2*dCodes+1]; // distance tree
  326. ct_data bl_tree_[
  327. 2*blCodes+1]; // Huffman tree for bit lengths
  328. tree_desc l_desc_; // desc. for literal tree
  329. tree_desc d_desc_; // desc. for distance tree
  330. tree_desc bl_desc_; // desc. for bit length tree
  331. // number of codes at each bit length for an optimal tree
  332. std::uint16_t bl_count_[maxBits+1];
  333. // Index within the heap array of least frequent node in the Huffman tree
  334. static std::size_t constexpr kSmallest = 1;
  335. /* The sons of heap[n] are heap[2*n] and heap[2*n+1].
  336. heap[0] is not used. The same heap array is used to build all trees.
  337. */
  338. int heap_[2*lCodes+1]; // heap used to build the Huffman trees
  339. int heap_len_; // number of elements in the heap
  340. int heap_max_; // element of largest frequency
  341. // Depth of each subtree used as tie breaker for trees of equal frequency
  342. std::uint8_t depth_[2*lCodes+1];
  343. std::uint8_t *l_buf_; // buffer for literals or lengths
  344. /* Size of match buffer for literals/lengths.
  345. There are 4 reasons for limiting lit_bufsize to 64K:
  346. - frequencies can be kept in 16 bit counters
  347. - if compression is not successful for the first block, all input
  348. data is still in the window so we can still emit a stored block even
  349. when input comes from standard input. (This can also be done for
  350. all blocks if lit_bufsize is not greater than 32K.)
  351. - if compression is not successful for a file smaller than 64K, we can
  352. even emit a stored file instead of a stored block (saving 5 bytes).
  353. This is applicable only for zip (not gzip or zlib).
  354. - creating new Huffman trees less frequently may not provide fast
  355. adaptation to changes in the input data statistics. (Take for
  356. example a binary file with poorly compressible code followed by
  357. a highly compressible string table.) Smaller buffer sizes give
  358. fast adaptation but have of course the overhead of transmitting
  359. trees more frequently.
  360. - I can't count above 4
  361. */
  362. uInt lit_bufsize_;
  363. uInt last_lit_; // running index in l_buf_
  364. /* Buffer for distances. To simplify the code, d_buf_ and l_buf_
  365. have the same number of elements. To use different lengths, an
  366. extra flag array would be necessary.
  367. */
  368. std::uint16_t* d_buf_;
  369. std::uint32_t opt_len_; // bit length of current block with optimal trees
  370. std::uint32_t static_len_; // bit length of current block with static trees
  371. uInt matches_; // number of string matches in current block
  372. uInt insert_; // bytes at end of window left to insert
  373. /* Output buffer.
  374. Bits are inserted starting at the bottom (least significant bits).
  375. */
  376. std::uint16_t bi_buf_;
  377. /* Number of valid bits in bi_buf._ All bits above the last valid
  378. bit are always zero.
  379. */
  380. int bi_valid_;
  381. /* High water mark offset in window for initialized bytes -- bytes
  382. above this are set to zero in order to avoid memory check warnings
  383. when longest match routines access bytes past the input. This is
  384. then updated to the new high water mark.
  385. */
  386. std::uint32_t high_water_;
  387. //--------------------------------------------------------------------------
  388. deflate_stream()
  389. : lut_(get_lut())
  390. {
  391. }
  392. /* In order to simplify the code, particularly on 16 bit machines, match
  393. distances are limited to MAX_DIST instead of WSIZE.
  394. */
  395. std::size_t
  396. max_dist() const
  397. {
  398. return w_size_ - kMinLookahead;
  399. }
  400. void
  401. put_byte(std::uint8_t c)
  402. {
  403. pending_buf_[pending_++] = c;
  404. }
  405. void
  406. put_short(std::uint16_t w)
  407. {
  408. put_byte(w & 0xff);
  409. put_byte(w >> 8);
  410. }
  411. /* Send a value on a given number of bits.
  412. IN assertion: length <= 16 and value fits in length bits.
  413. */
  414. void
  415. send_bits(int value, int length)
  416. {
  417. if(bi_valid_ > (int)Buf_size - length)
  418. {
  419. bi_buf_ |= (std::uint16_t)value << bi_valid_;
  420. put_short(bi_buf_);
  421. bi_buf_ = (std::uint16_t)value >> (Buf_size - bi_valid_);
  422. bi_valid_ += length - Buf_size;
  423. }
  424. else
  425. {
  426. bi_buf_ |= (std::uint16_t)(value) << bi_valid_;
  427. bi_valid_ += length;
  428. }
  429. }
  430. // Send a code of the given tree
  431. void
  432. send_code(int value, ct_data const* tree)
  433. {
  434. send_bits(tree[value].fc, tree[value].dl);
  435. }
  436. /* Mapping from a distance to a distance code. dist is the
  437. distance - 1 and must not have side effects. _dist_code[256]
  438. and _dist_code[257] are never used.
  439. */
  440. std::uint8_t
  441. d_code(unsigned dist)
  442. {
  443. if(dist < 256)
  444. return lut_.dist_code[dist];
  445. return lut_.dist_code[256+(dist>>7)];
  446. }
  447. /* Update a hash value with the given input byte
  448. IN assertion: all calls to to update_hash are made with
  449. consecutive input characters, so that a running hash
  450. key can be computed from the previous key instead of
  451. complete recalculation each time.
  452. */
  453. void
  454. update_hash(uInt& h, std::uint8_t c)
  455. {
  456. h = ((h << hash_shift_) ^ c) & hash_mask_;
  457. }
  458. /* Initialize the hash table (avoiding 64K overflow for 16
  459. bit systems). prev[] will be initialized on the fly.
  460. */
  461. void
  462. clear_hash()
  463. {
  464. head_[hash_size_-1] = 0;
  465. std::memset((Byte *)head_, 0,
  466. (unsigned)(hash_size_-1)*sizeof(*head_));
  467. }
  468. /* Compares two subtrees, using the tree depth as tie breaker
  469. when the subtrees have equal frequency. This minimizes the
  470. worst case length.
  471. */
  472. bool
  473. smaller(ct_data const* tree, int n, int m)
  474. {
  475. return tree[n].fc < tree[m].fc ||
  476. (tree[n].fc == tree[m].fc &&
  477. depth_[n] <= depth_[m]);
  478. }
  479. /* Insert string str in the dictionary and set match_head to the
  480. previous head of the hash chain (the most recent string with
  481. same hash key). Return the previous length of the hash chain.
  482. If this file is compiled with -DFASTEST, the compression level
  483. is forced to 1, and no hash chains are maintained.
  484. IN assertion: all calls to to INSERT_STRING are made with
  485. consecutive input characters and the first minMatch
  486. bytes of str are valid (except for the last minMatch-1
  487. bytes of the input file).
  488. */
  489. void
  490. insert_string(IPos& hash_head)
  491. {
  492. update_hash(ins_h_, window_[strstart_ + (minMatch-1)]);
  493. hash_head = prev_[strstart_ & w_mask_] = head_[ins_h_];
  494. head_[ins_h_] = (std::uint16_t)strstart_;
  495. }
  496. //--------------------------------------------------------------------------
  497. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  498. * the desired pack level (0..9). The values given below have been tuned to
  499. * exclude worst case performance for pathological files. Better values may be
  500. * found for specific files.
  501. */
  502. struct config
  503. {
  504. std::uint16_t good_length; /* reduce lazy search above this match length */
  505. std::uint16_t max_lazy; /* do not perform lazy search above this match length */
  506. std::uint16_t nice_length; /* quit search above this match length */
  507. std::uint16_t max_chain;
  508. compress_func func;
  509. config(
  510. std::uint16_t good_length_,
  511. std::uint16_t max_lazy_,
  512. std::uint16_t nice_length_,
  513. std::uint16_t max_chain_,
  514. compress_func func_)
  515. : good_length(good_length_)
  516. , max_lazy(max_lazy_)
  517. , nice_length(nice_length_)
  518. , max_chain(max_chain_)
  519. , func(func_)
  520. {
  521. }
  522. };
  523. static
  524. config
  525. get_config(std::size_t level)
  526. {
  527. switch(level)
  528. {
  529. // good lazy nice chain
  530. case 0: return { 0, 0, 0, 0, &self::deflate_stored}; // store only
  531. case 1: return { 4, 4, 8, 4, &self::deflate_fast}; // max speed, no lazy matches
  532. case 2: return { 4, 5, 16, 8, &self::deflate_fast};
  533. case 3: return { 4, 6, 32, 32, &self::deflate_fast};
  534. case 4: return { 4, 4, 16, 16, &self::deflate_slow}; // lazy matches
  535. case 5: return { 8, 16, 32, 32, &self::deflate_slow};
  536. case 6: return { 8, 16, 128, 128, &self::deflate_slow};
  537. case 7: return { 8, 32, 128, 256, &self::deflate_slow};
  538. case 8: return { 32, 128, 258, 1024, &self::deflate_slow};
  539. default:
  540. case 9: return { 32, 258, 258, 4096, &self::deflate_slow}; // max compression
  541. }
  542. }
  543. void
  544. maybe_init()
  545. {
  546. if(! inited_)
  547. init();
  548. }
  549. template<class Unsigned>
  550. static
  551. Unsigned
  552. bi_reverse(Unsigned code, unsigned len);
  553. template<class = void>
  554. static
  555. void
  556. gen_codes(ct_data *tree, int max_code, std::uint16_t *bl_count);
  557. template<class = void>
  558. static
  559. lut_type const&
  560. get_lut();
  561. template<class = void> void doReset (int level, int windowBits, int memLevel, Strategy strategy);
  562. template<class = void> void doReset ();
  563. template<class = void> void doClear ();
  564. template<class = void> std::size_t doUpperBound (std::size_t sourceLen) const;
  565. template<class = void> void doTune (int good_length, int max_lazy, int nice_length, int max_chain);
  566. template<class = void> void doParams (z_params& zs, int level, Strategy strategy, error_code& ec);
  567. template<class = void> void doWrite (z_params& zs, boost::optional<Flush> flush, error_code& ec);
  568. template<class = void> void doDictionary (Byte const* dict, uInt dictLength, error_code& ec);
  569. template<class = void> void doPrime (int bits, int value, error_code& ec);
  570. template<class = void> void doPending (unsigned* value, int* bits);
  571. template<class = void> void init ();
  572. template<class = void> void lm_init ();
  573. template<class = void> void init_block ();
  574. template<class = void> void pqdownheap (ct_data const* tree, int k);
  575. template<class = void> void pqremove (ct_data const* tree, int& top);
  576. template<class = void> void gen_bitlen (tree_desc *desc);
  577. template<class = void> void build_tree (tree_desc *desc);
  578. template<class = void> void scan_tree (ct_data *tree, int max_code);
  579. template<class = void> void send_tree (ct_data *tree, int max_code);
  580. template<class = void> int build_bl_tree ();
  581. template<class = void> void send_all_trees (int lcodes, int dcodes, int blcodes);
  582. template<class = void> void compress_block (ct_data const* ltree, ct_data const* dtree);
  583. template<class = void> int detect_data_type ();
  584. template<class = void> void bi_windup ();
  585. template<class = void> void bi_flush ();
  586. template<class = void> void copy_block (char *buf, unsigned len, int header);
  587. template<class = void> void tr_init ();
  588. template<class = void> void tr_align ();
  589. template<class = void> void tr_flush_bits ();
  590. template<class = void> void tr_stored_block (char *bu, std::uint32_t stored_len, int last);
  591. template<class = void> void tr_tally_dist (std::uint16_t dist, std::uint8_t len, bool& flush);
  592. template<class = void> void tr_tally_lit (std::uint8_t c, bool& flush);
  593. template<class = void> void tr_flush_block (z_params& zs, char *buf, std::uint32_t stored_len, int last);
  594. template<class = void> void fill_window (z_params& zs);
  595. template<class = void> void flush_pending (z_params& zs);
  596. template<class = void> void flush_block (z_params& zs, bool last);
  597. template<class = void> int read_buf (z_params& zs, Byte *buf, unsigned size);
  598. template<class = void> uInt longest_match (IPos cur_match);
  599. template<class = void> block_state f_stored (z_params& zs, Flush flush);
  600. template<class = void> block_state f_fast (z_params& zs, Flush flush);
  601. template<class = void> block_state f_slow (z_params& zs, Flush flush);
  602. template<class = void> block_state f_rle (z_params& zs, Flush flush);
  603. template<class = void> block_state f_huff (z_params& zs, Flush flush);
  604. block_state
  605. deflate_stored(z_params& zs, Flush flush)
  606. {
  607. return f_stored(zs, flush);
  608. }
  609. block_state
  610. deflate_fast(z_params& zs, Flush flush)
  611. {
  612. return f_fast(zs, flush);
  613. }
  614. block_state
  615. deflate_slow(z_params& zs, Flush flush)
  616. {
  617. return f_slow(zs, flush);
  618. }
  619. block_state
  620. deflate_rle(z_params& zs, Flush flush)
  621. {
  622. return f_rle(zs, flush);
  623. }
  624. block_state
  625. deflate_huff(z_params& zs, Flush flush)
  626. {
  627. return f_huff(zs, flush);
  628. }
  629. };
  630. //--------------------------------------------------------------------------
  631. // Reverse the first len bits of a code
  632. template<class Unsigned>
  633. inline
  634. Unsigned
  635. deflate_stream::
  636. bi_reverse(Unsigned code, unsigned len)
  637. {
  638. BOOST_STATIC_ASSERT(std::is_unsigned<Unsigned>::value);
  639. BOOST_ASSERT(len <= 8 * sizeof(unsigned));
  640. Unsigned res = 0;
  641. do
  642. {
  643. res |= code & 1;
  644. code >>= 1;
  645. res <<= 1;
  646. }
  647. while(--len > 0);
  648. return res >> 1;
  649. }
  650. /* Generate the codes for a given tree and bit counts (which need not be optimal).
  651. IN assertion: the array bl_count contains the bit length statistics for
  652. the given tree and the field len is set for all tree elements.
  653. OUT assertion: the field code is set for all tree elements of non
  654. zero code length.
  655. */
  656. template<class>
  657. void
  658. deflate_stream::
  659. gen_codes(ct_data *tree, int max_code, std::uint16_t *bl_count)
  660. {
  661. std::uint16_t next_code[maxBits+1]; /* next code value for each bit length */
  662. std::uint16_t code = 0; /* running code value */
  663. int bits; /* bit index */
  664. int n; /* code index */
  665. // The distribution counts are first used to
  666. // generate the code values without bit reversal.
  667. for(bits = 1; bits <= maxBits; bits++)
  668. {
  669. code = (code + bl_count[bits-1]) << 1;
  670. next_code[bits] = code;
  671. }
  672. // Check that the bit counts in bl_count are consistent.
  673. // The last code must be all ones.
  674. BOOST_ASSERT(code + bl_count[maxBits]-1 == (1<<maxBits)-1);
  675. for(n = 0; n <= max_code; n++)
  676. {
  677. int len = tree[n].dl;
  678. if(len == 0)
  679. continue;
  680. tree[n].fc = bi_reverse(next_code[len]++, len);
  681. }
  682. }
  683. template<class>
  684. auto
  685. deflate_stream::get_lut() ->
  686. lut_type const&
  687. {
  688. struct init
  689. {
  690. lut_type tables;
  691. init()
  692. {
  693. // number of codes at each bit length for an optimal tree
  694. //std::uint16_t bl_count[maxBits+1];
  695. // Initialize the mapping length (0..255) -> length code (0..28)
  696. std::uint8_t length = 0;
  697. for(std::uint8_t code = 0; code < lengthCodes-1; ++code)
  698. {
  699. tables.base_length[code] = length;
  700. auto const run = 1U << tables.extra_lbits[code];
  701. for(unsigned n = 0; n < run; ++n)
  702. tables.length_code[length++] = code;
  703. }
  704. BOOST_ASSERT(length == 0);
  705. // Note that the length 255 (match length 258) can be represented
  706. // in two different ways: code 284 + 5 bits or code 285, so we
  707. // overwrite length_code[255] to use the best encoding:
  708. tables.length_code[255] = lengthCodes-1;
  709. // Initialize the mapping dist (0..32K) -> dist code (0..29)
  710. {
  711. std::uint8_t code;
  712. std::uint16_t dist = 0;
  713. for(code = 0; code < 16; code++)
  714. {
  715. tables.base_dist[code] = dist;
  716. auto const run = 1U << tables.extra_dbits[code];
  717. for(unsigned n = 0; n < run; ++n)
  718. tables.dist_code[dist++] = code;
  719. }
  720. BOOST_ASSERT(dist == 256);
  721. // from now on, all distances are divided by 128
  722. dist >>= 7;
  723. for(; code < dCodes; ++code)
  724. {
  725. tables.base_dist[code] = dist << 7;
  726. auto const run = 1U << (tables.extra_dbits[code]-7);
  727. for(std::size_t n = 0; n < run; ++n)
  728. tables.dist_code[256 + dist++] = code;
  729. }
  730. BOOST_ASSERT(dist == 256);
  731. }
  732. // Construct the codes of the static literal tree
  733. std::uint16_t bl_count[maxBits+1];
  734. std::memset(bl_count, 0, sizeof(bl_count));
  735. unsigned n = 0;
  736. while (n <= 143)
  737. tables.ltree[n++].dl = 8;
  738. bl_count[8] += 144;
  739. while (n <= 255)
  740. tables.ltree[n++].dl = 9;
  741. bl_count[9] += 112;
  742. while (n <= 279)
  743. tables.ltree[n++].dl = 7;
  744. bl_count[7] += 24;
  745. while (n <= 287)
  746. tables.ltree[n++].dl = 8;
  747. bl_count[8] += 8;
  748. // Codes 286 and 287 do not exist, but we must include them in the tree
  749. // construction to get a canonical Huffman tree (longest code all ones)
  750. gen_codes(tables.ltree, lCodes+1, bl_count);
  751. for(n = 0; n < dCodes; ++n)
  752. {
  753. tables.dtree[n].dl = 5;
  754. tables.dtree[n].fc =
  755. static_cast<std::uint16_t>(bi_reverse(n, 5));
  756. }
  757. }
  758. };
  759. static init const data;
  760. return data.tables;
  761. }
  762. template<class>
  763. void
  764. deflate_stream::
  765. doReset(
  766. int level,
  767. int windowBits,
  768. int memLevel,
  769. Strategy strategy)
  770. {
  771. if(level == default_size)
  772. level = 6;
  773. // VFALCO What do we do about this?
  774. // until 256-byte window bug fixed
  775. if(windowBits == 8)
  776. windowBits = 9;
  777. if(level < 0 || level > 9)
  778. BOOST_THROW_EXCEPTION(std::invalid_argument{
  779. "invalid level"});
  780. if(windowBits < 8 || windowBits > 15)
  781. BOOST_THROW_EXCEPTION(std::invalid_argument{
  782. "invalid windowBits"});
  783. if(memLevel < 1 || memLevel > max_mem_level)
  784. BOOST_THROW_EXCEPTION(std::invalid_argument{
  785. "invalid memLevel"});
  786. w_bits_ = windowBits;
  787. hash_bits_ = memLevel + 7;
  788. // 16K elements by default
  789. lit_bufsize_ = 1 << (memLevel + 6);
  790. level_ = level;
  791. strategy_ = strategy;
  792. inited_ = false;
  793. }
  794. template<class>
  795. void
  796. deflate_stream::
  797. doReset()
  798. {
  799. inited_ = false;
  800. }
  801. template<class>
  802. void
  803. deflate_stream::
  804. doClear()
  805. {
  806. inited_ = false;
  807. buf_.reset();
  808. }
  809. template<class>
  810. std::size_t
  811. deflate_stream::
  812. doUpperBound(std::size_t sourceLen) const
  813. {
  814. std::size_t complen;
  815. std::size_t wraplen;
  816. /* conservative upper bound for compressed data */
  817. complen = sourceLen +
  818. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
  819. /* compute wrapper length */
  820. wraplen = 0;
  821. /* if not default parameters, return conservative bound */
  822. if(w_bits_ != 15 || hash_bits_ != 8 + 7)
  823. return complen + wraplen;
  824. /* default settings: return tight bound for that case */
  825. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
  826. (sourceLen >> 25) + 13 - 6 + wraplen;
  827. }
  828. template<class>
  829. void
  830. deflate_stream::
  831. doTune(
  832. int good_length,
  833. int max_lazy,
  834. int nice_length,
  835. int max_chain)
  836. {
  837. good_match_ = good_length;
  838. nice_match_ = nice_length;
  839. max_lazy_match_ = max_lazy;
  840. max_chain_length_ = max_chain;
  841. }
  842. template<class>
  843. void
  844. deflate_stream::
  845. doParams(z_params& zs, int level, Strategy strategy, error_code& ec)
  846. {
  847. compress_func func;
  848. if(level == default_size)
  849. level = 6;
  850. if(level < 0 || level > 9)
  851. {
  852. ec = error::stream_error;
  853. return;
  854. }
  855. func = get_config(level_).func;
  856. if((strategy != strategy_ || func != get_config(level).func) &&
  857. zs.total_in != 0)
  858. {
  859. // Flush the last buffer:
  860. doWrite(zs, Flush::block, ec);
  861. if(ec == error::need_buffers && pending_ == 0)
  862. ec.assign(0, ec.category());
  863. }
  864. if(level_ != level)
  865. {
  866. level_ = level;
  867. max_lazy_match_ = get_config(level).max_lazy;
  868. good_match_ = get_config(level).good_length;
  869. nice_match_ = get_config(level).nice_length;
  870. max_chain_length_ = get_config(level).max_chain;
  871. }
  872. strategy_ = strategy;
  873. }
  874. // VFALCO boost::optional param is a workaround for
  875. // gcc "maybe uninitialized" warning
  876. // https://github.com/boostorg/beast/issues/532
  877. //
  878. template<class>
  879. void
  880. deflate_stream::
  881. doWrite(z_params& zs, boost::optional<Flush> flush, error_code& ec)
  882. {
  883. maybe_init();
  884. if(zs.next_out == 0 || (zs.next_in == 0 && zs.avail_in != 0) ||
  885. (status_ == FINISH_STATE && flush != Flush::finish))
  886. {
  887. ec = error::stream_error;
  888. return;
  889. }
  890. if(zs.avail_out == 0)
  891. {
  892. ec = error::need_buffers;
  893. return;
  894. }
  895. // value of flush param for previous deflate call
  896. auto old_flush = boost::make_optional<Flush>(
  897. last_flush_.is_initialized(),
  898. last_flush_ ? *last_flush_ : Flush::none);
  899. last_flush_ = flush;
  900. // Flush as much pending output as possible
  901. if(pending_ != 0)
  902. {
  903. flush_pending(zs);
  904. if(zs.avail_out == 0)
  905. {
  906. /* Since avail_out is 0, deflate will be called again with
  907. * more output space, but possibly with both pending and
  908. * avail_in equal to zero. There won't be anything to do,
  909. * but this is not an error situation so make sure we
  910. * return OK instead of BUF_ERROR at next call of deflate:
  911. */
  912. last_flush_ = boost::none;
  913. return;
  914. }
  915. }
  916. else if(zs.avail_in == 0 && (
  917. old_flush && flush <= *old_flush
  918. ) && flush != Flush::finish)
  919. {
  920. /* Make sure there is something to do and avoid duplicate consecutive
  921. * flushes. For repeated and useless calls with Flush::finish, we keep
  922. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  923. */
  924. ec = error::need_buffers;
  925. return;
  926. }
  927. // User must not provide more input after the first FINISH:
  928. if(status_ == FINISH_STATE && zs.avail_in != 0)
  929. {
  930. ec = error::need_buffers;
  931. return;
  932. }
  933. /* Start a new block or continue the current one.
  934. */
  935. if(zs.avail_in != 0 || lookahead_ != 0 ||
  936. (flush != Flush::none && status_ != FINISH_STATE))
  937. {
  938. block_state bstate;
  939. switch(strategy_)
  940. {
  941. case Strategy::huffman:
  942. bstate = deflate_huff(zs, flush.get());
  943. break;
  944. case Strategy::rle:
  945. bstate = deflate_rle(zs, flush.get());
  946. break;
  947. default:
  948. {
  949. bstate = (this->*(get_config(level_).func))(zs, flush.get());
  950. break;
  951. }
  952. }
  953. if(bstate == finish_started || bstate == finish_done)
  954. {
  955. status_ = FINISH_STATE;
  956. }
  957. if(bstate == need_more || bstate == finish_started)
  958. {
  959. if(zs.avail_out == 0)
  960. {
  961. last_flush_ = boost::none; /* avoid BUF_ERROR next call, see above */
  962. }
  963. return;
  964. /* If flush != Flush::none && avail_out == 0, the next call
  965. of deflate should use the same flush parameter to make sure
  966. that the flush is complete. So we don't have to output an
  967. empty block here, this will be done at next call. This also
  968. ensures that for a very small output buffer, we emit at most
  969. one empty block.
  970. */
  971. }
  972. if(bstate == block_done)
  973. {
  974. if(flush == Flush::partial)
  975. {
  976. tr_align();
  977. }
  978. else if(flush != Flush::block)
  979. {
  980. /* FULL_FLUSH or SYNC_FLUSH */
  981. tr_stored_block((char*)0, 0L, 0);
  982. /* For a full flush, this empty block will be recognized
  983. * as a special marker by inflate_sync().
  984. */
  985. if(flush == Flush::full)
  986. {
  987. clear_hash(); // forget history
  988. if(lookahead_ == 0)
  989. {
  990. strstart_ = 0;
  991. block_start_ = 0L;
  992. insert_ = 0;
  993. }
  994. }
  995. }
  996. flush_pending(zs);
  997. if(zs.avail_out == 0)
  998. {
  999. last_flush_ = boost::none; /* avoid BUF_ERROR at next call, see above */
  1000. return;
  1001. }
  1002. }
  1003. }
  1004. if(flush == Flush::finish)
  1005. {
  1006. ec = error::end_of_stream;
  1007. return;
  1008. }
  1009. }
  1010. // VFALCO Warning: untested
  1011. template<class>
  1012. void
  1013. deflate_stream::
  1014. doDictionary(Byte const* dict, uInt dictLength, error_code& ec)
  1015. {
  1016. if(lookahead_)
  1017. {
  1018. ec = error::stream_error;
  1019. return;
  1020. }
  1021. maybe_init();
  1022. /* if dict would fill window, just replace the history */
  1023. if(dictLength >= w_size_)
  1024. {
  1025. clear_hash();
  1026. strstart_ = 0;
  1027. block_start_ = 0L;
  1028. insert_ = 0;
  1029. dict += dictLength - w_size_; /* use the tail */
  1030. dictLength = w_size_;
  1031. }
  1032. /* insert dict into window and hash */
  1033. z_params zs;
  1034. zs.avail_in = dictLength;
  1035. zs.next_in = (const Byte *)dict;
  1036. zs.avail_out = 0;
  1037. zs.next_out = 0;
  1038. fill_window(zs);
  1039. while(lookahead_ >= minMatch)
  1040. {
  1041. uInt str = strstart_;
  1042. uInt n = lookahead_ - (minMatch-1);
  1043. do
  1044. {
  1045. update_hash(ins_h_, window_[str + minMatch-1]);
  1046. prev_[str & w_mask_] = head_[ins_h_];
  1047. head_[ins_h_] = (std::uint16_t)str;
  1048. str++;
  1049. }
  1050. while(--n);
  1051. strstart_ = str;
  1052. lookahead_ = minMatch-1;
  1053. fill_window(zs);
  1054. }
  1055. strstart_ += lookahead_;
  1056. block_start_ = (long)strstart_;
  1057. insert_ = lookahead_;
  1058. lookahead_ = 0;
  1059. match_length_ = prev_length_ = minMatch-1;
  1060. match_available_ = 0;
  1061. }
  1062. template<class>
  1063. void
  1064. deflate_stream::
  1065. doPrime(int bits, int value, error_code& ec)
  1066. {
  1067. maybe_init();
  1068. if((Byte *)(d_buf_) < pending_out_ + ((Buf_size + 7) >> 3))
  1069. {
  1070. ec = error::need_buffers;
  1071. return;
  1072. }
  1073. do
  1074. {
  1075. int put = Buf_size - bi_valid_;
  1076. if(put > bits)
  1077. put = bits;
  1078. bi_buf_ |= (std::uint16_t)((value & ((1 << put) - 1)) << bi_valid_);
  1079. bi_valid_ += put;
  1080. tr_flush_bits();
  1081. value >>= put;
  1082. bits -= put;
  1083. }
  1084. while(bits);
  1085. }
  1086. template<class>
  1087. void
  1088. deflate_stream::
  1089. doPending(unsigned* value, int* bits)
  1090. {
  1091. if(value != 0)
  1092. *value = pending_;
  1093. if(bits != 0)
  1094. *bits = bi_valid_;
  1095. }
  1096. //--------------------------------------------------------------------------
  1097. // Do lazy initialization
  1098. template<class>
  1099. void
  1100. deflate_stream::
  1101. init()
  1102. {
  1103. // Caller must set these:
  1104. // w_bits_
  1105. // hash_bits_
  1106. // lit_bufsize_
  1107. // level_
  1108. // strategy_
  1109. w_size_ = 1 << w_bits_;
  1110. w_mask_ = w_size_ - 1;
  1111. hash_size_ = 1 << hash_bits_;
  1112. hash_mask_ = hash_size_ - 1;
  1113. hash_shift_ = ((hash_bits_+minMatch-1)/minMatch);
  1114. auto const nwindow = w_size_ * 2*sizeof(Byte);
  1115. auto const nprev = w_size_ * sizeof(std::uint16_t);
  1116. auto const nhead = hash_size_ * sizeof(std::uint16_t);
  1117. auto const noverlay = lit_bufsize_ * (sizeof(std::uint16_t)+2);
  1118. auto const needed = nwindow + nprev + nhead + noverlay;
  1119. if(! buf_ || buf_size_ != needed)
  1120. {
  1121. buf_ = boost::make_unique_noinit<
  1122. std::uint8_t[]>(needed);
  1123. buf_size_ = needed;
  1124. }
  1125. window_ = reinterpret_cast<Byte*>(buf_.get());
  1126. prev_ = reinterpret_cast<std::uint16_t*>(buf_.get() + nwindow);
  1127. head_ = reinterpret_cast<std::uint16_t*>(buf_.get() + nwindow + nprev);
  1128. /* We overlay pending_buf_ and d_buf_ + l_buf_. This works
  1129. since the average output size for(length, distance)
  1130. codes is <= 24 bits.
  1131. */
  1132. auto overlay = reinterpret_cast<std::uint16_t*>(
  1133. buf_.get() + nwindow + nprev + nhead);
  1134. // nothing written to window_ yet
  1135. high_water_ = 0;
  1136. pending_buf_ =
  1137. reinterpret_cast<std::uint8_t*>(overlay);
  1138. pending_buf_size_ =
  1139. static_cast<std::uint32_t>(lit_bufsize_) *
  1140. (sizeof(std::uint16_t) + 2L);
  1141. d_buf_ = overlay + lit_bufsize_ / sizeof(std::uint16_t);
  1142. l_buf_ = pending_buf_ + (1 + sizeof(std::uint16_t)) * lit_bufsize_;
  1143. pending_ = 0;
  1144. pending_out_ = pending_buf_;
  1145. status_ = BUSY_STATE;
  1146. last_flush_ = Flush::none;
  1147. tr_init();
  1148. lm_init();
  1149. inited_ = true;
  1150. }
  1151. /* Initialize the "longest match" routines for a new zlib stream
  1152. */
  1153. template<class>
  1154. void
  1155. deflate_stream::
  1156. lm_init()
  1157. {
  1158. window_size_ = (std::uint32_t)2L*w_size_;
  1159. clear_hash();
  1160. /* Set the default configuration parameters:
  1161. */
  1162. // VFALCO TODO just copy the config struct
  1163. max_lazy_match_ = get_config(level_).max_lazy;
  1164. good_match_ = get_config(level_).good_length;
  1165. nice_match_ = get_config(level_).nice_length;
  1166. max_chain_length_ = get_config(level_).max_chain;
  1167. strstart_ = 0;
  1168. block_start_ = 0L;
  1169. lookahead_ = 0;
  1170. insert_ = 0;
  1171. match_length_ = prev_length_ = minMatch-1;
  1172. match_available_ = 0;
  1173. ins_h_ = 0;
  1174. }
  1175. // Initialize a new block.
  1176. //
  1177. template<class>
  1178. void
  1179. deflate_stream::
  1180. init_block()
  1181. {
  1182. for(int n = 0; n < lCodes; n++)
  1183. dyn_ltree_[n].fc = 0;
  1184. for(int n = 0; n < dCodes; n++)
  1185. dyn_dtree_[n].fc = 0;
  1186. for(int n = 0; n < blCodes; n++)
  1187. bl_tree_[n].fc = 0;
  1188. dyn_ltree_[END_BLOCK].fc = 1;
  1189. opt_len_ = 0L;
  1190. static_len_ = 0L;
  1191. last_lit_ = 0;
  1192. matches_ = 0;
  1193. }
  1194. /* Restore the heap property by moving down the tree starting at node k,
  1195. exchanging a node with the smallest of its two sons if necessary,
  1196. stopping when the heap property is re-established (each father smaller
  1197. than its two sons).
  1198. */
  1199. template<class>
  1200. void
  1201. deflate_stream::
  1202. pqdownheap(
  1203. ct_data const* tree, // the tree to restore
  1204. int k) // node to move down
  1205. {
  1206. int v = heap_[k];
  1207. int j = k << 1; // left son of k
  1208. while(j <= heap_len_)
  1209. {
  1210. // Set j to the smallest of the two sons:
  1211. if(j < heap_len_ &&
  1212. smaller(tree, heap_[j+1], heap_[j]))
  1213. j++;
  1214. // Exit if v is smaller than both sons
  1215. if(smaller(tree, v, heap_[j]))
  1216. break;
  1217. // Exchange v with the smallest son
  1218. heap_[k] = heap_[j];
  1219. k = j;
  1220. // And continue down the tree,
  1221. // setting j to the left son of k
  1222. j <<= 1;
  1223. }
  1224. heap_[k] = v;
  1225. }
  1226. /* Remove the smallest element from the heap and recreate the heap
  1227. with one less element. Updates heap and heap_len.
  1228. */
  1229. template<class>
  1230. inline
  1231. void
  1232. deflate_stream::
  1233. pqremove(ct_data const* tree, int& top)
  1234. {
  1235. top = heap_[kSmallest];
  1236. heap_[kSmallest] = heap_[heap_len_--];
  1237. pqdownheap(tree, kSmallest);
  1238. }
  1239. /* Compute the optimal bit lengths for a tree and update the total bit length
  1240. for the current block.
  1241. IN assertion: the fields freq and dad are set, heap[heap_max] and
  1242. above are the tree nodes sorted by increasing frequency.
  1243. OUT assertions: the field len is set to the optimal bit length, the
  1244. array bl_count contains the frequencies for each bit length.
  1245. The length opt_len is updated; static_len is also updated if stree is
  1246. not null.
  1247. */
  1248. template<class>
  1249. void
  1250. deflate_stream::
  1251. gen_bitlen(tree_desc *desc)
  1252. {
  1253. ct_data *tree = desc->dyn_tree;
  1254. int max_code = desc->max_code;
  1255. ct_data const* stree = desc->stat_desc->static_tree;
  1256. std::uint8_t const *extra = desc->stat_desc->extra_bits;
  1257. int base = desc->stat_desc->extra_base;
  1258. int max_length = desc->stat_desc->max_length;
  1259. int h; // heap index
  1260. int n, m; // iterate over the tree elements
  1261. int bits; // bit length
  1262. int xbits; // extra bits
  1263. std::uint16_t f; // frequency
  1264. int overflow = 0; // number of elements with bit length too large
  1265. std::fill(&bl_count_[0], &bl_count_[maxBits+1], std::uint16_t{0});
  1266. /* In a first pass, compute the optimal bit lengths (which may
  1267. * overflow in the case of the bit length tree).
  1268. */
  1269. tree[heap_[heap_max_]].dl = 0; // root of the heap
  1270. for(h = heap_max_+1; h < HEAP_SIZE; h++) {
  1271. n = heap_[h];
  1272. bits = tree[tree[n].dl].dl + 1;
  1273. if(bits > max_length) bits = max_length, overflow++;
  1274. // We overwrite tree[n].dl which is no longer needed
  1275. tree[n].dl = (std::uint16_t)bits;
  1276. if(n > max_code)
  1277. continue; // not a leaf node
  1278. bl_count_[bits]++;
  1279. xbits = 0;
  1280. if(n >= base)
  1281. xbits = extra[n-base];
  1282. f = tree[n].fc;
  1283. opt_len_ += (std::uint32_t)f * (bits + xbits);
  1284. if(stree)
  1285. static_len_ += (std::uint32_t)f * (stree[n].dl + xbits);
  1286. }
  1287. if(overflow == 0)
  1288. return;
  1289. // Find the first bit length which could increase:
  1290. do
  1291. {
  1292. bits = max_length-1;
  1293. while(bl_count_[bits] == 0)
  1294. bits--;
  1295. bl_count_[bits]--; // move one leaf down the tree
  1296. bl_count_[bits+1] += 2; // move one overflow item as its brother
  1297. bl_count_[max_length]--;
  1298. /* The brother of the overflow item also moves one step up,
  1299. * but this does not affect bl_count[max_length]
  1300. */
  1301. overflow -= 2;
  1302. }
  1303. while(overflow > 0);
  1304. /* Now recompute all bit lengths, scanning in increasing frequency.
  1305. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  1306. * lengths instead of fixing only the wrong ones. This idea is taken
  1307. * from 'ar' written by Haruhiko Okumura.)
  1308. */
  1309. for(bits = max_length; bits != 0; bits--)
  1310. {
  1311. n = bl_count_[bits];
  1312. while(n != 0)
  1313. {
  1314. m = heap_[--h];
  1315. if(m > max_code)
  1316. continue;
  1317. if((unsigned) tree[m].dl != (unsigned) bits)
  1318. {
  1319. opt_len_ += ((long)bits - (long)tree[m].dl) *(long)tree[m].fc;
  1320. tree[m].dl = (std::uint16_t)bits;
  1321. }
  1322. n--;
  1323. }
  1324. }
  1325. }
  1326. /* Construct one Huffman tree and assigns the code bit strings and lengths.
  1327. Update the total bit length for the current block.
  1328. IN assertion: the field freq is set for all tree elements.
  1329. OUT assertions: the fields len and code are set to the optimal bit length
  1330. and corresponding code. The length opt_len is updated; static_len is
  1331. also updated if stree is not null. The field max_code is set.
  1332. */
  1333. template<class>
  1334. void
  1335. deflate_stream::
  1336. build_tree(tree_desc *desc)
  1337. {
  1338. ct_data *tree = desc->dyn_tree;
  1339. ct_data const* stree = desc->stat_desc->static_tree;
  1340. int elems = desc->stat_desc->elems;
  1341. int n, m; // iterate over heap elements
  1342. int max_code = -1; // largest code with non zero frequency
  1343. int node; // new node being created
  1344. /* Construct the initial heap, with least frequent element in
  1345. * heap[kSmallest]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1346. * heap[0] is not used.
  1347. */
  1348. heap_len_ = 0;
  1349. heap_max_ = HEAP_SIZE;
  1350. for(n = 0; n < elems; n++)
  1351. {
  1352. if(tree[n].fc != 0)
  1353. {
  1354. heap_[++(heap_len_)] = max_code = n;
  1355. depth_[n] = 0;
  1356. }
  1357. else
  1358. {
  1359. tree[n].dl = 0;
  1360. }
  1361. }
  1362. /* The pkzip format requires that at least one distance code exists,
  1363. * and that at least one bit should be sent even if there is only one
  1364. * possible code. So to avoid special checks later on we force at least
  1365. * two codes of non zero frequency.
  1366. */
  1367. while(heap_len_ < 2)
  1368. {
  1369. node = heap_[++(heap_len_)] = (max_code < 2 ? ++max_code : 0);
  1370. tree[node].fc = 1;
  1371. depth_[node] = 0;
  1372. opt_len_--;
  1373. if(stree)
  1374. static_len_ -= stree[node].dl;
  1375. // node is 0 or 1 so it does not have extra bits
  1376. }
  1377. desc->max_code = max_code;
  1378. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1379. * establish sub-heaps of increasing lengths:
  1380. */
  1381. for(n = heap_len_/2; n >= 1; n--)
  1382. pqdownheap(tree, n);
  1383. /* Construct the Huffman tree by repeatedly combining the least two
  1384. * frequent nodes.
  1385. */
  1386. node = elems; /* next internal node of the tree */
  1387. do
  1388. {
  1389. pqremove(tree, n); /* n = node of least frequency */
  1390. m = heap_[kSmallest]; /* m = node of next least frequency */
  1391. heap_[--(heap_max_)] = n; /* keep the nodes sorted by frequency */
  1392. heap_[--(heap_max_)] = m;
  1393. /* Create a new node father of n and m */
  1394. tree[node].fc = tree[n].fc + tree[m].fc;
  1395. depth_[node] = (std::uint8_t)((depth_[n] >= depth_[m] ?
  1396. depth_[n] : depth_[m]) + 1);
  1397. tree[n].dl = tree[m].dl = (std::uint16_t)node;
  1398. /* and insert the new node in the heap */
  1399. heap_[kSmallest] = node++;
  1400. pqdownheap(tree, kSmallest);
  1401. }
  1402. while(heap_len_ >= 2);
  1403. heap_[--(heap_max_)] = heap_[kSmallest];
  1404. /* At this point, the fields freq and dad are set. We can now
  1405. * generate the bit lengths.
  1406. */
  1407. gen_bitlen((tree_desc *)desc);
  1408. /* The field len is now set, we can generate the bit codes */
  1409. gen_codes(tree, max_code, bl_count_);
  1410. }
  1411. /* Scan a literal or distance tree to determine the frequencies
  1412. of the codes in the bit length tree.
  1413. */
  1414. template<class>
  1415. void
  1416. deflate_stream::
  1417. scan_tree(
  1418. ct_data *tree, // the tree to be scanned
  1419. int max_code) // and its largest code of non zero frequency
  1420. {
  1421. int n; // iterates over all tree elements
  1422. int prevlen = -1; // last emitted length
  1423. int curlen; // length of current code
  1424. int nextlen = tree[0].dl; // length of next code
  1425. std::uint16_t count = 0; // repeat count of the current code
  1426. int max_count = 7; // max repeat count
  1427. int min_count = 4; // min repeat count
  1428. if(nextlen == 0)
  1429. {
  1430. max_count = 138;
  1431. min_count = 3;
  1432. }
  1433. tree[max_code+1].dl = (std::uint16_t)0xffff; // guard
  1434. for(n = 0; n <= max_code; n++)
  1435. {
  1436. curlen = nextlen; nextlen = tree[n+1].dl;
  1437. if(++count < max_count && curlen == nextlen)
  1438. {
  1439. continue;
  1440. }
  1441. else if(count < min_count)
  1442. {
  1443. bl_tree_[curlen].fc += count;
  1444. }
  1445. else if(curlen != 0)
  1446. {
  1447. if(curlen != prevlen) bl_tree_[curlen].fc++;
  1448. bl_tree_[REP_3_6].fc++;
  1449. }
  1450. else if(count <= 10)
  1451. {
  1452. bl_tree_[REPZ_3_10].fc++;
  1453. }
  1454. else
  1455. {
  1456. bl_tree_[REPZ_11_138].fc++;
  1457. }
  1458. count = 0;
  1459. prevlen = curlen;
  1460. if(nextlen == 0)
  1461. {
  1462. max_count = 138;
  1463. min_count = 3;
  1464. }
  1465. else if(curlen == nextlen)
  1466. {
  1467. max_count = 6;
  1468. min_count = 3;
  1469. }
  1470. else
  1471. {
  1472. max_count = 7;
  1473. min_count = 4;
  1474. }
  1475. }
  1476. }
  1477. /* Send a literal or distance tree in compressed form,
  1478. using the codes in bl_tree.
  1479. */
  1480. template<class>
  1481. void
  1482. deflate_stream::
  1483. send_tree(
  1484. ct_data *tree, // the tree to be scanned
  1485. int max_code) // and its largest code of non zero frequency
  1486. {
  1487. int n; // iterates over all tree elements
  1488. int prevlen = -1; // last emitted length
  1489. int curlen; // length of current code
  1490. int nextlen = tree[0].dl; // length of next code
  1491. int count = 0; // repeat count of the current code
  1492. int max_count = 7; // max repeat count
  1493. int min_count = 4; // min repeat count
  1494. // tree[max_code+1].dl = -1; // guard already set
  1495. if(nextlen == 0)
  1496. {
  1497. max_count = 138;
  1498. min_count = 3;
  1499. }
  1500. for(n = 0; n <= max_code; n++)
  1501. {
  1502. curlen = nextlen;
  1503. nextlen = tree[n+1].dl;
  1504. if(++count < max_count && curlen == nextlen)
  1505. {
  1506. continue;
  1507. }
  1508. else if(count < min_count)
  1509. {
  1510. do
  1511. {
  1512. send_code(curlen, bl_tree_);
  1513. }
  1514. while (--count != 0);
  1515. }
  1516. else if(curlen != 0)
  1517. {
  1518. if(curlen != prevlen)
  1519. {
  1520. send_code(curlen, bl_tree_);
  1521. count--;
  1522. }
  1523. BOOST_ASSERT(count >= 3 && count <= 6);
  1524. send_code(REP_3_6, bl_tree_);
  1525. send_bits(count-3, 2);
  1526. }
  1527. else if(count <= 10)
  1528. {
  1529. send_code(REPZ_3_10, bl_tree_);
  1530. send_bits(count-3, 3);
  1531. }
  1532. else
  1533. {
  1534. send_code(REPZ_11_138, bl_tree_);
  1535. send_bits(count-11, 7);
  1536. }
  1537. count = 0;
  1538. prevlen = curlen;
  1539. if(nextlen == 0)
  1540. {
  1541. max_count = 138;
  1542. min_count = 3;
  1543. }
  1544. else if(curlen == nextlen)
  1545. {
  1546. max_count = 6;
  1547. min_count = 3;
  1548. }
  1549. else
  1550. {
  1551. max_count = 7;
  1552. min_count = 4;
  1553. }
  1554. }
  1555. }
  1556. /* Construct the Huffman tree for the bit lengths and return
  1557. the index in bl_order of the last bit length code to send.
  1558. */
  1559. template<class>
  1560. int
  1561. deflate_stream::
  1562. build_bl_tree()
  1563. {
  1564. int max_blindex; // index of last bit length code of non zero freq
  1565. // Determine the bit length frequencies for literal and distance trees
  1566. scan_tree((ct_data *)dyn_ltree_, l_desc_.max_code);
  1567. scan_tree((ct_data *)dyn_dtree_, d_desc_.max_code);
  1568. // Build the bit length tree:
  1569. build_tree((tree_desc *)(&(bl_desc_)));
  1570. /* opt_len now includes the length of the tree representations, except
  1571. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1572. */
  1573. /* Determine the number of bit length codes to send. The pkzip format
  1574. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1575. * 3 but the actual value used is 4.)
  1576. */
  1577. for(max_blindex = blCodes-1; max_blindex >= 3; max_blindex--)
  1578. {
  1579. if(bl_tree_[lut_.bl_order[max_blindex]].dl != 0)
  1580. break;
  1581. }
  1582. // Update opt_len to include the bit length tree and counts
  1583. opt_len_ += 3*(max_blindex+1) + 5+5+4;
  1584. return max_blindex;
  1585. }
  1586. /* Send the header for a block using dynamic Huffman trees: the counts,
  1587. the lengths of the bit length codes, the literal tree and the distance
  1588. tree.
  1589. IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1590. */
  1591. template<class>
  1592. void
  1593. deflate_stream::
  1594. send_all_trees(
  1595. int lcodes,
  1596. int dcodes,
  1597. int blcodes) // number of codes for each tree
  1598. {
  1599. int rank; // index in bl_order
  1600. BOOST_ASSERT(lcodes >= 257 && dcodes >= 1 && blcodes >= 4);
  1601. BOOST_ASSERT(lcodes <= lCodes && dcodes <= dCodes && blcodes <= blCodes);
  1602. send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
  1603. send_bits(dcodes-1, 5);
  1604. send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
  1605. for(rank = 0; rank < blcodes; rank++)
  1606. send_bits(bl_tree_[lut_.bl_order[rank]].dl, 3);
  1607. send_tree((ct_data *)dyn_ltree_, lcodes-1); // literal tree
  1608. send_tree((ct_data *)dyn_dtree_, dcodes-1); // distance tree
  1609. }
  1610. /* Send the block data compressed using the given Huffman trees
  1611. */
  1612. template<class>
  1613. void
  1614. deflate_stream::
  1615. compress_block(
  1616. ct_data const* ltree, // literal tree
  1617. ct_data const* dtree) // distance tree
  1618. {
  1619. unsigned dist; /* distance of matched string */
  1620. int lc; /* match length or unmatched char (if dist == 0) */
  1621. unsigned lx = 0; /* running index in l_buf */
  1622. unsigned code; /* the code to send */
  1623. int extra; /* number of extra bits to send */
  1624. if(last_lit_ != 0)
  1625. {
  1626. do
  1627. {
  1628. dist = d_buf_[lx];
  1629. lc = l_buf_[lx++];
  1630. if(dist == 0)
  1631. {
  1632. send_code(lc, ltree); /* send a literal byte */
  1633. }
  1634. else
  1635. {
  1636. /* Here, lc is the match length - minMatch */
  1637. code = lut_.length_code[lc];
  1638. send_code(code+literals+1, ltree); /* send the length code */
  1639. extra = lut_.extra_lbits[code];
  1640. if(extra != 0)
  1641. {
  1642. lc -= lut_.base_length[code];
  1643. send_bits(lc, extra); /* send the extra length bits */
  1644. }
  1645. dist--; /* dist is now the match distance - 1 */
  1646. code = d_code(dist);
  1647. BOOST_ASSERT(code < dCodes);
  1648. send_code(code, dtree); /* send the distance code */
  1649. extra = lut_.extra_dbits[code];
  1650. if(extra != 0)
  1651. {
  1652. dist -= lut_.base_dist[code];
  1653. send_bits(dist, extra); /* send the extra distance bits */
  1654. }
  1655. } /* literal or match pair ? */
  1656. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  1657. BOOST_ASSERT((uInt)(pending_) < lit_bufsize_ + 2*lx);
  1658. }
  1659. while(lx < last_lit_);
  1660. }
  1661. send_code(END_BLOCK, ltree);
  1662. }
  1663. /* Check if the data type is TEXT or BINARY, using the following algorithm:
  1664. - TEXT if the two conditions below are satisfied:
  1665. a) There are no non-portable control characters belonging to the
  1666. "black list" (0..6, 14..25, 28..31).
  1667. b) There is at least one printable character belonging to the
  1668. "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  1669. - BINARY otherwise.
  1670. - The following partially-portable control characters form a
  1671. "gray list" that is ignored in this detection algorithm:
  1672. (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  1673. IN assertion: the fields fc of dyn_ltree are set.
  1674. */
  1675. template<class>
  1676. int
  1677. deflate_stream::
  1678. detect_data_type()
  1679. {
  1680. /* black_mask is the bit mask of black-listed bytes
  1681. * set bits 0..6, 14..25, and 28..31
  1682. * 0xf3ffc07f = binary 11110011111111111100000001111111
  1683. */
  1684. unsigned long black_mask = 0xf3ffc07fUL;
  1685. int n;
  1686. // Check for non-textual ("black-listed") bytes.
  1687. for(n = 0; n <= 31; n++, black_mask >>= 1)
  1688. if((black_mask & 1) && (dyn_ltree_[n].fc != 0))
  1689. return binary;
  1690. // Check for textual ("white-listed") bytes. */
  1691. if(dyn_ltree_[9].fc != 0 || dyn_ltree_[10].fc != 0
  1692. || dyn_ltree_[13].fc != 0)
  1693. return text;
  1694. for(n = 32; n < literals; n++)
  1695. if(dyn_ltree_[n].fc != 0)
  1696. return text;
  1697. /* There are no "black-listed" or "white-listed" bytes:
  1698. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  1699. */
  1700. return binary;
  1701. }
  1702. /* Flush the bit buffer and align the output on a byte boundary
  1703. */
  1704. template<class>
  1705. void
  1706. deflate_stream::
  1707. bi_windup()
  1708. {
  1709. if(bi_valid_ > 8)
  1710. put_short(bi_buf_);
  1711. else if(bi_valid_ > 0)
  1712. put_byte((Byte)bi_buf_);
  1713. bi_buf_ = 0;
  1714. bi_valid_ = 0;
  1715. }
  1716. /* Flush the bit buffer, keeping at most 7 bits in it.
  1717. */
  1718. template<class>
  1719. void
  1720. deflate_stream::
  1721. bi_flush()
  1722. {
  1723. if(bi_valid_ == 16)
  1724. {
  1725. put_short(bi_buf_);
  1726. bi_buf_ = 0;
  1727. bi_valid_ = 0;
  1728. }
  1729. else if(bi_valid_ >= 8)
  1730. {
  1731. put_byte((Byte)bi_buf_);
  1732. bi_buf_ >>= 8;
  1733. bi_valid_ -= 8;
  1734. }
  1735. }
  1736. /* Copy a stored block, storing first the length and its
  1737. one's complement if requested.
  1738. */
  1739. template<class>
  1740. void
  1741. deflate_stream::
  1742. copy_block(
  1743. char *buf, // the input data
  1744. unsigned len, // its length
  1745. int header) // true if block header must be written
  1746. {
  1747. bi_windup(); // align on byte boundary
  1748. if(header)
  1749. {
  1750. put_short((std::uint16_t)len);
  1751. put_short((std::uint16_t)~len);
  1752. }
  1753. // VFALCO Use memcpy?
  1754. while (len--)
  1755. put_byte(*buf++);
  1756. }
  1757. //------------------------------------------------------------------------------
  1758. /* Initialize the tree data structures for a new zlib stream.
  1759. */
  1760. template<class>
  1761. void
  1762. deflate_stream::
  1763. tr_init()
  1764. {
  1765. l_desc_.dyn_tree = dyn_ltree_;
  1766. l_desc_.stat_desc = &lut_.l_desc;
  1767. d_desc_.dyn_tree = dyn_dtree_;
  1768. d_desc_.stat_desc = &lut_.d_desc;
  1769. bl_desc_.dyn_tree = bl_tree_;
  1770. bl_desc_.stat_desc = &lut_.bl_desc;
  1771. bi_buf_ = 0;
  1772. bi_valid_ = 0;
  1773. // Initialize the first block of the first file:
  1774. init_block();
  1775. }
  1776. /* Send one empty static block to give enough lookahead for inflate.
  1777. This takes 10 bits, of which 7 may remain in the bit buffer.
  1778. */
  1779. template<class>
  1780. void
  1781. deflate_stream::
  1782. tr_align()
  1783. {
  1784. send_bits(STATIC_TREES<<1, 3);
  1785. send_code(END_BLOCK, lut_.ltree);
  1786. bi_flush();
  1787. }
  1788. /* Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
  1789. */
  1790. template<class>
  1791. void
  1792. deflate_stream::
  1793. tr_flush_bits()
  1794. {
  1795. bi_flush();
  1796. }
  1797. /* Send a stored block
  1798. */
  1799. template<class>
  1800. void
  1801. deflate_stream::
  1802. tr_stored_block(
  1803. char *buf, // input block
  1804. std::uint32_t stored_len, // length of input block
  1805. int last) // one if this is the last block for a file
  1806. {
  1807. send_bits((STORED_BLOCK<<1)+last, 3); // send block type
  1808. copy_block(buf, (unsigned)stored_len, 1); // with header
  1809. }
  1810. template<class>
  1811. inline
  1812. void
  1813. deflate_stream::
  1814. tr_tally_dist(std::uint16_t dist, std::uint8_t len, bool& flush)
  1815. {
  1816. d_buf_[last_lit_] = dist;
  1817. l_buf_[last_lit_++] = len;
  1818. dist--;
  1819. dyn_ltree_[lut_.length_code[len]+literals+1].fc++;
  1820. dyn_dtree_[d_code(dist)].fc++;
  1821. flush = (last_lit_ == lit_bufsize_-1);
  1822. }
  1823. template<class>
  1824. inline
  1825. void
  1826. deflate_stream::
  1827. tr_tally_lit(std::uint8_t c, bool& flush)
  1828. {
  1829. d_buf_[last_lit_] = 0;
  1830. l_buf_[last_lit_++] = c;
  1831. dyn_ltree_[c].fc++;
  1832. flush = (last_lit_ == lit_bufsize_-1);
  1833. }
  1834. //------------------------------------------------------------------------------
  1835. /* Determine the best encoding for the current block: dynamic trees,
  1836. static trees or store, and output the encoded block to the zip file.
  1837. */
  1838. template<class>
  1839. void
  1840. deflate_stream::
  1841. tr_flush_block(
  1842. z_params& zs,
  1843. char *buf, // input block, or NULL if too old
  1844. std::uint32_t stored_len, // length of input block
  1845. int last) // one if this is the last block for a file
  1846. {
  1847. std::uint32_t opt_lenb;
  1848. std::uint32_t static_lenb; // opt_len and static_len in bytes
  1849. int max_blindex = 0; // index of last bit length code of non zero freq
  1850. // Build the Huffman trees unless a stored block is forced
  1851. if(level_ > 0)
  1852. {
  1853. // Check if the file is binary or text
  1854. if(zs.data_type == unknown)
  1855. zs.data_type = detect_data_type();
  1856. // Construct the literal and distance trees
  1857. build_tree((tree_desc *)(&(l_desc_)));
  1858. build_tree((tree_desc *)(&(d_desc_)));
  1859. /* At this point, opt_len and static_len are the total bit lengths of
  1860. * the compressed block data, excluding the tree representations.
  1861. */
  1862. /* Build the bit length tree for the above two trees, and get the index
  1863. * in bl_order of the last bit length code to send.
  1864. */
  1865. max_blindex = build_bl_tree();
  1866. /* Determine the best encoding. Compute the block lengths in bytes. */
  1867. opt_lenb = (opt_len_+3+7)>>3;
  1868. static_lenb = (static_len_+3+7)>>3;
  1869. if(static_lenb <= opt_lenb)
  1870. opt_lenb = static_lenb;
  1871. }
  1872. else
  1873. {
  1874. // VFALCO This assertion fails even in the original ZLib,
  1875. // happens with strategy == Z_HUFFMAN_ONLY, see:
  1876. // https://github.com/madler/zlib/issues/172
  1877. #if 0
  1878. BOOST_ASSERT(buf);
  1879. #endif
  1880. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  1881. }
  1882. #ifdef FORCE_STORED
  1883. if(buf != (char*)0) { /* force stored block */
  1884. #else
  1885. if(stored_len+4 <= opt_lenb && buf != (char*)0) {
  1886. /* 4: two words for the lengths */
  1887. #endif
  1888. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1889. * Otherwise we can't have processed more than WSIZE input bytes since
  1890. * the last block flush, because compression would have been
  1891. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1892. * transform a block into a stored block.
  1893. */
  1894. tr_stored_block(buf, stored_len, last);
  1895. #ifdef FORCE_STATIC
  1896. }
  1897. else if(static_lenb >= 0)
  1898. {
  1899. // force static trees
  1900. #else
  1901. }
  1902. else if(strategy_ == Strategy::fixed || static_lenb == opt_lenb)
  1903. {
  1904. #endif
  1905. send_bits((STATIC_TREES<<1)+last, 3);
  1906. compress_block(lut_.ltree, lut_.dtree);
  1907. }
  1908. else
  1909. {
  1910. send_bits((DYN_TREES<<1)+last, 3);
  1911. send_all_trees(l_desc_.max_code+1, d_desc_.max_code+1,
  1912. max_blindex+1);
  1913. compress_block((const ct_data *)dyn_ltree_,
  1914. (const ct_data *)dyn_dtree_);
  1915. }
  1916. /* The above check is made mod 2^32, for files larger than 512 MB
  1917. * and std::size_t implemented on 32 bits.
  1918. */
  1919. init_block();
  1920. if(last)
  1921. bi_windup();
  1922. }
  1923. template<class>
  1924. void
  1925. deflate_stream::
  1926. fill_window(z_params& zs)
  1927. {
  1928. unsigned n, m;
  1929. unsigned more; // Amount of free space at the end of the window.
  1930. std::uint16_t *p;
  1931. uInt wsize = w_size_;
  1932. do
  1933. {
  1934. more = (unsigned)(window_size_ -
  1935. (std::uint32_t)lookahead_ -(std::uint32_t)strstart_);
  1936. // VFALCO We don't support systems below 32-bit
  1937. #if 0
  1938. // Deal with !@#$% 64K limit:
  1939. if(sizeof(int) <= 2)
  1940. {
  1941. if(more == 0 && strstart_ == 0 && lookahead_ == 0)
  1942. {
  1943. more = wsize;
  1944. }
  1945. else if(more == (unsigned)(-1))
  1946. {
  1947. /* Very unlikely, but possible on 16 bit machine if
  1948. * strstart == 0 && lookahead == 1 (input done a byte at time)
  1949. */
  1950. more--;
  1951. }
  1952. }
  1953. #endif
  1954. /* If the window is almost full and there is insufficient lookahead,
  1955. move the upper half to the lower one to make room in the upper half.
  1956. */
  1957. if(strstart_ >= wsize+max_dist())
  1958. {
  1959. std::memcpy(window_, window_+wsize, (unsigned)wsize);
  1960. match_start_ -= wsize;
  1961. strstart_ -= wsize; // we now have strstart >= max_dist
  1962. block_start_ -= (long) wsize;
  1963. /* Slide the hash table (could be avoided with 32 bit values
  1964. at the expense of memory usage). We slide even when level == 0
  1965. to keep the hash table consistent if we switch back to level > 0
  1966. later. (Using level 0 permanently is not an optimal usage of
  1967. zlib, so we don't care about this pathological case.)
  1968. */
  1969. n = hash_size_;
  1970. p = &head_[n];
  1971. do
  1972. {
  1973. m = *--p;
  1974. *p = (std::uint16_t)(m >= wsize ? m-wsize : 0);
  1975. }
  1976. while(--n);
  1977. n = wsize;
  1978. p = &prev_[n];
  1979. do
  1980. {
  1981. m = *--p;
  1982. *p = (std::uint16_t)(m >= wsize ? m-wsize : 0);
  1983. /* If n is not on any hash chain, prev[n] is garbage but
  1984. its value will never be used.
  1985. */
  1986. }
  1987. while(--n);
  1988. more += wsize;
  1989. }
  1990. if(zs.avail_in == 0)
  1991. break;
  1992. /* If there was no sliding:
  1993. strstart <= WSIZE+max_dist-1 && lookahead <= kMinLookahead - 1 &&
  1994. more == window_size - lookahead - strstart
  1995. => more >= window_size - (kMinLookahead-1 + WSIZE + max_dist-1)
  1996. => more >= window_size - 2*WSIZE + 2
  1997. In the BIG_MEM or MMAP case (not yet supported),
  1998. window_size == input_size + kMinLookahead &&
  1999. strstart + lookahead_ <= input_size => more >= kMinLookahead.
  2000. Otherwise, window_size == 2*WSIZE so more >= 2.
  2001. If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  2002. */
  2003. n = read_buf(zs, window_ + strstart_ + lookahead_, more);
  2004. lookahead_ += n;
  2005. // Initialize the hash value now that we have some input:
  2006. if(lookahead_ + insert_ >= minMatch)
  2007. {
  2008. uInt str = strstart_ - insert_;
  2009. ins_h_ = window_[str];
  2010. update_hash(ins_h_, window_[str + 1]);
  2011. while(insert_)
  2012. {
  2013. update_hash(ins_h_, window_[str + minMatch-1]);
  2014. prev_[str & w_mask_] = head_[ins_h_];
  2015. head_[ins_h_] = (std::uint16_t)str;
  2016. str++;
  2017. insert_--;
  2018. if(lookahead_ + insert_ < minMatch)
  2019. break;
  2020. }
  2021. }
  2022. /* If the whole input has less than minMatch bytes, ins_h is garbage,
  2023. but this is not important since only literal bytes will be emitted.
  2024. */
  2025. }
  2026. while(lookahead_ < kMinLookahead && zs.avail_in != 0);
  2027. /* If the kWinInit bytes after the end of the current data have never been
  2028. written, then zero those bytes in order to avoid memory check reports of
  2029. the use of uninitialized (or uninitialised as Julian writes) bytes by
  2030. the longest match routines. Update the high water mark for the next
  2031. time through here. kWinInit is set to maxMatch since the longest match
  2032. routines allow scanning to strstart + maxMatch, ignoring lookahead.
  2033. */
  2034. if(high_water_ < window_size_)
  2035. {
  2036. std::uint32_t curr = strstart_ + (std::uint32_t)(lookahead_);
  2037. std::uint32_t winit;
  2038. if(high_water_ < curr)
  2039. {
  2040. /* Previous high water mark below current data -- zero kWinInit
  2041. bytes or up to end of window, whichever is less.
  2042. */
  2043. winit = window_size_ - curr;
  2044. if(winit > kWinInit)
  2045. winit = kWinInit;
  2046. std::memset(window_ + curr, 0, (unsigned)winit);
  2047. high_water_ = curr + winit;
  2048. }
  2049. else if(high_water_ < (std::uint32_t)curr + kWinInit)
  2050. {
  2051. /* High water mark at or above current data, but below current data
  2052. plus kWinInit -- zero out to current data plus kWinInit, or up
  2053. to end of window, whichever is less.
  2054. */
  2055. winit = (std::uint32_t)curr + kWinInit - high_water_;
  2056. if(winit > window_size_ - high_water_)
  2057. winit = window_size_ - high_water_;
  2058. std::memset(window_ + high_water_, 0, (unsigned)winit);
  2059. high_water_ += winit;
  2060. }
  2061. }
  2062. }
  2063. /* Flush as much pending output as possible. All write() output goes
  2064. through this function so some applications may wish to modify it
  2065. to avoid allocating a large strm->next_out buffer and copying into it.
  2066. (See also read_buf()).
  2067. */
  2068. template<class>
  2069. void
  2070. deflate_stream::
  2071. flush_pending(z_params& zs)
  2072. {
  2073. tr_flush_bits();
  2074. auto len = clamp(pending_, zs.avail_out);
  2075. if(len == 0)
  2076. return;
  2077. std::memcpy(zs.next_out, pending_out_, len);
  2078. zs.next_out =
  2079. static_cast<std::uint8_t*>(zs.next_out) + len;
  2080. pending_out_ += len;
  2081. zs.total_out += len;
  2082. zs.avail_out -= len;
  2083. pending_ -= len;
  2084. if(pending_ == 0)
  2085. pending_out_ = pending_buf_;
  2086. }
  2087. /* Flush the current block, with given end-of-file flag.
  2088. IN assertion: strstart is set to the end of the current match.
  2089. */
  2090. template<class>
  2091. inline
  2092. void
  2093. deflate_stream::
  2094. flush_block(z_params& zs, bool last)
  2095. {
  2096. tr_flush_block(zs,
  2097. (block_start_ >= 0L ?
  2098. (char *)&window_[(unsigned)block_start_] :
  2099. (char *)0),
  2100. (std::uint32_t)((long)strstart_ - block_start_),
  2101. last);
  2102. block_start_ = strstart_;
  2103. flush_pending(zs);
  2104. }
  2105. /* Read a new buffer from the current input stream, update the adler32
  2106. and total number of bytes read. All write() input goes through
  2107. this function so some applications may wish to modify it to avoid
  2108. allocating a large strm->next_in buffer and copying from it.
  2109. (See also flush_pending()).
  2110. */
  2111. template<class>
  2112. int
  2113. deflate_stream::
  2114. read_buf(z_params& zs, Byte *buf, unsigned size)
  2115. {
  2116. auto len = clamp(zs.avail_in, size);
  2117. if(len == 0)
  2118. return 0;
  2119. zs.avail_in -= len;
  2120. std::memcpy(buf, zs.next_in, len);
  2121. zs.next_in = static_cast<
  2122. std::uint8_t const*>(zs.next_in) + len;
  2123. zs.total_in += len;
  2124. return (int)len;
  2125. }
  2126. /* Set match_start to the longest match starting at the given string and
  2127. return its length. Matches shorter or equal to prev_length are discarded,
  2128. in which case the result is equal to prev_length and match_start is
  2129. garbage.
  2130. IN assertions: cur_match is the head of the hash chain for the current
  2131. string (strstart) and its distance is <= max_dist, and prev_length >= 1
  2132. OUT assertion: the match length is not greater than s->lookahead_.
  2133. For 80x86 and 680x0, an optimized version will be provided in match.asm or
  2134. match.S. The code will be functionally equivalent.
  2135. */
  2136. template<class>
  2137. uInt
  2138. deflate_stream::
  2139. longest_match(IPos cur_match)
  2140. {
  2141. unsigned chain_length = max_chain_length_;/* max hash chain length */
  2142. Byte *scan = window_ + strstart_; /* current string */
  2143. Byte *match; /* matched string */
  2144. int len; /* length of current match */
  2145. int best_len = prev_length_; /* best match length so far */
  2146. int nice_match = nice_match_; /* stop if match long enough */
  2147. IPos limit = strstart_ > (IPos)max_dist() ?
  2148. strstart_ - (IPos)max_dist() : 0;
  2149. /* Stop when cur_match becomes <= limit. To simplify the code,
  2150. * we prevent matches with the string of window index 0.
  2151. */
  2152. std::uint16_t *prev = prev_;
  2153. uInt wmask = w_mask_;
  2154. Byte *strend = window_ + strstart_ + maxMatch;
  2155. Byte scan_end1 = scan[best_len-1];
  2156. Byte scan_end = scan[best_len];
  2157. /* The code is optimized for HASH_BITS >= 8 and maxMatch-2 multiple of 16.
  2158. * It is easy to get rid of this optimization if necessary.
  2159. */
  2160. BOOST_ASSERT(hash_bits_ >= 8 && maxMatch == 258);
  2161. /* Do not waste too much time if we already have a good match: */
  2162. if(prev_length_ >= good_match_) {
  2163. chain_length >>= 2;
  2164. }
  2165. /* Do not look for matches beyond the end of the input. This is necessary
  2166. * to make deflate deterministic.
  2167. */
  2168. if((uInt)nice_match > lookahead_)
  2169. nice_match = lookahead_;
  2170. BOOST_ASSERT((std::uint32_t)strstart_ <= window_size_-kMinLookahead);
  2171. do {
  2172. BOOST_ASSERT(cur_match < strstart_);
  2173. match = window_ + cur_match;
  2174. /* Skip to next match if the match length cannot increase
  2175. * or if the match length is less than 2. Note that the checks below
  2176. * for insufficient lookahead only occur occasionally for performance
  2177. * reasons. Therefore uninitialized memory will be accessed, and
  2178. * conditional jumps will be made that depend on those values.
  2179. * However the length of the match is limited to the lookahead, so
  2180. * the output of deflate is not affected by the uninitialized values.
  2181. */
  2182. if( match[best_len] != scan_end ||
  2183. match[best_len-1] != scan_end1 ||
  2184. *match != *scan ||
  2185. *++match != scan[1])
  2186. continue;
  2187. /* The check at best_len-1 can be removed because it will be made
  2188. * again later. (This heuristic is not always a win.)
  2189. * It is not necessary to compare scan[2] and match[2] since they
  2190. * are always equal when the other bytes match, given that
  2191. * the hash keys are equal and that HASH_BITS >= 8.
  2192. */
  2193. scan += 2, match++;
  2194. BOOST_ASSERT(*scan == *match);
  2195. /* We check for insufficient lookahead only every 8th comparison;
  2196. * the 256th check will be made at strstart+258.
  2197. */
  2198. do
  2199. {
  2200. }
  2201. while( *++scan == *++match && *++scan == *++match &&
  2202. *++scan == *++match && *++scan == *++match &&
  2203. *++scan == *++match && *++scan == *++match &&
  2204. *++scan == *++match && *++scan == *++match &&
  2205. scan < strend);
  2206. BOOST_ASSERT(scan <= window_+(unsigned)(window_size_-1));
  2207. len = maxMatch - (int)(strend - scan);
  2208. scan = strend - maxMatch;
  2209. if(len > best_len) {
  2210. match_start_ = cur_match;
  2211. best_len = len;
  2212. if(len >= nice_match) break;
  2213. scan_end1 = scan[best_len-1];
  2214. scan_end = scan[best_len];
  2215. }
  2216. }
  2217. while((cur_match = prev[cur_match & wmask]) > limit
  2218. && --chain_length != 0);
  2219. if((uInt)best_len <= lookahead_)
  2220. return (uInt)best_len;
  2221. return lookahead_;
  2222. }
  2223. //------------------------------------------------------------------------------
  2224. /* Copy without compression as much as possible from the input stream, return
  2225. the current block state.
  2226. This function does not insert new strings in the dictionary since
  2227. uncompressible data is probably not useful. This function is used
  2228. only for the level=0 compression option.
  2229. NOTE: this function should be optimized to avoid extra copying from
  2230. window to pending_buf.
  2231. */
  2232. template<class>
  2233. inline
  2234. auto
  2235. deflate_stream::
  2236. f_stored(z_params& zs, Flush flush) ->
  2237. block_state
  2238. {
  2239. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  2240. * to pending_buf_size, and each stored block has a 5 byte header:
  2241. */
  2242. std::uint32_t max_block_size = 0xffff;
  2243. std::uint32_t max_start;
  2244. if(max_block_size > pending_buf_size_ - 5) {
  2245. max_block_size = pending_buf_size_ - 5;
  2246. }
  2247. /* Copy as much as possible from input to output: */
  2248. for(;;) {
  2249. /* Fill the window as much as possible: */
  2250. if(lookahead_ <= 1) {
  2251. BOOST_ASSERT(strstart_ < w_size_+max_dist() ||
  2252. block_start_ >= (long)w_size_);
  2253. fill_window(zs);
  2254. if(lookahead_ == 0 && flush == Flush::none)
  2255. return need_more;
  2256. if(lookahead_ == 0) break; /* flush the current block */
  2257. }
  2258. BOOST_ASSERT(block_start_ >= 0L);
  2259. strstart_ += lookahead_;
  2260. lookahead_ = 0;
  2261. /* Emit a stored block if pending_buf will be full: */
  2262. max_start = block_start_ + max_block_size;
  2263. if(strstart_ == 0 || (std::uint32_t)strstart_ >= max_start) {
  2264. /* strstart == 0 is possible when wraparound on 16-bit machine */
  2265. lookahead_ = (uInt)(strstart_ - max_start);
  2266. strstart_ = (uInt)max_start;
  2267. flush_block(zs, false);
  2268. if(zs.avail_out == 0)
  2269. return need_more;
  2270. }
  2271. /* Flush if we may have to slide, otherwise block_start may become
  2272. * negative and the data will be gone:
  2273. */
  2274. if(strstart_ - (uInt)block_start_ >= max_dist()) {
  2275. flush_block(zs, false);
  2276. if(zs.avail_out == 0)
  2277. return need_more;
  2278. }
  2279. }
  2280. insert_ = 0;
  2281. if(flush == Flush::finish)
  2282. {
  2283. flush_block(zs, true);
  2284. if(zs.avail_out == 0)
  2285. return finish_started;
  2286. return finish_done;
  2287. }
  2288. if((long)strstart_ > block_start_)
  2289. {
  2290. flush_block(zs, false);
  2291. if(zs.avail_out == 0)
  2292. return need_more;
  2293. }
  2294. return block_done;
  2295. }
  2296. /* Compress as much as possible from the input stream, return the current
  2297. block state.
  2298. This function does not perform lazy evaluation of matches and inserts
  2299. new strings in the dictionary only for unmatched strings or for short
  2300. matches. It is used only for the fast compression options.
  2301. */
  2302. template<class>
  2303. inline
  2304. auto
  2305. deflate_stream::
  2306. f_fast(z_params& zs, Flush flush) ->
  2307. block_state
  2308. {
  2309. IPos hash_head; /* head of the hash chain */
  2310. bool bflush; /* set if current block must be flushed */
  2311. for(;;)
  2312. {
  2313. /* Make sure that we always have enough lookahead, except
  2314. * at the end of the input file. We need maxMatch bytes
  2315. * for the next match, plus minMatch bytes to insert the
  2316. * string following the next match.
  2317. */
  2318. if(lookahead_ < kMinLookahead)
  2319. {
  2320. fill_window(zs);
  2321. if(lookahead_ < kMinLookahead && flush == Flush::none)
  2322. return need_more;
  2323. if(lookahead_ == 0)
  2324. break; /* flush the current block */
  2325. }
  2326. /* Insert the string window[strstart .. strstart+2] in the
  2327. * dictionary, and set hash_head to the head of the hash chain:
  2328. */
  2329. hash_head = 0;
  2330. if(lookahead_ >= minMatch) {
  2331. insert_string(hash_head);
  2332. }
  2333. /* Find the longest match, discarding those <= prev_length.
  2334. * At this point we have always match_length < minMatch
  2335. */
  2336. if(hash_head != 0 && strstart_ - hash_head <= max_dist()) {
  2337. /* To simplify the code, we prevent matches with the string
  2338. * of window index 0 (in particular we have to avoid a match
  2339. * of the string with itself at the start of the input file).
  2340. */
  2341. match_length_ = longest_match (hash_head);
  2342. /* longest_match() sets match_start */
  2343. }
  2344. if(match_length_ >= minMatch)
  2345. {
  2346. tr_tally_dist(static_cast<std::uint16_t>(strstart_ - match_start_),
  2347. static_cast<std::uint8_t>(match_length_ - minMatch), bflush);
  2348. lookahead_ -= match_length_;
  2349. /* Insert new strings in the hash table only if the match length
  2350. * is not too large. This saves time but degrades compression.
  2351. */
  2352. if(match_length_ <= max_lazy_match_ &&
  2353. lookahead_ >= minMatch) {
  2354. match_length_--; /* string at strstart already in table */
  2355. do
  2356. {
  2357. strstart_++;
  2358. insert_string(hash_head);
  2359. /* strstart never exceeds WSIZE-maxMatch, so there are
  2360. * always minMatch bytes ahead.
  2361. */
  2362. }
  2363. while(--match_length_ != 0);
  2364. strstart_++;
  2365. }
  2366. else
  2367. {
  2368. strstart_ += match_length_;
  2369. match_length_ = 0;
  2370. ins_h_ = window_[strstart_];
  2371. update_hash(ins_h_, window_[strstart_+1]);
  2372. /* If lookahead < minMatch, ins_h is garbage, but it does not
  2373. * matter since it will be recomputed at next deflate call.
  2374. */
  2375. }
  2376. }
  2377. else
  2378. {
  2379. /* No match, output a literal byte */
  2380. tr_tally_lit(window_[strstart_], bflush);
  2381. lookahead_--;
  2382. strstart_++;
  2383. }
  2384. if(bflush)
  2385. {
  2386. flush_block(zs, false);
  2387. if(zs.avail_out == 0)
  2388. return need_more;
  2389. }
  2390. }
  2391. insert_ = strstart_ < minMatch-1 ? strstart_ : minMatch-1;
  2392. if(flush == Flush::finish)
  2393. {
  2394. flush_block(zs, true);
  2395. if(zs.avail_out == 0)
  2396. return finish_started;
  2397. return finish_done;
  2398. }
  2399. if(last_lit_)
  2400. {
  2401. flush_block(zs, false);
  2402. if(zs.avail_out == 0)
  2403. return need_more;
  2404. }
  2405. return block_done;
  2406. }
  2407. /* Same as above, but achieves better compression. We use a lazy
  2408. evaluation for matches: a match is finally adopted only if there is
  2409. no better match at the next window position.
  2410. */
  2411. template<class>
  2412. inline
  2413. auto
  2414. deflate_stream::
  2415. f_slow(z_params& zs, Flush flush) ->
  2416. block_state
  2417. {
  2418. IPos hash_head; /* head of hash chain */
  2419. bool bflush; /* set if current block must be flushed */
  2420. /* Process the input block. */
  2421. for(;;)
  2422. {
  2423. /* Make sure that we always have enough lookahead, except
  2424. * at the end of the input file. We need maxMatch bytes
  2425. * for the next match, plus minMatch bytes to insert the
  2426. * string following the next match.
  2427. */
  2428. if(lookahead_ < kMinLookahead)
  2429. {
  2430. fill_window(zs);
  2431. if(lookahead_ < kMinLookahead && flush == Flush::none)
  2432. return need_more;
  2433. if(lookahead_ == 0)
  2434. break; /* flush the current block */
  2435. }
  2436. /* Insert the string window[strstart .. strstart+2] in the
  2437. * dictionary, and set hash_head to the head of the hash chain:
  2438. */
  2439. hash_head = 0;
  2440. if(lookahead_ >= minMatch)
  2441. insert_string(hash_head);
  2442. /* Find the longest match, discarding those <= prev_length.
  2443. */
  2444. prev_length_ = match_length_, prev_match_ = match_start_;
  2445. match_length_ = minMatch-1;
  2446. if(hash_head != 0 && prev_length_ < max_lazy_match_ &&
  2447. strstart_ - hash_head <= max_dist())
  2448. {
  2449. /* To simplify the code, we prevent matches with the string
  2450. * of window index 0 (in particular we have to avoid a match
  2451. * of the string with itself at the start of the input file).
  2452. */
  2453. match_length_ = longest_match(hash_head);
  2454. /* longest_match() sets match_start */
  2455. if(match_length_ <= 5 && (strategy_ == Strategy::filtered
  2456. || (match_length_ == minMatch &&
  2457. strstart_ - match_start_ > kTooFar)
  2458. ))
  2459. {
  2460. /* If prev_match is also minMatch, match_start is garbage
  2461. * but we will ignore the current match anyway.
  2462. */
  2463. match_length_ = minMatch-1;
  2464. }
  2465. }
  2466. /* If there was a match at the previous step and the current
  2467. * match is not better, output the previous match:
  2468. */
  2469. if(prev_length_ >= minMatch && match_length_ <= prev_length_)
  2470. {
  2471. /* Do not insert strings in hash table beyond this. */
  2472. uInt max_insert = strstart_ + lookahead_ - minMatch;
  2473. tr_tally_dist(
  2474. static_cast<std::uint16_t>(strstart_ -1 - prev_match_),
  2475. static_cast<std::uint8_t>(prev_length_ - minMatch), bflush);
  2476. /* Insert in hash table all strings up to the end of the match.
  2477. * strstart-1 and strstart are already inserted. If there is not
  2478. * enough lookahead, the last two strings are not inserted in
  2479. * the hash table.
  2480. */
  2481. lookahead_ -= prev_length_-1;
  2482. prev_length_ -= 2;
  2483. do {
  2484. if(++strstart_ <= max_insert)
  2485. insert_string(hash_head);
  2486. }
  2487. while(--prev_length_ != 0);
  2488. match_available_ = 0;
  2489. match_length_ = minMatch-1;
  2490. strstart_++;
  2491. if(bflush)
  2492. {
  2493. flush_block(zs, false);
  2494. if(zs.avail_out == 0)
  2495. return need_more;
  2496. }
  2497. }
  2498. else if(match_available_)
  2499. {
  2500. /* If there was no match at the previous position, output a
  2501. * single literal. If there was a match but the current match
  2502. * is longer, truncate the previous match to a single literal.
  2503. */
  2504. tr_tally_lit(window_[strstart_-1], bflush);
  2505. if(bflush)
  2506. flush_block(zs, false);
  2507. strstart_++;
  2508. lookahead_--;
  2509. if(zs.avail_out == 0)
  2510. return need_more;
  2511. }
  2512. else
  2513. {
  2514. /* There is no previous match to compare with, wait for
  2515. * the next step to decide.
  2516. */
  2517. match_available_ = 1;
  2518. strstart_++;
  2519. lookahead_--;
  2520. }
  2521. }
  2522. BOOST_ASSERT(flush != Flush::none);
  2523. if(match_available_)
  2524. {
  2525. tr_tally_lit(window_[strstart_-1], bflush);
  2526. match_available_ = 0;
  2527. }
  2528. insert_ = strstart_ < minMatch-1 ? strstart_ : minMatch-1;
  2529. if(flush == Flush::finish)
  2530. {
  2531. flush_block(zs, true);
  2532. if(zs.avail_out == 0)
  2533. return finish_started;
  2534. return finish_done;
  2535. }
  2536. if(last_lit_)
  2537. {
  2538. flush_block(zs, false);
  2539. if(zs.avail_out == 0)
  2540. return need_more;
  2541. }
  2542. return block_done;
  2543. }
  2544. /* For Strategy::rle, simply look for runs of bytes, generate matches only of distance
  2545. one. Do not maintain a hash table. (It will be regenerated if this run of
  2546. deflate switches away from Strategy::rle.)
  2547. */
  2548. template<class>
  2549. inline
  2550. auto
  2551. deflate_stream::
  2552. f_rle(z_params& zs, Flush flush) ->
  2553. block_state
  2554. {
  2555. bool bflush; // set if current block must be flushed
  2556. uInt prev; // byte at distance one to match
  2557. Byte *scan, *strend; // scan goes up to strend for length of run
  2558. for(;;)
  2559. {
  2560. /* Make sure that we always have enough lookahead, except
  2561. * at the end of the input file. We need maxMatch bytes
  2562. * for the longest run, plus one for the unrolled loop.
  2563. */
  2564. if(lookahead_ <= maxMatch) {
  2565. fill_window(zs);
  2566. if(lookahead_ <= maxMatch && flush == Flush::none) {
  2567. return need_more;
  2568. }
  2569. if(lookahead_ == 0) break; /* flush the current block */
  2570. }
  2571. /* See how many times the previous byte repeats */
  2572. match_length_ = 0;
  2573. if(lookahead_ >= minMatch && strstart_ > 0) {
  2574. scan = window_ + strstart_ - 1;
  2575. prev = *scan;
  2576. if(prev == *++scan && prev == *++scan && prev == *++scan) {
  2577. strend = window_ + strstart_ + maxMatch;
  2578. do {
  2579. } while(prev == *++scan && prev == *++scan &&
  2580. prev == *++scan && prev == *++scan &&
  2581. prev == *++scan && prev == *++scan &&
  2582. prev == *++scan && prev == *++scan &&
  2583. scan < strend);
  2584. match_length_ = maxMatch - (int)(strend - scan);
  2585. if(match_length_ > lookahead_)
  2586. match_length_ = lookahead_;
  2587. }
  2588. BOOST_ASSERT(scan <= window_+(uInt)(window_size_-1));
  2589. }
  2590. /* Emit match if have run of minMatch or longer, else emit literal */
  2591. if(match_length_ >= minMatch) {
  2592. tr_tally_dist(std::uint16_t{1},
  2593. static_cast<std::uint8_t>(match_length_ - minMatch),
  2594. bflush);
  2595. lookahead_ -= match_length_;
  2596. strstart_ += match_length_;
  2597. match_length_ = 0;
  2598. } else {
  2599. /* No match, output a literal byte */
  2600. tr_tally_lit(window_[strstart_], bflush);
  2601. lookahead_--;
  2602. strstart_++;
  2603. }
  2604. if(bflush)
  2605. {
  2606. flush_block(zs, false);
  2607. if(zs.avail_out == 0)
  2608. return need_more;
  2609. }
  2610. }
  2611. insert_ = 0;
  2612. if(flush == Flush::finish)
  2613. {
  2614. flush_block(zs, true);
  2615. if(zs.avail_out == 0)
  2616. return finish_started;
  2617. return finish_done;
  2618. }
  2619. if(last_lit_)
  2620. {
  2621. flush_block(zs, false);
  2622. if(zs.avail_out == 0)
  2623. return need_more;
  2624. }
  2625. return block_done;
  2626. }
  2627. /* ===========================================================================
  2628. * For Strategy::huffman, do not look for matches. Do not maintain a hash table.
  2629. * (It will be regenerated if this run of deflate switches away from Huffman.)
  2630. */
  2631. template<class>
  2632. inline
  2633. auto
  2634. deflate_stream::
  2635. f_huff(z_params& zs, Flush flush) ->
  2636. block_state
  2637. {
  2638. bool bflush; // set if current block must be flushed
  2639. for(;;)
  2640. {
  2641. // Make sure that we have a literal to write.
  2642. if(lookahead_ == 0)
  2643. {
  2644. fill_window(zs);
  2645. if(lookahead_ == 0)
  2646. {
  2647. if(flush == Flush::none)
  2648. return need_more;
  2649. break; // flush the current block
  2650. }
  2651. }
  2652. // Output a literal byte
  2653. match_length_ = 0;
  2654. tr_tally_lit(window_[strstart_], bflush);
  2655. lookahead_--;
  2656. strstart_++;
  2657. if(bflush)
  2658. {
  2659. flush_block(zs, false);
  2660. if(zs.avail_out == 0)
  2661. return need_more;
  2662. }
  2663. }
  2664. insert_ = 0;
  2665. if(flush == Flush::finish)
  2666. {
  2667. flush_block(zs, true);
  2668. if(zs.avail_out == 0)
  2669. return finish_started;
  2670. return finish_done;
  2671. }
  2672. if(last_lit_)
  2673. {
  2674. flush_block(zs, false);
  2675. if(zs.avail_out == 0)
  2676. return need_more;
  2677. }
  2678. return block_done;
  2679. }
  2680. } // detail
  2681. } // zlib
  2682. } // beast
  2683. } // boost
  2684. #endif