pako_deflate.js 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126
  1. /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pako = {}));
  6. })(this, (function (exports) { 'use strict';
  7. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9. //
  10. // This software is provided 'as-is', without any express or implied
  11. // warranty. In no event will the authors be held liable for any damages
  12. // arising from the use of this software.
  13. //
  14. // Permission is granted to anyone to use this software for any purpose,
  15. // including commercial applications, and to alter it and redistribute it
  16. // freely, subject to the following restrictions:
  17. //
  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. /* eslint-disable space-unary-ops */
  26. /* Public constants ==========================================================*/
  27. /* ===========================================================================*/
  28. //const Z_FILTERED = 1;
  29. //const Z_HUFFMAN_ONLY = 2;
  30. //const Z_RLE = 3;
  31. const Z_FIXED$1 = 4;
  32. //const Z_DEFAULT_STRATEGY = 0;
  33. /* Possible values of the data_type field (though see inflate()) */
  34. const Z_BINARY = 0;
  35. const Z_TEXT = 1;
  36. //const Z_ASCII = 1; // = Z_TEXT
  37. const Z_UNKNOWN$1 = 2;
  38. /*============================================================================*/
  39. function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  40. // From zutil.h
  41. const STORED_BLOCK = 0;
  42. const STATIC_TREES = 1;
  43. const DYN_TREES = 2;
  44. /* The three kinds of block type */
  45. const MIN_MATCH$1 = 3;
  46. const MAX_MATCH$1 = 258;
  47. /* The minimum and maximum match lengths */
  48. // From deflate.h
  49. /* ===========================================================================
  50. * Internal compression state.
  51. */
  52. const LENGTH_CODES$1 = 29;
  53. /* number of length codes, not counting the special END_BLOCK code */
  54. const LITERALS$1 = 256;
  55. /* number of literal bytes 0..255 */
  56. const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
  57. /* number of Literal or Length codes, including the END_BLOCK code */
  58. const D_CODES$1 = 30;
  59. /* number of distance codes */
  60. const BL_CODES$1 = 19;
  61. /* number of codes used to transfer the bit lengths */
  62. const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
  63. /* maximum heap size */
  64. const MAX_BITS$1 = 15;
  65. /* All codes must not exceed MAX_BITS bits */
  66. const Buf_size = 16;
  67. /* size of bit buffer in bi_buf */
  68. /* ===========================================================================
  69. * Constants
  70. */
  71. const MAX_BL_BITS = 7;
  72. /* Bit length codes must not exceed MAX_BL_BITS bits */
  73. const END_BLOCK = 256;
  74. /* end of block literal code */
  75. const REP_3_6 = 16;
  76. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  77. const REPZ_3_10 = 17;
  78. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  79. const REPZ_11_138 = 18;
  80. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81. /* eslint-disable comma-spacing,array-bracket-spacing */
  82. const extra_lbits = /* extra bits for each length code */
  83. new Uint8Array([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]);
  84. const extra_dbits = /* extra bits for each distance code */
  85. new Uint8Array([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]);
  86. const extra_blbits = /* extra bits for each bit length code */
  87. new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);
  88. const bl_order =
  89. new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);
  90. /* eslint-enable comma-spacing,array-bracket-spacing */
  91. /* The lengths of the bit length codes are sent in order of decreasing
  92. * probability, to avoid transmitting the lengths for unused bit length codes.
  93. */
  94. /* ===========================================================================
  95. * Local data. These are initialized only once.
  96. */
  97. // We pre-fill arrays with 0 to avoid uninitialized gaps
  98. const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  99. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  100. const static_ltree = new Array((L_CODES$1 + 2) * 2);
  101. zero$1(static_ltree);
  102. /* The static literal tree. Since the bit lengths are imposed, there is no
  103. * need for the L_CODES extra codes used during heap construction. However
  104. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  105. * below).
  106. */
  107. const static_dtree = new Array(D_CODES$1 * 2);
  108. zero$1(static_dtree);
  109. /* The static distance tree. (Actually a trivial tree since all codes use
  110. * 5 bits.)
  111. */
  112. const _dist_code = new Array(DIST_CODE_LEN);
  113. zero$1(_dist_code);
  114. /* Distance codes. The first 256 values correspond to the distances
  115. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  116. * the 15 bit distances.
  117. */
  118. const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
  119. zero$1(_length_code);
  120. /* length code for each normalized match length (0 == MIN_MATCH) */
  121. const base_length = new Array(LENGTH_CODES$1);
  122. zero$1(base_length);
  123. /* First normalized length for each code (0 = MIN_MATCH) */
  124. const base_dist = new Array(D_CODES$1);
  125. zero$1(base_dist);
  126. /* First normalized distance for each code (0 = distance of 1) */
  127. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  128. this.static_tree = static_tree; /* static tree or NULL */
  129. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  130. this.extra_base = extra_base; /* base index for extra_bits */
  131. this.elems = elems; /* max number of elements in the tree */
  132. this.max_length = max_length; /* max bit length for the codes */
  133. // show if `static_tree` has data or dummy - needed for monomorphic objects
  134. this.has_stree = static_tree && static_tree.length;
  135. }
  136. let static_l_desc;
  137. let static_d_desc;
  138. let static_bl_desc;
  139. function TreeDesc(dyn_tree, stat_desc) {
  140. this.dyn_tree = dyn_tree; /* the dynamic tree */
  141. this.max_code = 0; /* largest code with non zero frequency */
  142. this.stat_desc = stat_desc; /* the corresponding static tree */
  143. }
  144. const d_code = (dist) => {
  145. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  146. };
  147. /* ===========================================================================
  148. * Output a short LSB first on the stream.
  149. * IN assertion: there is enough room in pendingBuf.
  150. */
  151. const put_short = (s, w) => {
  152. // put_byte(s, (uch)((w) & 0xff));
  153. // put_byte(s, (uch)((ush)(w) >> 8));
  154. s.pending_buf[s.pending++] = (w) & 0xff;
  155. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  156. };
  157. /* ===========================================================================
  158. * Send a value on a given number of bits.
  159. * IN assertion: length <= 16 and value fits in length bits.
  160. */
  161. const send_bits = (s, value, length) => {
  162. if (s.bi_valid > (Buf_size - length)) {
  163. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  164. put_short(s, s.bi_buf);
  165. s.bi_buf = value >> (Buf_size - s.bi_valid);
  166. s.bi_valid += length - Buf_size;
  167. } else {
  168. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  169. s.bi_valid += length;
  170. }
  171. };
  172. const send_code = (s, c, tree) => {
  173. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  174. };
  175. /* ===========================================================================
  176. * Reverse the first len bits of a code, using straightforward code (a faster
  177. * method would use a table)
  178. * IN assertion: 1 <= len <= 15
  179. */
  180. const bi_reverse = (code, len) => {
  181. let res = 0;
  182. do {
  183. res |= code & 1;
  184. code >>>= 1;
  185. res <<= 1;
  186. } while (--len > 0);
  187. return res >>> 1;
  188. };
  189. /* ===========================================================================
  190. * Flush the bit buffer, keeping at most 7 bits in it.
  191. */
  192. const bi_flush = (s) => {
  193. if (s.bi_valid === 16) {
  194. put_short(s, s.bi_buf);
  195. s.bi_buf = 0;
  196. s.bi_valid = 0;
  197. } else if (s.bi_valid >= 8) {
  198. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  199. s.bi_buf >>= 8;
  200. s.bi_valid -= 8;
  201. }
  202. };
  203. /* ===========================================================================
  204. * Compute the optimal bit lengths for a tree and update the total bit length
  205. * for the current block.
  206. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  207. * above are the tree nodes sorted by increasing frequency.
  208. * OUT assertions: the field len is set to the optimal bit length, the
  209. * array bl_count contains the frequencies for each bit length.
  210. * The length opt_len is updated; static_len is also updated if stree is
  211. * not null.
  212. */
  213. const gen_bitlen = (s, desc) => {
  214. // deflate_state *s;
  215. // tree_desc *desc; /* the tree descriptor */
  216. const tree = desc.dyn_tree;
  217. const max_code = desc.max_code;
  218. const stree = desc.stat_desc.static_tree;
  219. const has_stree = desc.stat_desc.has_stree;
  220. const extra = desc.stat_desc.extra_bits;
  221. const base = desc.stat_desc.extra_base;
  222. const max_length = desc.stat_desc.max_length;
  223. let h; /* heap index */
  224. let n, m; /* iterate over the tree elements */
  225. let bits; /* bit length */
  226. let xbits; /* extra bits */
  227. let f; /* frequency */
  228. let overflow = 0; /* number of elements with bit length too large */
  229. for (bits = 0; bits <= MAX_BITS$1; bits++) {
  230. s.bl_count[bits] = 0;
  231. }
  232. /* In a first pass, compute the optimal bit lengths (which may
  233. * overflow in the case of the bit length tree).
  234. */
  235. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  236. for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {
  237. n = s.heap[h];
  238. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  239. if (bits > max_length) {
  240. bits = max_length;
  241. overflow++;
  242. }
  243. tree[n * 2 + 1]/*.Len*/ = bits;
  244. /* We overwrite tree[n].Dad which is no longer needed */
  245. if (n > max_code) { continue; } /* not a leaf node */
  246. s.bl_count[bits]++;
  247. xbits = 0;
  248. if (n >= base) {
  249. xbits = extra[n - base];
  250. }
  251. f = tree[n * 2]/*.Freq*/;
  252. s.opt_len += f * (bits + xbits);
  253. if (has_stree) {
  254. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  255. }
  256. }
  257. if (overflow === 0) { return; }
  258. // Tracev((stderr,"\nbit length overflow\n"));
  259. /* This happens for example on obj2 and pic of the Calgary corpus */
  260. /* Find the first bit length which could increase: */
  261. do {
  262. bits = max_length - 1;
  263. while (s.bl_count[bits] === 0) { bits--; }
  264. s.bl_count[bits]--; /* move one leaf down the tree */
  265. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  266. s.bl_count[max_length]--;
  267. /* The brother of the overflow item also moves one step up,
  268. * but this does not affect bl_count[max_length]
  269. */
  270. overflow -= 2;
  271. } while (overflow > 0);
  272. /* Now recompute all bit lengths, scanning in increasing frequency.
  273. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  274. * lengths instead of fixing only the wrong ones. This idea is taken
  275. * from 'ar' written by Haruhiko Okumura.)
  276. */
  277. for (bits = max_length; bits !== 0; bits--) {
  278. n = s.bl_count[bits];
  279. while (n !== 0) {
  280. m = s.heap[--h];
  281. if (m > max_code) { continue; }
  282. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  283. // Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  284. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  285. tree[m * 2 + 1]/*.Len*/ = bits;
  286. }
  287. n--;
  288. }
  289. }
  290. };
  291. /* ===========================================================================
  292. * Generate the codes for a given tree and bit counts (which need not be
  293. * optimal).
  294. * IN assertion: the array bl_count contains the bit length statistics for
  295. * the given tree and the field len is set for all tree elements.
  296. * OUT assertion: the field code is set for all tree elements of non
  297. * zero code length.
  298. */
  299. const gen_codes = (tree, max_code, bl_count) => {
  300. // ct_data *tree; /* the tree to decorate */
  301. // int max_code; /* largest code with non zero frequency */
  302. // ushf *bl_count; /* number of codes at each bit length */
  303. const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */
  304. let code = 0; /* running code value */
  305. let bits; /* bit index */
  306. let n; /* code index */
  307. /* The distribution counts are first used to generate the code values
  308. * without bit reversal.
  309. */
  310. for (bits = 1; bits <= MAX_BITS$1; bits++) {
  311. code = (code + bl_count[bits - 1]) << 1;
  312. next_code[bits] = code;
  313. }
  314. /* Check that the bit counts in bl_count are consistent. The last code
  315. * must be all ones.
  316. */
  317. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  318. // "inconsistent bit counts");
  319. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  320. for (n = 0; n <= max_code; n++) {
  321. let len = tree[n * 2 + 1]/*.Len*/;
  322. if (len === 0) { continue; }
  323. /* Now reverse the bits */
  324. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  325. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  326. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  327. }
  328. };
  329. /* ===========================================================================
  330. * Initialize the various 'constant' tables.
  331. */
  332. const tr_static_init = () => {
  333. let n; /* iterates over tree elements */
  334. let bits; /* bit counter */
  335. let length; /* length value */
  336. let code; /* code value */
  337. let dist; /* distance index */
  338. const bl_count = new Array(MAX_BITS$1 + 1);
  339. /* number of codes at each bit length for an optimal tree */
  340. // do check in _tr_init()
  341. //if (static_init_done) return;
  342. /* For some embedded targets, global variables are not initialized: */
  343. /*#ifdef NO_INIT_GLOBAL_POINTERS
  344. static_l_desc.static_tree = static_ltree;
  345. static_l_desc.extra_bits = extra_lbits;
  346. static_d_desc.static_tree = static_dtree;
  347. static_d_desc.extra_bits = extra_dbits;
  348. static_bl_desc.extra_bits = extra_blbits;
  349. #endif*/
  350. /* Initialize the mapping length (0..255) -> length code (0..28) */
  351. length = 0;
  352. for (code = 0; code < LENGTH_CODES$1 - 1; code++) {
  353. base_length[code] = length;
  354. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  355. _length_code[length++] = code;
  356. }
  357. }
  358. //Assert (length == 256, "tr_static_init: length != 256");
  359. /* Note that the length 255 (match length 258) can be represented
  360. * in two different ways: code 284 + 5 bits or code 285, so we
  361. * overwrite length_code[255] to use the best encoding:
  362. */
  363. _length_code[length - 1] = code;
  364. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  365. dist = 0;
  366. for (code = 0; code < 16; code++) {
  367. base_dist[code] = dist;
  368. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  369. _dist_code[dist++] = code;
  370. }
  371. }
  372. //Assert (dist == 256, "tr_static_init: dist != 256");
  373. dist >>= 7; /* from now on, all distances are divided by 128 */
  374. for (; code < D_CODES$1; code++) {
  375. base_dist[code] = dist << 7;
  376. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  377. _dist_code[256 + dist++] = code;
  378. }
  379. }
  380. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  381. /* Construct the codes of the static literal tree */
  382. for (bits = 0; bits <= MAX_BITS$1; bits++) {
  383. bl_count[bits] = 0;
  384. }
  385. n = 0;
  386. while (n <= 143) {
  387. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  388. n++;
  389. bl_count[8]++;
  390. }
  391. while (n <= 255) {
  392. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  393. n++;
  394. bl_count[9]++;
  395. }
  396. while (n <= 279) {
  397. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  398. n++;
  399. bl_count[7]++;
  400. }
  401. while (n <= 287) {
  402. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  403. n++;
  404. bl_count[8]++;
  405. }
  406. /* Codes 286 and 287 do not exist, but we must include them in the
  407. * tree construction to get a canonical Huffman tree (longest code
  408. * all ones)
  409. */
  410. gen_codes(static_ltree, L_CODES$1 + 1, bl_count);
  411. /* The static distance tree is trivial: */
  412. for (n = 0; n < D_CODES$1; n++) {
  413. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  414. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  415. }
  416. // Now data ready and we can init static trees
  417. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);
  418. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);
  419. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);
  420. //static_init_done = true;
  421. };
  422. /* ===========================================================================
  423. * Initialize a new block.
  424. */
  425. const init_block = (s) => {
  426. let n; /* iterates over tree elements */
  427. /* Initialize the trees. */
  428. for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  429. for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  430. for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  431. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  432. s.opt_len = s.static_len = 0;
  433. s.sym_next = s.matches = 0;
  434. };
  435. /* ===========================================================================
  436. * Flush the bit buffer and align the output on a byte boundary
  437. */
  438. const bi_windup = (s) =>
  439. {
  440. if (s.bi_valid > 8) {
  441. put_short(s, s.bi_buf);
  442. } else if (s.bi_valid > 0) {
  443. //put_byte(s, (Byte)s->bi_buf);
  444. s.pending_buf[s.pending++] = s.bi_buf;
  445. }
  446. s.bi_buf = 0;
  447. s.bi_valid = 0;
  448. };
  449. /* ===========================================================================
  450. * Compares to subtrees, using the tree depth as tie breaker when
  451. * the subtrees have equal frequency. This minimizes the worst case length.
  452. */
  453. const smaller = (tree, n, m, depth) => {
  454. const _n2 = n * 2;
  455. const _m2 = m * 2;
  456. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  457. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  458. };
  459. /* ===========================================================================
  460. * Restore the heap property by moving down the tree starting at node k,
  461. * exchanging a node with the smallest of its two sons if necessary, stopping
  462. * when the heap property is re-established (each father smaller than its
  463. * two sons).
  464. */
  465. const pqdownheap = (s, tree, k) => {
  466. // deflate_state *s;
  467. // ct_data *tree; /* the tree to restore */
  468. // int k; /* node to move down */
  469. const v = s.heap[k];
  470. let j = k << 1; /* left son of k */
  471. while (j <= s.heap_len) {
  472. /* Set j to the smallest of the two sons: */
  473. if (j < s.heap_len &&
  474. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  475. j++;
  476. }
  477. /* Exit if v is smaller than both sons */
  478. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  479. /* Exchange v with the smallest son */
  480. s.heap[k] = s.heap[j];
  481. k = j;
  482. /* And continue down the tree, setting j to the left son of k */
  483. j <<= 1;
  484. }
  485. s.heap[k] = v;
  486. };
  487. // inlined manually
  488. // const SMALLEST = 1;
  489. /* ===========================================================================
  490. * Send the block data compressed using the given Huffman trees
  491. */
  492. const compress_block = (s, ltree, dtree) => {
  493. // deflate_state *s;
  494. // const ct_data *ltree; /* literal tree */
  495. // const ct_data *dtree; /* distance tree */
  496. let dist; /* distance of matched string */
  497. let lc; /* match length or unmatched char (if dist == 0) */
  498. let sx = 0; /* running index in sym_buf */
  499. let code; /* the code to send */
  500. let extra; /* number of extra bits to send */
  501. if (s.sym_next !== 0) {
  502. do {
  503. dist = s.pending_buf[s.sym_buf + sx++] & 0xff;
  504. dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;
  505. lc = s.pending_buf[s.sym_buf + sx++];
  506. if (dist === 0) {
  507. send_code(s, lc, ltree); /* send a literal byte */
  508. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  509. } else {
  510. /* Here, lc is the match length - MIN_MATCH */
  511. code = _length_code[lc];
  512. send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */
  513. extra = extra_lbits[code];
  514. if (extra !== 0) {
  515. lc -= base_length[code];
  516. send_bits(s, lc, extra); /* send the extra length bits */
  517. }
  518. dist--; /* dist is now the match distance - 1 */
  519. code = d_code(dist);
  520. //Assert (code < D_CODES, "bad d_code");
  521. send_code(s, code, dtree); /* send the distance code */
  522. extra = extra_dbits[code];
  523. if (extra !== 0) {
  524. dist -= base_dist[code];
  525. send_bits(s, dist, extra); /* send the extra distance bits */
  526. }
  527. } /* literal or match pair ? */
  528. /* Check that the overlay between pending_buf and sym_buf is ok: */
  529. //Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
  530. } while (sx < s.sym_next);
  531. }
  532. send_code(s, END_BLOCK, ltree);
  533. };
  534. /* ===========================================================================
  535. * Construct one Huffman tree and assigns the code bit strings and lengths.
  536. * Update the total bit length for the current block.
  537. * IN assertion: the field freq is set for all tree elements.
  538. * OUT assertions: the fields len and code are set to the optimal bit length
  539. * and corresponding code. The length opt_len is updated; static_len is
  540. * also updated if stree is not null. The field max_code is set.
  541. */
  542. const build_tree = (s, desc) => {
  543. // deflate_state *s;
  544. // tree_desc *desc; /* the tree descriptor */
  545. const tree = desc.dyn_tree;
  546. const stree = desc.stat_desc.static_tree;
  547. const has_stree = desc.stat_desc.has_stree;
  548. const elems = desc.stat_desc.elems;
  549. let n, m; /* iterate over heap elements */
  550. let max_code = -1; /* largest code with non zero frequency */
  551. let node; /* new node being created */
  552. /* Construct the initial heap, with least frequent element in
  553. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  554. * heap[0] is not used.
  555. */
  556. s.heap_len = 0;
  557. s.heap_max = HEAP_SIZE$1;
  558. for (n = 0; n < elems; n++) {
  559. if (tree[n * 2]/*.Freq*/ !== 0) {
  560. s.heap[++s.heap_len] = max_code = n;
  561. s.depth[n] = 0;
  562. } else {
  563. tree[n * 2 + 1]/*.Len*/ = 0;
  564. }
  565. }
  566. /* The pkzip format requires that at least one distance code exists,
  567. * and that at least one bit should be sent even if there is only one
  568. * possible code. So to avoid special checks later on we force at least
  569. * two codes of non zero frequency.
  570. */
  571. while (s.heap_len < 2) {
  572. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  573. tree[node * 2]/*.Freq*/ = 1;
  574. s.depth[node] = 0;
  575. s.opt_len--;
  576. if (has_stree) {
  577. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  578. }
  579. /* node is 0 or 1 so it does not have extra bits */
  580. }
  581. desc.max_code = max_code;
  582. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  583. * establish sub-heaps of increasing lengths:
  584. */
  585. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  586. /* Construct the Huffman tree by repeatedly combining the least two
  587. * frequent nodes.
  588. */
  589. node = elems; /* next internal node of the tree */
  590. do {
  591. //pqremove(s, tree, n); /* n = node of least frequency */
  592. /*** pqremove ***/
  593. n = s.heap[1/*SMALLEST*/];
  594. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  595. pqdownheap(s, tree, 1/*SMALLEST*/);
  596. /***/
  597. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  598. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  599. s.heap[--s.heap_max] = m;
  600. /* Create a new node father of n and m */
  601. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  602. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  603. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  604. /* and insert the new node in the heap */
  605. s.heap[1/*SMALLEST*/] = node++;
  606. pqdownheap(s, tree, 1/*SMALLEST*/);
  607. } while (s.heap_len >= 2);
  608. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  609. /* At this point, the fields freq and dad are set. We can now
  610. * generate the bit lengths.
  611. */
  612. gen_bitlen(s, desc);
  613. /* The field len is now set, we can generate the bit codes */
  614. gen_codes(tree, max_code, s.bl_count);
  615. };
  616. /* ===========================================================================
  617. * Scan a literal or distance tree to determine the frequencies of the codes
  618. * in the bit length tree.
  619. */
  620. const scan_tree = (s, tree, max_code) => {
  621. // deflate_state *s;
  622. // ct_data *tree; /* the tree to be scanned */
  623. // int max_code; /* and its largest code of non zero frequency */
  624. let n; /* iterates over all tree elements */
  625. let prevlen = -1; /* last emitted length */
  626. let curlen; /* length of current code */
  627. let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  628. let count = 0; /* repeat count of the current code */
  629. let max_count = 7; /* max repeat count */
  630. let min_count = 4; /* min repeat count */
  631. if (nextlen === 0) {
  632. max_count = 138;
  633. min_count = 3;
  634. }
  635. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  636. for (n = 0; n <= max_code; n++) {
  637. curlen = nextlen;
  638. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  639. if (++count < max_count && curlen === nextlen) {
  640. continue;
  641. } else if (count < min_count) {
  642. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  643. } else if (curlen !== 0) {
  644. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  645. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  646. } else if (count <= 10) {
  647. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  648. } else {
  649. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  650. }
  651. count = 0;
  652. prevlen = curlen;
  653. if (nextlen === 0) {
  654. max_count = 138;
  655. min_count = 3;
  656. } else if (curlen === nextlen) {
  657. max_count = 6;
  658. min_count = 3;
  659. } else {
  660. max_count = 7;
  661. min_count = 4;
  662. }
  663. }
  664. };
  665. /* ===========================================================================
  666. * Send a literal or distance tree in compressed form, using the codes in
  667. * bl_tree.
  668. */
  669. const send_tree = (s, tree, max_code) => {
  670. // deflate_state *s;
  671. // ct_data *tree; /* the tree to be scanned */
  672. // int max_code; /* and its largest code of non zero frequency */
  673. let n; /* iterates over all tree elements */
  674. let prevlen = -1; /* last emitted length */
  675. let curlen; /* length of current code */
  676. let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  677. let count = 0; /* repeat count of the current code */
  678. let max_count = 7; /* max repeat count */
  679. let min_count = 4; /* min repeat count */
  680. /* tree[max_code+1].Len = -1; */ /* guard already set */
  681. if (nextlen === 0) {
  682. max_count = 138;
  683. min_count = 3;
  684. }
  685. for (n = 0; n <= max_code; n++) {
  686. curlen = nextlen;
  687. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  688. if (++count < max_count && curlen === nextlen) {
  689. continue;
  690. } else if (count < min_count) {
  691. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  692. } else if (curlen !== 0) {
  693. if (curlen !== prevlen) {
  694. send_code(s, curlen, s.bl_tree);
  695. count--;
  696. }
  697. //Assert(count >= 3 && count <= 6, " 3_6?");
  698. send_code(s, REP_3_6, s.bl_tree);
  699. send_bits(s, count - 3, 2);
  700. } else if (count <= 10) {
  701. send_code(s, REPZ_3_10, s.bl_tree);
  702. send_bits(s, count - 3, 3);
  703. } else {
  704. send_code(s, REPZ_11_138, s.bl_tree);
  705. send_bits(s, count - 11, 7);
  706. }
  707. count = 0;
  708. prevlen = curlen;
  709. if (nextlen === 0) {
  710. max_count = 138;
  711. min_count = 3;
  712. } else if (curlen === nextlen) {
  713. max_count = 6;
  714. min_count = 3;
  715. } else {
  716. max_count = 7;
  717. min_count = 4;
  718. }
  719. }
  720. };
  721. /* ===========================================================================
  722. * Construct the Huffman tree for the bit lengths and return the index in
  723. * bl_order of the last bit length code to send.
  724. */
  725. const build_bl_tree = (s) => {
  726. let max_blindex; /* index of last bit length code of non zero freq */
  727. /* Determine the bit length frequencies for literal and distance trees */
  728. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  729. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  730. /* Build the bit length tree: */
  731. build_tree(s, s.bl_desc);
  732. /* opt_len now includes the length of the tree representations, except
  733. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  734. */
  735. /* Determine the number of bit length codes to send. The pkzip format
  736. * requires that at least 4 bit length codes be sent. (appnote.txt says
  737. * 3 but the actual value used is 4.)
  738. */
  739. for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {
  740. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  741. break;
  742. }
  743. }
  744. /* Update opt_len to include the bit length tree and counts */
  745. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  746. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  747. // s->opt_len, s->static_len));
  748. return max_blindex;
  749. };
  750. /* ===========================================================================
  751. * Send the header for a block using dynamic Huffman trees: the counts, the
  752. * lengths of the bit length codes, the literal tree and the distance tree.
  753. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  754. */
  755. const send_all_trees = (s, lcodes, dcodes, blcodes) => {
  756. // deflate_state *s;
  757. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  758. let rank; /* index in bl_order */
  759. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  760. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  761. // "too many codes");
  762. //Tracev((stderr, "\nbl counts: "));
  763. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  764. send_bits(s, dcodes - 1, 5);
  765. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  766. for (rank = 0; rank < blcodes; rank++) {
  767. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  768. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  769. }
  770. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  771. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  772. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  773. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  774. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  775. };
  776. /* ===========================================================================
  777. * Check if the data type is TEXT or BINARY, using the following algorithm:
  778. * - TEXT if the two conditions below are satisfied:
  779. * a) There are no non-portable control characters belonging to the
  780. * "block list" (0..6, 14..25, 28..31).
  781. * b) There is at least one printable character belonging to the
  782. * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  783. * - BINARY otherwise.
  784. * - The following partially-portable control characters form a
  785. * "gray list" that is ignored in this detection algorithm:
  786. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  787. * IN assertion: the fields Freq of dyn_ltree are set.
  788. */
  789. const detect_data_type = (s) => {
  790. /* block_mask is the bit mask of block-listed bytes
  791. * set bits 0..6, 14..25, and 28..31
  792. * 0xf3ffc07f = binary 11110011111111111100000001111111
  793. */
  794. let block_mask = 0xf3ffc07f;
  795. let n;
  796. /* Check for non-textual ("block-listed") bytes. */
  797. for (n = 0; n <= 31; n++, block_mask >>>= 1) {
  798. if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  799. return Z_BINARY;
  800. }
  801. }
  802. /* Check for textual ("allow-listed") bytes. */
  803. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  804. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  805. return Z_TEXT;
  806. }
  807. for (n = 32; n < LITERALS$1; n++) {
  808. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  809. return Z_TEXT;
  810. }
  811. }
  812. /* There are no "block-listed" or "allow-listed" bytes:
  813. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  814. */
  815. return Z_BINARY;
  816. };
  817. let static_init_done = false;
  818. /* ===========================================================================
  819. * Initialize the tree data structures for a new zlib stream.
  820. */
  821. const _tr_init$1 = (s) =>
  822. {
  823. if (!static_init_done) {
  824. tr_static_init();
  825. static_init_done = true;
  826. }
  827. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  828. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  829. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  830. s.bi_buf = 0;
  831. s.bi_valid = 0;
  832. /* Initialize the first block of the first file: */
  833. init_block(s);
  834. };
  835. /* ===========================================================================
  836. * Send a stored block
  837. */
  838. const _tr_stored_block$1 = (s, buf, stored_len, last) => {
  839. //DeflateState *s;
  840. //charf *buf; /* input block */
  841. //ulg stored_len; /* length of input block */
  842. //int last; /* one if this is the last block for a file */
  843. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  844. bi_windup(s); /* align on byte boundary */
  845. put_short(s, stored_len);
  846. put_short(s, ~stored_len);
  847. if (stored_len) {
  848. s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);
  849. }
  850. s.pending += stored_len;
  851. };
  852. /* ===========================================================================
  853. * Send one empty static block to give enough lookahead for inflate.
  854. * This takes 10 bits, of which 7 may remain in the bit buffer.
  855. */
  856. const _tr_align$1 = (s) => {
  857. send_bits(s, STATIC_TREES << 1, 3);
  858. send_code(s, END_BLOCK, static_ltree);
  859. bi_flush(s);
  860. };
  861. /* ===========================================================================
  862. * Determine the best encoding for the current block: dynamic trees, static
  863. * trees or store, and write out the encoded block.
  864. */
  865. const _tr_flush_block$1 = (s, buf, stored_len, last) => {
  866. //DeflateState *s;
  867. //charf *buf; /* input block, or NULL if too old */
  868. //ulg stored_len; /* length of input block */
  869. //int last; /* one if this is the last block for a file */
  870. let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  871. let max_blindex = 0; /* index of last bit length code of non zero freq */
  872. /* Build the Huffman trees unless a stored block is forced */
  873. if (s.level > 0) {
  874. /* Check if the file is binary or text */
  875. if (s.strm.data_type === Z_UNKNOWN$1) {
  876. s.strm.data_type = detect_data_type(s);
  877. }
  878. /* Construct the literal and distance trees */
  879. build_tree(s, s.l_desc);
  880. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  881. // s->static_len));
  882. build_tree(s, s.d_desc);
  883. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  884. // s->static_len));
  885. /* At this point, opt_len and static_len are the total bit lengths of
  886. * the compressed block data, excluding the tree representations.
  887. */
  888. /* Build the bit length tree for the above two trees, and get the index
  889. * in bl_order of the last bit length code to send.
  890. */
  891. max_blindex = build_bl_tree(s);
  892. /* Determine the best encoding. Compute the block lengths in bytes. */
  893. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  894. static_lenb = (s.static_len + 3 + 7) >>> 3;
  895. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  896. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  897. // s->sym_next / 3));
  898. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  899. } else {
  900. // Assert(buf != (char*)0, "lost buf");
  901. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  902. }
  903. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  904. /* 4: two words for the lengths */
  905. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  906. * Otherwise we can't have processed more than WSIZE input bytes since
  907. * the last block flush, because compression would have been
  908. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  909. * transform a block into a stored block.
  910. */
  911. _tr_stored_block$1(s, buf, stored_len, last);
  912. } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {
  913. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  914. compress_block(s, static_ltree, static_dtree);
  915. } else {
  916. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  917. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  918. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  919. }
  920. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  921. /* The above check is made mod 2^32, for files larger than 512 MB
  922. * and uLong implemented on 32 bits.
  923. */
  924. init_block(s);
  925. if (last) {
  926. bi_windup(s);
  927. }
  928. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  929. // s->compressed_len-7*last));
  930. };
  931. /* ===========================================================================
  932. * Save the match info and tally the frequency counts. Return true if
  933. * the current block must be flushed.
  934. */
  935. const _tr_tally$1 = (s, dist, lc) => {
  936. // deflate_state *s;
  937. // unsigned dist; /* distance of matched string */
  938. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  939. s.pending_buf[s.sym_buf + s.sym_next++] = dist;
  940. s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;
  941. s.pending_buf[s.sym_buf + s.sym_next++] = lc;
  942. if (dist === 0) {
  943. /* lc is the unmatched char */
  944. s.dyn_ltree[lc * 2]/*.Freq*/++;
  945. } else {
  946. s.matches++;
  947. /* Here, lc is the match length - MIN_MATCH */
  948. dist--; /* dist = match distance - 1 */
  949. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  950. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  951. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  952. s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;
  953. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  954. }
  955. return (s.sym_next === s.sym_end);
  956. };
  957. var _tr_init_1 = _tr_init$1;
  958. var _tr_stored_block_1 = _tr_stored_block$1;
  959. var _tr_flush_block_1 = _tr_flush_block$1;
  960. var _tr_tally_1 = _tr_tally$1;
  961. var _tr_align_1 = _tr_align$1;
  962. var trees = {
  963. _tr_init: _tr_init_1,
  964. _tr_stored_block: _tr_stored_block_1,
  965. _tr_flush_block: _tr_flush_block_1,
  966. _tr_tally: _tr_tally_1,
  967. _tr_align: _tr_align_1
  968. };
  969. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  970. // It isn't worth it to make additional optimizations as in original.
  971. // Small size is preferable.
  972. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  973. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  974. //
  975. // This software is provided 'as-is', without any express or implied
  976. // warranty. In no event will the authors be held liable for any damages
  977. // arising from the use of this software.
  978. //
  979. // Permission is granted to anyone to use this software for any purpose,
  980. // including commercial applications, and to alter it and redistribute it
  981. // freely, subject to the following restrictions:
  982. //
  983. // 1. The origin of this software must not be misrepresented; you must not
  984. // claim that you wrote the original software. If you use this software
  985. // in a product, an acknowledgment in the product documentation would be
  986. // appreciated but is not required.
  987. // 2. Altered source versions must be plainly marked as such, and must not be
  988. // misrepresented as being the original software.
  989. // 3. This notice may not be removed or altered from any source distribution.
  990. const adler32 = (adler, buf, len, pos) => {
  991. let s1 = (adler & 0xffff) |0,
  992. s2 = ((adler >>> 16) & 0xffff) |0,
  993. n = 0;
  994. while (len !== 0) {
  995. // Set limit ~ twice less than 5552, to keep
  996. // s2 in 31-bits, because we force signed ints.
  997. // in other case %= will fail.
  998. n = len > 2000 ? 2000 : len;
  999. len -= n;
  1000. do {
  1001. s1 = (s1 + buf[pos++]) |0;
  1002. s2 = (s2 + s1) |0;
  1003. } while (--n);
  1004. s1 %= 65521;
  1005. s2 %= 65521;
  1006. }
  1007. return (s1 | (s2 << 16)) |0;
  1008. };
  1009. var adler32_1 = adler32;
  1010. // Note: we can't get significant speed boost here.
  1011. // So write code to minimize size - no pregenerated tables
  1012. // and array tools dependencies.
  1013. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1014. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1015. //
  1016. // This software is provided 'as-is', without any express or implied
  1017. // warranty. In no event will the authors be held liable for any damages
  1018. // arising from the use of this software.
  1019. //
  1020. // Permission is granted to anyone to use this software for any purpose,
  1021. // including commercial applications, and to alter it and redistribute it
  1022. // freely, subject to the following restrictions:
  1023. //
  1024. // 1. The origin of this software must not be misrepresented; you must not
  1025. // claim that you wrote the original software. If you use this software
  1026. // in a product, an acknowledgment in the product documentation would be
  1027. // appreciated but is not required.
  1028. // 2. Altered source versions must be plainly marked as such, and must not be
  1029. // misrepresented as being the original software.
  1030. // 3. This notice may not be removed or altered from any source distribution.
  1031. // Use ordinary array, since untyped makes no boost here
  1032. const makeTable = () => {
  1033. let c, table = [];
  1034. for (var n = 0; n < 256; n++) {
  1035. c = n;
  1036. for (var k = 0; k < 8; k++) {
  1037. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  1038. }
  1039. table[n] = c;
  1040. }
  1041. return table;
  1042. };
  1043. // Create table on load. Just 255 signed longs. Not a problem.
  1044. const crcTable = new Uint32Array(makeTable());
  1045. const crc32 = (crc, buf, len, pos) => {
  1046. const t = crcTable;
  1047. const end = pos + len;
  1048. crc ^= -1;
  1049. for (let i = pos; i < end; i++) {
  1050. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  1051. }
  1052. return (crc ^ (-1)); // >>> 0;
  1053. };
  1054. var crc32_1 = crc32;
  1055. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1056. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1057. //
  1058. // This software is provided 'as-is', without any express or implied
  1059. // warranty. In no event will the authors be held liable for any damages
  1060. // arising from the use of this software.
  1061. //
  1062. // Permission is granted to anyone to use this software for any purpose,
  1063. // including commercial applications, and to alter it and redistribute it
  1064. // freely, subject to the following restrictions:
  1065. //
  1066. // 1. The origin of this software must not be misrepresented; you must not
  1067. // claim that you wrote the original software. If you use this software
  1068. // in a product, an acknowledgment in the product documentation would be
  1069. // appreciated but is not required.
  1070. // 2. Altered source versions must be plainly marked as such, and must not be
  1071. // misrepresented as being the original software.
  1072. // 3. This notice may not be removed or altered from any source distribution.
  1073. var messages = {
  1074. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  1075. 1: 'stream end', /* Z_STREAM_END 1 */
  1076. 0: '', /* Z_OK 0 */
  1077. '-1': 'file error', /* Z_ERRNO (-1) */
  1078. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  1079. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  1080. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  1081. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  1082. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  1083. };
  1084. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1085. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1086. //
  1087. // This software is provided 'as-is', without any express or implied
  1088. // warranty. In no event will the authors be held liable for any damages
  1089. // arising from the use of this software.
  1090. //
  1091. // Permission is granted to anyone to use this software for any purpose,
  1092. // including commercial applications, and to alter it and redistribute it
  1093. // freely, subject to the following restrictions:
  1094. //
  1095. // 1. The origin of this software must not be misrepresented; you must not
  1096. // claim that you wrote the original software. If you use this software
  1097. // in a product, an acknowledgment in the product documentation would be
  1098. // appreciated but is not required.
  1099. // 2. Altered source versions must be plainly marked as such, and must not be
  1100. // misrepresented as being the original software.
  1101. // 3. This notice may not be removed or altered from any source distribution.
  1102. var constants$1 = {
  1103. /* Allowed flush values; see deflate() and inflate() below for details */
  1104. Z_NO_FLUSH: 0,
  1105. Z_PARTIAL_FLUSH: 1,
  1106. Z_SYNC_FLUSH: 2,
  1107. Z_FULL_FLUSH: 3,
  1108. Z_FINISH: 4,
  1109. Z_BLOCK: 5,
  1110. Z_TREES: 6,
  1111. /* Return codes for the compression/decompression functions. Negative values
  1112. * are errors, positive values are used for special but normal events.
  1113. */
  1114. Z_OK: 0,
  1115. Z_STREAM_END: 1,
  1116. Z_NEED_DICT: 2,
  1117. Z_ERRNO: -1,
  1118. Z_STREAM_ERROR: -2,
  1119. Z_DATA_ERROR: -3,
  1120. Z_MEM_ERROR: -4,
  1121. Z_BUF_ERROR: -5,
  1122. //Z_VERSION_ERROR: -6,
  1123. /* compression levels */
  1124. Z_NO_COMPRESSION: 0,
  1125. Z_BEST_SPEED: 1,
  1126. Z_BEST_COMPRESSION: 9,
  1127. Z_DEFAULT_COMPRESSION: -1,
  1128. Z_FILTERED: 1,
  1129. Z_HUFFMAN_ONLY: 2,
  1130. Z_RLE: 3,
  1131. Z_FIXED: 4,
  1132. Z_DEFAULT_STRATEGY: 0,
  1133. /* Possible values of the data_type field (though see inflate()) */
  1134. Z_BINARY: 0,
  1135. Z_TEXT: 1,
  1136. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  1137. Z_UNKNOWN: 2,
  1138. /* The deflate compression method */
  1139. Z_DEFLATED: 8
  1140. //Z_NULL: null // Use -1 or null inline, depending on var type
  1141. };
  1142. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  1143. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  1144. //
  1145. // This software is provided 'as-is', without any express or implied
  1146. // warranty. In no event will the authors be held liable for any damages
  1147. // arising from the use of this software.
  1148. //
  1149. // Permission is granted to anyone to use this software for any purpose,
  1150. // including commercial applications, and to alter it and redistribute it
  1151. // freely, subject to the following restrictions:
  1152. //
  1153. // 1. The origin of this software must not be misrepresented; you must not
  1154. // claim that you wrote the original software. If you use this software
  1155. // in a product, an acknowledgment in the product documentation would be
  1156. // appreciated but is not required.
  1157. // 2. Altered source versions must be plainly marked as such, and must not be
  1158. // misrepresented as being the original software.
  1159. // 3. This notice may not be removed or altered from any source distribution.
  1160. const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;
  1161. /* Public constants ==========================================================*/
  1162. /* ===========================================================================*/
  1163. const {
  1164. Z_NO_FLUSH: Z_NO_FLUSH$1, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$1, Z_BLOCK,
  1165. Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,
  1166. Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
  1167. Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,
  1168. Z_UNKNOWN,
  1169. Z_DEFLATED: Z_DEFLATED$1
  1170. } = constants$1;
  1171. /*============================================================================*/
  1172. const MAX_MEM_LEVEL = 9;
  1173. /* Maximum value for memLevel in deflateInit2 */
  1174. const MAX_WBITS = 15;
  1175. /* 32K LZ77 window */
  1176. const DEF_MEM_LEVEL = 8;
  1177. const LENGTH_CODES = 29;
  1178. /* number of length codes, not counting the special END_BLOCK code */
  1179. const LITERALS = 256;
  1180. /* number of literal bytes 0..255 */
  1181. const L_CODES = LITERALS + 1 + LENGTH_CODES;
  1182. /* number of Literal or Length codes, including the END_BLOCK code */
  1183. const D_CODES = 30;
  1184. /* number of distance codes */
  1185. const BL_CODES = 19;
  1186. /* number of codes used to transfer the bit lengths */
  1187. const HEAP_SIZE = 2 * L_CODES + 1;
  1188. /* maximum heap size */
  1189. const MAX_BITS = 15;
  1190. /* All codes must not exceed MAX_BITS bits */
  1191. const MIN_MATCH = 3;
  1192. const MAX_MATCH = 258;
  1193. const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  1194. const PRESET_DICT = 0x20;
  1195. const INIT_STATE = 42; /* zlib header -> BUSY_STATE */
  1196. //#ifdef GZIP
  1197. const GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */
  1198. //#endif
  1199. const EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */
  1200. const NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */
  1201. const COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */
  1202. const HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */
  1203. const BUSY_STATE = 113; /* deflate -> FINISH_STATE */
  1204. const FINISH_STATE = 666; /* stream complete */
  1205. const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  1206. const BS_BLOCK_DONE = 2; /* block flush performed */
  1207. const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  1208. const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  1209. const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  1210. const err = (strm, errorCode) => {
  1211. strm.msg = messages[errorCode];
  1212. return errorCode;
  1213. };
  1214. const rank = (f) => {
  1215. return ((f) * 2) - ((f) > 4 ? 9 : 0);
  1216. };
  1217. const zero = (buf) => {
  1218. let len = buf.length; while (--len >= 0) { buf[len] = 0; }
  1219. };
  1220. /* ===========================================================================
  1221. * Slide the hash table when sliding the window down (could be avoided with 32
  1222. * bit values at the expense of memory usage). We slide even when level == 0 to
  1223. * keep the hash table consistent if we switch back to level > 0 later.
  1224. */
  1225. const slide_hash = (s) => {
  1226. let n, m;
  1227. let p;
  1228. let wsize = s.w_size;
  1229. n = s.hash_size;
  1230. p = n;
  1231. do {
  1232. m = s.head[--p];
  1233. s.head[p] = (m >= wsize ? m - wsize : 0);
  1234. } while (--n);
  1235. n = wsize;
  1236. //#ifndef FASTEST
  1237. p = n;
  1238. do {
  1239. m = s.prev[--p];
  1240. s.prev[p] = (m >= wsize ? m - wsize : 0);
  1241. /* If n is not on any hash chain, prev[n] is garbage but
  1242. * its value will never be used.
  1243. */
  1244. } while (--n);
  1245. //#endif
  1246. };
  1247. /* eslint-disable new-cap */
  1248. let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;
  1249. // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
  1250. // But breaks binary compatibility
  1251. //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
  1252. let HASH = HASH_ZLIB;
  1253. /* =========================================================================
  1254. * Flush as much pending output as possible. All deflate() output, except for
  1255. * some deflate_stored() output, goes through this function so some
  1256. * applications may wish to modify it to avoid allocating a large
  1257. * strm->next_out buffer and copying into it. (See also read_buf()).
  1258. */
  1259. const flush_pending = (strm) => {
  1260. const s = strm.state;
  1261. //_tr_flush_bits(s);
  1262. let len = s.pending;
  1263. if (len > strm.avail_out) {
  1264. len = strm.avail_out;
  1265. }
  1266. if (len === 0) { return; }
  1267. strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
  1268. strm.next_out += len;
  1269. s.pending_out += len;
  1270. strm.total_out += len;
  1271. strm.avail_out -= len;
  1272. s.pending -= len;
  1273. if (s.pending === 0) {
  1274. s.pending_out = 0;
  1275. }
  1276. };
  1277. const flush_block_only = (s, last) => {
  1278. _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  1279. s.block_start = s.strstart;
  1280. flush_pending(s.strm);
  1281. };
  1282. const put_byte = (s, b) => {
  1283. s.pending_buf[s.pending++] = b;
  1284. };
  1285. /* =========================================================================
  1286. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  1287. * IN assertion: the stream state is correct and there is enough room in
  1288. * pending_buf.
  1289. */
  1290. const putShortMSB = (s, b) => {
  1291. // put_byte(s, (Byte)(b >> 8));
  1292. // put_byte(s, (Byte)(b & 0xff));
  1293. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  1294. s.pending_buf[s.pending++] = b & 0xff;
  1295. };
  1296. /* ===========================================================================
  1297. * Read a new buffer from the current input stream, update the adler32
  1298. * and total number of bytes read. All deflate() input goes through
  1299. * this function so some applications may wish to modify it to avoid
  1300. * allocating a large strm->input buffer and copying from it.
  1301. * (See also flush_pending()).
  1302. */
  1303. const read_buf = (strm, buf, start, size) => {
  1304. let len = strm.avail_in;
  1305. if (len > size) { len = size; }
  1306. if (len === 0) { return 0; }
  1307. strm.avail_in -= len;
  1308. // zmemcpy(buf, strm->next_in, len);
  1309. buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
  1310. if (strm.state.wrap === 1) {
  1311. strm.adler = adler32_1(strm.adler, buf, len, start);
  1312. }
  1313. else if (strm.state.wrap === 2) {
  1314. strm.adler = crc32_1(strm.adler, buf, len, start);
  1315. }
  1316. strm.next_in += len;
  1317. strm.total_in += len;
  1318. return len;
  1319. };
  1320. /* ===========================================================================
  1321. * Set match_start to the longest match starting at the given string and
  1322. * return its length. Matches shorter or equal to prev_length are discarded,
  1323. * in which case the result is equal to prev_length and match_start is
  1324. * garbage.
  1325. * IN assertions: cur_match is the head of the hash chain for the current
  1326. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1327. * OUT assertion: the match length is not greater than s->lookahead.
  1328. */
  1329. const longest_match = (s, cur_match) => {
  1330. let chain_length = s.max_chain_length; /* max hash chain length */
  1331. let scan = s.strstart; /* current string */
  1332. let match; /* matched string */
  1333. let len; /* length of current match */
  1334. let best_len = s.prev_length; /* best match length so far */
  1335. let nice_match = s.nice_match; /* stop if match long enough */
  1336. const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  1337. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  1338. const _win = s.window; // shortcut
  1339. const wmask = s.w_mask;
  1340. const prev = s.prev;
  1341. /* Stop when cur_match becomes <= limit. To simplify the code,
  1342. * we prevent matches with the string of window index 0.
  1343. */
  1344. const strend = s.strstart + MAX_MATCH;
  1345. let scan_end1 = _win[scan + best_len - 1];
  1346. let scan_end = _win[scan + best_len];
  1347. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1348. * It is easy to get rid of this optimization if necessary.
  1349. */
  1350. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1351. /* Do not waste too much time if we already have a good match: */
  1352. if (s.prev_length >= s.good_match) {
  1353. chain_length >>= 2;
  1354. }
  1355. /* Do not look for matches beyond the end of the input. This is necessary
  1356. * to make deflate deterministic.
  1357. */
  1358. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  1359. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1360. do {
  1361. // Assert(cur_match < s->strstart, "no future");
  1362. match = cur_match;
  1363. /* Skip to next match if the match length cannot increase
  1364. * or if the match length is less than 2. Note that the checks below
  1365. * for insufficient lookahead only occur occasionally for performance
  1366. * reasons. Therefore uninitialized memory will be accessed, and
  1367. * conditional jumps will be made that depend on those values.
  1368. * However the length of the match is limited to the lookahead, so
  1369. * the output of deflate is not affected by the uninitialized values.
  1370. */
  1371. if (_win[match + best_len] !== scan_end ||
  1372. _win[match + best_len - 1] !== scan_end1 ||
  1373. _win[match] !== _win[scan] ||
  1374. _win[++match] !== _win[scan + 1]) {
  1375. continue;
  1376. }
  1377. /* The check at best_len-1 can be removed because it will be made
  1378. * again later. (This heuristic is not always a win.)
  1379. * It is not necessary to compare scan[2] and match[2] since they
  1380. * are always equal when the other bytes match, given that
  1381. * the hash keys are equal and that HASH_BITS >= 8.
  1382. */
  1383. scan += 2;
  1384. match++;
  1385. // Assert(*scan == *match, "match[2]?");
  1386. /* We check for insufficient lookahead only every 8th comparison;
  1387. * the 256th check will be made at strstart+258.
  1388. */
  1389. do {
  1390. /*jshint noempty:false*/
  1391. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1392. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1393. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1394. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  1395. scan < strend);
  1396. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1397. len = MAX_MATCH - (strend - scan);
  1398. scan = strend - MAX_MATCH;
  1399. if (len > best_len) {
  1400. s.match_start = cur_match;
  1401. best_len = len;
  1402. if (len >= nice_match) {
  1403. break;
  1404. }
  1405. scan_end1 = _win[scan + best_len - 1];
  1406. scan_end = _win[scan + best_len];
  1407. }
  1408. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  1409. if (best_len <= s.lookahead) {
  1410. return best_len;
  1411. }
  1412. return s.lookahead;
  1413. };
  1414. /* ===========================================================================
  1415. * Fill the window when the lookahead becomes insufficient.
  1416. * Updates strstart and lookahead.
  1417. *
  1418. * IN assertion: lookahead < MIN_LOOKAHEAD
  1419. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1420. * At least one byte has been read, or avail_in == 0; reads are
  1421. * performed for at least two bytes (required for the zip translate_eol
  1422. * option -- not supported here).
  1423. */
  1424. const fill_window = (s) => {
  1425. const _w_size = s.w_size;
  1426. let n, more, str;
  1427. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  1428. do {
  1429. more = s.window_size - s.lookahead - s.strstart;
  1430. // JS ints have 32 bit, block below not needed
  1431. /* Deal with !@#$% 64K limit: */
  1432. //if (sizeof(int) <= 2) {
  1433. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  1434. // more = wsize;
  1435. //
  1436. // } else if (more == (unsigned)(-1)) {
  1437. // /* Very unlikely, but possible on 16 bit machine if
  1438. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  1439. // */
  1440. // more--;
  1441. // }
  1442. //}
  1443. /* If the window is almost full and there is insufficient lookahead,
  1444. * move the upper half to the lower one to make room in the upper half.
  1445. */
  1446. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  1447. s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);
  1448. s.match_start -= _w_size;
  1449. s.strstart -= _w_size;
  1450. /* we now have strstart >= MAX_DIST */
  1451. s.block_start -= _w_size;
  1452. if (s.insert > s.strstart) {
  1453. s.insert = s.strstart;
  1454. }
  1455. slide_hash(s);
  1456. more += _w_size;
  1457. }
  1458. if (s.strm.avail_in === 0) {
  1459. break;
  1460. }
  1461. /* If there was no sliding:
  1462. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1463. * more == window_size - lookahead - strstart
  1464. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1465. * => more >= window_size - 2*WSIZE + 2
  1466. * In the BIG_MEM or MMAP case (not yet supported),
  1467. * window_size == input_size + MIN_LOOKAHEAD &&
  1468. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1469. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1470. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1471. */
  1472. //Assert(more >= 2, "more < 2");
  1473. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  1474. s.lookahead += n;
  1475. /* Initialize the hash value now that we have some input: */
  1476. if (s.lookahead + s.insert >= MIN_MATCH) {
  1477. str = s.strstart - s.insert;
  1478. s.ins_h = s.window[str];
  1479. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  1480. s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);
  1481. //#if MIN_MATCH != 3
  1482. // Call update_hash() MIN_MATCH-3 more times
  1483. //#endif
  1484. while (s.insert) {
  1485. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  1486. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  1487. s.prev[str & s.w_mask] = s.head[s.ins_h];
  1488. s.head[s.ins_h] = str;
  1489. str++;
  1490. s.insert--;
  1491. if (s.lookahead + s.insert < MIN_MATCH) {
  1492. break;
  1493. }
  1494. }
  1495. }
  1496. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1497. * but this is not important since only literal bytes will be emitted.
  1498. */
  1499. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  1500. /* If the WIN_INIT bytes after the end of the current data have never been
  1501. * written, then zero those bytes in order to avoid memory check reports of
  1502. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1503. * the longest match routines. Update the high water mark for the next
  1504. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  1505. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  1506. */
  1507. // if (s.high_water < s.window_size) {
  1508. // const curr = s.strstart + s.lookahead;
  1509. // let init = 0;
  1510. //
  1511. // if (s.high_water < curr) {
  1512. // /* Previous high water mark below current data -- zero WIN_INIT
  1513. // * bytes or up to end of window, whichever is less.
  1514. // */
  1515. // init = s.window_size - curr;
  1516. // if (init > WIN_INIT)
  1517. // init = WIN_INIT;
  1518. // zmemzero(s->window + curr, (unsigned)init);
  1519. // s->high_water = curr + init;
  1520. // }
  1521. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  1522. // /* High water mark at or above current data, but below current data
  1523. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1524. // * to end of window, whichever is less.
  1525. // */
  1526. // init = (ulg)curr + WIN_INIT - s->high_water;
  1527. // if (init > s->window_size - s->high_water)
  1528. // init = s->window_size - s->high_water;
  1529. // zmemzero(s->window + s->high_water, (unsigned)init);
  1530. // s->high_water += init;
  1531. // }
  1532. // }
  1533. //
  1534. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  1535. // "not enough room for search");
  1536. };
  1537. /* ===========================================================================
  1538. * Copy without compression as much as possible from the input stream, return
  1539. * the current block state.
  1540. *
  1541. * In case deflateParams() is used to later switch to a non-zero compression
  1542. * level, s->matches (otherwise unused when storing) keeps track of the number
  1543. * of hash table slides to perform. If s->matches is 1, then one hash table
  1544. * slide will be done when switching. If s->matches is 2, the maximum value
  1545. * allowed here, then the hash table will be cleared, since two or more slides
  1546. * is the same as a clear.
  1547. *
  1548. * deflate_stored() is written to minimize the number of times an input byte is
  1549. * copied. It is most efficient with large input and output buffers, which
  1550. * maximizes the opportunites to have a single copy from next_in to next_out.
  1551. */
  1552. const deflate_stored = (s, flush) => {
  1553. /* Smallest worthy block size when not flushing or finishing. By default
  1554. * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
  1555. * large input and output buffers, the stored block size will be larger.
  1556. */
  1557. let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;
  1558. /* Copy as many min_block or larger stored blocks directly to next_out as
  1559. * possible. If flushing, copy the remaining available input to next_out as
  1560. * stored blocks, if there is enough space.
  1561. */
  1562. let len, left, have, last = 0;
  1563. let used = s.strm.avail_in;
  1564. do {
  1565. /* Set len to the maximum size block that we can copy directly with the
  1566. * available input data and output space. Set left to how much of that
  1567. * would be copied from what's left in the window.
  1568. */
  1569. len = 65535/* MAX_STORED */; /* maximum deflate stored block length */
  1570. have = (s.bi_valid + 42) >> 3; /* number of header bytes */
  1571. if (s.strm.avail_out < have) { /* need room for header */
  1572. break;
  1573. }
  1574. /* maximum stored block length that will fit in avail_out: */
  1575. have = s.strm.avail_out - have;
  1576. left = s.strstart - s.block_start; /* bytes left in window */
  1577. if (len > left + s.strm.avail_in) {
  1578. len = left + s.strm.avail_in; /* limit len to the input */
  1579. }
  1580. if (len > have) {
  1581. len = have; /* limit len to the output */
  1582. }
  1583. /* If the stored block would be less than min_block in length, or if
  1584. * unable to copy all of the available input when flushing, then try
  1585. * copying to the window and the pending buffer instead. Also don't
  1586. * write an empty block when flushing -- deflate() does that.
  1587. */
  1588. if (len < min_block && ((len === 0 && flush !== Z_FINISH$1) ||
  1589. flush === Z_NO_FLUSH$1 ||
  1590. len !== left + s.strm.avail_in)) {
  1591. break;
  1592. }
  1593. /* Make a dummy stored block in pending to get the header bytes,
  1594. * including any pending bits. This also updates the debugging counts.
  1595. */
  1596. last = flush === Z_FINISH$1 && len === left + s.strm.avail_in ? 1 : 0;
  1597. _tr_stored_block(s, 0, 0, last);
  1598. /* Replace the lengths in the dummy stored block with len. */
  1599. s.pending_buf[s.pending - 4] = len;
  1600. s.pending_buf[s.pending - 3] = len >> 8;
  1601. s.pending_buf[s.pending - 2] = ~len;
  1602. s.pending_buf[s.pending - 1] = ~len >> 8;
  1603. /* Write the stored block header bytes. */
  1604. flush_pending(s.strm);
  1605. //#ifdef ZLIB_DEBUG
  1606. // /* Update debugging counts for the data about to be copied. */
  1607. // s->compressed_len += len << 3;
  1608. // s->bits_sent += len << 3;
  1609. //#endif
  1610. /* Copy uncompressed bytes from the window to next_out. */
  1611. if (left) {
  1612. if (left > len) {
  1613. left = len;
  1614. }
  1615. //zmemcpy(s->strm->next_out, s->window + s->block_start, left);
  1616. s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
  1617. s.strm.next_out += left;
  1618. s.strm.avail_out -= left;
  1619. s.strm.total_out += left;
  1620. s.block_start += left;
  1621. len -= left;
  1622. }
  1623. /* Copy uncompressed bytes directly from next_in to next_out, updating
  1624. * the check value.
  1625. */
  1626. if (len) {
  1627. read_buf(s.strm, s.strm.output, s.strm.next_out, len);
  1628. s.strm.next_out += len;
  1629. s.strm.avail_out -= len;
  1630. s.strm.total_out += len;
  1631. }
  1632. } while (last === 0);
  1633. /* Update the sliding window with the last s->w_size bytes of the copied
  1634. * data, or append all of the copied data to the existing window if less
  1635. * than s->w_size bytes were copied. Also update the number of bytes to
  1636. * insert in the hash tables, in the event that deflateParams() switches to
  1637. * a non-zero compression level.
  1638. */
  1639. used -= s.strm.avail_in; /* number of input bytes directly copied */
  1640. if (used) {
  1641. /* If any input was used, then no unused input remains in the window,
  1642. * therefore s->block_start == s->strstart.
  1643. */
  1644. if (used >= s.w_size) { /* supplant the previous history */
  1645. s.matches = 2; /* clear hash */
  1646. //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
  1647. s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);
  1648. s.strstart = s.w_size;
  1649. s.insert = s.strstart;
  1650. }
  1651. else {
  1652. if (s.window_size - s.strstart <= used) {
  1653. /* Slide the window down. */
  1654. s.strstart -= s.w_size;
  1655. //zmemcpy(s->window, s->window + s->w_size, s->strstart);
  1656. s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
  1657. if (s.matches < 2) {
  1658. s.matches++; /* add a pending slide_hash() */
  1659. }
  1660. if (s.insert > s.strstart) {
  1661. s.insert = s.strstart;
  1662. }
  1663. }
  1664. //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
  1665. s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);
  1666. s.strstart += used;
  1667. s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;
  1668. }
  1669. s.block_start = s.strstart;
  1670. }
  1671. if (s.high_water < s.strstart) {
  1672. s.high_water = s.strstart;
  1673. }
  1674. /* If the last block was written to next_out, then done. */
  1675. if (last) {
  1676. return BS_FINISH_DONE;
  1677. }
  1678. /* If flushing and all input has been consumed, then done. */
  1679. if (flush !== Z_NO_FLUSH$1 && flush !== Z_FINISH$1 &&
  1680. s.strm.avail_in === 0 && s.strstart === s.block_start) {
  1681. return BS_BLOCK_DONE;
  1682. }
  1683. /* Fill the window with any remaining input. */
  1684. have = s.window_size - s.strstart;
  1685. if (s.strm.avail_in > have && s.block_start >= s.w_size) {
  1686. /* Slide the window down. */
  1687. s.block_start -= s.w_size;
  1688. s.strstart -= s.w_size;
  1689. //zmemcpy(s->window, s->window + s->w_size, s->strstart);
  1690. s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
  1691. if (s.matches < 2) {
  1692. s.matches++; /* add a pending slide_hash() */
  1693. }
  1694. have += s.w_size; /* more space now */
  1695. if (s.insert > s.strstart) {
  1696. s.insert = s.strstart;
  1697. }
  1698. }
  1699. if (have > s.strm.avail_in) {
  1700. have = s.strm.avail_in;
  1701. }
  1702. if (have) {
  1703. read_buf(s.strm, s.window, s.strstart, have);
  1704. s.strstart += have;
  1705. s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;
  1706. }
  1707. if (s.high_water < s.strstart) {
  1708. s.high_water = s.strstart;
  1709. }
  1710. /* There was not enough avail_out to write a complete worthy or flushed
  1711. * stored block to next_out. Write a stored block to pending instead, if we
  1712. * have enough input for a worthy block, or if flushing and there is enough
  1713. * room for the remaining input as a stored block in the pending buffer.
  1714. */
  1715. have = (s.bi_valid + 42) >> 3; /* number of header bytes */
  1716. /* maximum stored block length that will fit in pending: */
  1717. have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;
  1718. min_block = have > s.w_size ? s.w_size : have;
  1719. left = s.strstart - s.block_start;
  1720. if (left >= min_block ||
  1721. ((left || flush === Z_FINISH$1) && flush !== Z_NO_FLUSH$1 &&
  1722. s.strm.avail_in === 0 && left <= have)) {
  1723. len = left > have ? have : left;
  1724. last = flush === Z_FINISH$1 && s.strm.avail_in === 0 &&
  1725. len === left ? 1 : 0;
  1726. _tr_stored_block(s, s.block_start, len, last);
  1727. s.block_start += len;
  1728. flush_pending(s.strm);
  1729. }
  1730. /* We've done all we can with the available input and output. */
  1731. return last ? BS_FINISH_STARTED : BS_NEED_MORE;
  1732. };
  1733. /* ===========================================================================
  1734. * Compress as much as possible from the input stream, return the current
  1735. * block state.
  1736. * This function does not perform lazy evaluation of matches and inserts
  1737. * new strings in the dictionary only for unmatched strings or for short
  1738. * matches. It is used only for the fast compression options.
  1739. */
  1740. const deflate_fast = (s, flush) => {
  1741. let hash_head; /* head of the hash chain */
  1742. let bflush; /* set if current block must be flushed */
  1743. for (;;) {
  1744. /* Make sure that we always have enough lookahead, except
  1745. * at the end of the input file. We need MAX_MATCH bytes
  1746. * for the next match, plus MIN_MATCH bytes to insert the
  1747. * string following the next match.
  1748. */
  1749. if (s.lookahead < MIN_LOOKAHEAD) {
  1750. fill_window(s);
  1751. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) {
  1752. return BS_NEED_MORE;
  1753. }
  1754. if (s.lookahead === 0) {
  1755. break; /* flush the current block */
  1756. }
  1757. }
  1758. /* Insert the string window[strstart .. strstart+2] in the
  1759. * dictionary, and set hash_head to the head of the hash chain:
  1760. */
  1761. hash_head = 0/*NIL*/;
  1762. if (s.lookahead >= MIN_MATCH) {
  1763. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1764. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1765. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1766. s.head[s.ins_h] = s.strstart;
  1767. /***/
  1768. }
  1769. /* Find the longest match, discarding those <= prev_length.
  1770. * At this point we have always match_length < MIN_MATCH
  1771. */
  1772. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  1773. /* To simplify the code, we prevent matches with the string
  1774. * of window index 0 (in particular we have to avoid a match
  1775. * of the string with itself at the start of the input file).
  1776. */
  1777. s.match_length = longest_match(s, hash_head);
  1778. /* longest_match() sets match_start */
  1779. }
  1780. if (s.match_length >= MIN_MATCH) {
  1781. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  1782. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  1783. s.match_length - MIN_MATCH, bflush); ***/
  1784. bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  1785. s.lookahead -= s.match_length;
  1786. /* Insert new strings in the hash table only if the match length
  1787. * is not too large. This saves time but degrades compression.
  1788. */
  1789. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  1790. s.match_length--; /* string at strstart already in table */
  1791. do {
  1792. s.strstart++;
  1793. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1794. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1795. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1796. s.head[s.ins_h] = s.strstart;
  1797. /***/
  1798. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1799. * always MIN_MATCH bytes ahead.
  1800. */
  1801. } while (--s.match_length !== 0);
  1802. s.strstart++;
  1803. } else
  1804. {
  1805. s.strstart += s.match_length;
  1806. s.match_length = 0;
  1807. s.ins_h = s.window[s.strstart];
  1808. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  1809. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);
  1810. //#if MIN_MATCH != 3
  1811. // Call UPDATE_HASH() MIN_MATCH-3 more times
  1812. //#endif
  1813. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1814. * matter since it will be recomputed at next deflate call.
  1815. */
  1816. }
  1817. } else {
  1818. /* No match, output a literal byte */
  1819. //Tracevv((stderr,"%c", s.window[s.strstart]));
  1820. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  1821. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  1822. s.lookahead--;
  1823. s.strstart++;
  1824. }
  1825. if (bflush) {
  1826. /*** FLUSH_BLOCK(s, 0); ***/
  1827. flush_block_only(s, false);
  1828. if (s.strm.avail_out === 0) {
  1829. return BS_NEED_MORE;
  1830. }
  1831. /***/
  1832. }
  1833. }
  1834. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  1835. if (flush === Z_FINISH$1) {
  1836. /*** FLUSH_BLOCK(s, 1); ***/
  1837. flush_block_only(s, true);
  1838. if (s.strm.avail_out === 0) {
  1839. return BS_FINISH_STARTED;
  1840. }
  1841. /***/
  1842. return BS_FINISH_DONE;
  1843. }
  1844. if (s.sym_next) {
  1845. /*** FLUSH_BLOCK(s, 0); ***/
  1846. flush_block_only(s, false);
  1847. if (s.strm.avail_out === 0) {
  1848. return BS_NEED_MORE;
  1849. }
  1850. /***/
  1851. }
  1852. return BS_BLOCK_DONE;
  1853. };
  1854. /* ===========================================================================
  1855. * Same as above, but achieves better compression. We use a lazy
  1856. * evaluation for matches: a match is finally adopted only if there is
  1857. * no better match at the next window position.
  1858. */
  1859. const deflate_slow = (s, flush) => {
  1860. let hash_head; /* head of hash chain */
  1861. let bflush; /* set if current block must be flushed */
  1862. let max_insert;
  1863. /* Process the input block. */
  1864. for (;;) {
  1865. /* Make sure that we always have enough lookahead, except
  1866. * at the end of the input file. We need MAX_MATCH bytes
  1867. * for the next match, plus MIN_MATCH bytes to insert the
  1868. * string following the next match.
  1869. */
  1870. if (s.lookahead < MIN_LOOKAHEAD) {
  1871. fill_window(s);
  1872. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) {
  1873. return BS_NEED_MORE;
  1874. }
  1875. if (s.lookahead === 0) { break; } /* flush the current block */
  1876. }
  1877. /* Insert the string window[strstart .. strstart+2] in the
  1878. * dictionary, and set hash_head to the head of the hash chain:
  1879. */
  1880. hash_head = 0/*NIL*/;
  1881. if (s.lookahead >= MIN_MATCH) {
  1882. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1883. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1884. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1885. s.head[s.ins_h] = s.strstart;
  1886. /***/
  1887. }
  1888. /* Find the longest match, discarding those <= prev_length.
  1889. */
  1890. s.prev_length = s.match_length;
  1891. s.prev_match = s.match_start;
  1892. s.match_length = MIN_MATCH - 1;
  1893. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  1894. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  1895. /* To simplify the code, we prevent matches with the string
  1896. * of window index 0 (in particular we have to avoid a match
  1897. * of the string with itself at the start of the input file).
  1898. */
  1899. s.match_length = longest_match(s, hash_head);
  1900. /* longest_match() sets match_start */
  1901. if (s.match_length <= 5 &&
  1902. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  1903. /* If prev_match is also MIN_MATCH, match_start is garbage
  1904. * but we will ignore the current match anyway.
  1905. */
  1906. s.match_length = MIN_MATCH - 1;
  1907. }
  1908. }
  1909. /* If there was a match at the previous step and the current
  1910. * match is not better, output the previous match:
  1911. */
  1912. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  1913. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  1914. /* Do not insert strings in hash table beyond this. */
  1915. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  1916. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  1917. s.prev_length - MIN_MATCH, bflush);***/
  1918. bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  1919. /* Insert in hash table all strings up to the end of the match.
  1920. * strstart-1 and strstart are already inserted. If there is not
  1921. * enough lookahead, the last two strings are not inserted in
  1922. * the hash table.
  1923. */
  1924. s.lookahead -= s.prev_length - 1;
  1925. s.prev_length -= 2;
  1926. do {
  1927. if (++s.strstart <= max_insert) {
  1928. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  1929. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  1930. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  1931. s.head[s.ins_h] = s.strstart;
  1932. /***/
  1933. }
  1934. } while (--s.prev_length !== 0);
  1935. s.match_available = 0;
  1936. s.match_length = MIN_MATCH - 1;
  1937. s.strstart++;
  1938. if (bflush) {
  1939. /*** FLUSH_BLOCK(s, 0); ***/
  1940. flush_block_only(s, false);
  1941. if (s.strm.avail_out === 0) {
  1942. return BS_NEED_MORE;
  1943. }
  1944. /***/
  1945. }
  1946. } else if (s.match_available) {
  1947. /* If there was no match at the previous position, output a
  1948. * single literal. If there was a match but the current match
  1949. * is longer, truncate the previous match to a single literal.
  1950. */
  1951. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1952. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  1953. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  1954. if (bflush) {
  1955. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  1956. flush_block_only(s, false);
  1957. /***/
  1958. }
  1959. s.strstart++;
  1960. s.lookahead--;
  1961. if (s.strm.avail_out === 0) {
  1962. return BS_NEED_MORE;
  1963. }
  1964. } else {
  1965. /* There is no previous match to compare with, wait for
  1966. * the next step to decide.
  1967. */
  1968. s.match_available = 1;
  1969. s.strstart++;
  1970. s.lookahead--;
  1971. }
  1972. }
  1973. //Assert (flush != Z_NO_FLUSH, "no flush?");
  1974. if (s.match_available) {
  1975. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1976. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  1977. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  1978. s.match_available = 0;
  1979. }
  1980. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  1981. if (flush === Z_FINISH$1) {
  1982. /*** FLUSH_BLOCK(s, 1); ***/
  1983. flush_block_only(s, true);
  1984. if (s.strm.avail_out === 0) {
  1985. return BS_FINISH_STARTED;
  1986. }
  1987. /***/
  1988. return BS_FINISH_DONE;
  1989. }
  1990. if (s.sym_next) {
  1991. /*** FLUSH_BLOCK(s, 0); ***/
  1992. flush_block_only(s, false);
  1993. if (s.strm.avail_out === 0) {
  1994. return BS_NEED_MORE;
  1995. }
  1996. /***/
  1997. }
  1998. return BS_BLOCK_DONE;
  1999. };
  2000. /* ===========================================================================
  2001. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  2002. * one. Do not maintain a hash table. (It will be regenerated if this run of
  2003. * deflate switches away from Z_RLE.)
  2004. */
  2005. const deflate_rle = (s, flush) => {
  2006. let bflush; /* set if current block must be flushed */
  2007. let prev; /* byte at distance one to match */
  2008. let scan, strend; /* scan goes up to strend for length of run */
  2009. const _win = s.window;
  2010. for (;;) {
  2011. /* Make sure that we always have enough lookahead, except
  2012. * at the end of the input file. We need MAX_MATCH bytes
  2013. * for the longest run, plus one for the unrolled loop.
  2014. */
  2015. if (s.lookahead <= MAX_MATCH) {
  2016. fill_window(s);
  2017. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$1) {
  2018. return BS_NEED_MORE;
  2019. }
  2020. if (s.lookahead === 0) { break; } /* flush the current block */
  2021. }
  2022. /* See how many times the previous byte repeats */
  2023. s.match_length = 0;
  2024. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  2025. scan = s.strstart - 1;
  2026. prev = _win[scan];
  2027. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  2028. strend = s.strstart + MAX_MATCH;
  2029. do {
  2030. /*jshint noempty:false*/
  2031. } while (prev === _win[++scan] && prev === _win[++scan] &&
  2032. prev === _win[++scan] && prev === _win[++scan] &&
  2033. prev === _win[++scan] && prev === _win[++scan] &&
  2034. prev === _win[++scan] && prev === _win[++scan] &&
  2035. scan < strend);
  2036. s.match_length = MAX_MATCH - (strend - scan);
  2037. if (s.match_length > s.lookahead) {
  2038. s.match_length = s.lookahead;
  2039. }
  2040. }
  2041. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  2042. }
  2043. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  2044. if (s.match_length >= MIN_MATCH) {
  2045. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  2046. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  2047. bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
  2048. s.lookahead -= s.match_length;
  2049. s.strstart += s.match_length;
  2050. s.match_length = 0;
  2051. } else {
  2052. /* No match, output a literal byte */
  2053. //Tracevv((stderr,"%c", s->window[s->strstart]));
  2054. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  2055. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  2056. s.lookahead--;
  2057. s.strstart++;
  2058. }
  2059. if (bflush) {
  2060. /*** FLUSH_BLOCK(s, 0); ***/
  2061. flush_block_only(s, false);
  2062. if (s.strm.avail_out === 0) {
  2063. return BS_NEED_MORE;
  2064. }
  2065. /***/
  2066. }
  2067. }
  2068. s.insert = 0;
  2069. if (flush === Z_FINISH$1) {
  2070. /*** FLUSH_BLOCK(s, 1); ***/
  2071. flush_block_only(s, true);
  2072. if (s.strm.avail_out === 0) {
  2073. return BS_FINISH_STARTED;
  2074. }
  2075. /***/
  2076. return BS_FINISH_DONE;
  2077. }
  2078. if (s.sym_next) {
  2079. /*** FLUSH_BLOCK(s, 0); ***/
  2080. flush_block_only(s, false);
  2081. if (s.strm.avail_out === 0) {
  2082. return BS_NEED_MORE;
  2083. }
  2084. /***/
  2085. }
  2086. return BS_BLOCK_DONE;
  2087. };
  2088. /* ===========================================================================
  2089. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  2090. * (It will be regenerated if this run of deflate switches away from Huffman.)
  2091. */
  2092. const deflate_huff = (s, flush) => {
  2093. let bflush; /* set if current block must be flushed */
  2094. for (;;) {
  2095. /* Make sure that we have a literal to write. */
  2096. if (s.lookahead === 0) {
  2097. fill_window(s);
  2098. if (s.lookahead === 0) {
  2099. if (flush === Z_NO_FLUSH$1) {
  2100. return BS_NEED_MORE;
  2101. }
  2102. break; /* flush the current block */
  2103. }
  2104. }
  2105. /* Output a literal byte */
  2106. s.match_length = 0;
  2107. //Tracevv((stderr,"%c", s->window[s->strstart]));
  2108. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  2109. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  2110. s.lookahead--;
  2111. s.strstart++;
  2112. if (bflush) {
  2113. /*** FLUSH_BLOCK(s, 0); ***/
  2114. flush_block_only(s, false);
  2115. if (s.strm.avail_out === 0) {
  2116. return BS_NEED_MORE;
  2117. }
  2118. /***/
  2119. }
  2120. }
  2121. s.insert = 0;
  2122. if (flush === Z_FINISH$1) {
  2123. /*** FLUSH_BLOCK(s, 1); ***/
  2124. flush_block_only(s, true);
  2125. if (s.strm.avail_out === 0) {
  2126. return BS_FINISH_STARTED;
  2127. }
  2128. /***/
  2129. return BS_FINISH_DONE;
  2130. }
  2131. if (s.sym_next) {
  2132. /*** FLUSH_BLOCK(s, 0); ***/
  2133. flush_block_only(s, false);
  2134. if (s.strm.avail_out === 0) {
  2135. return BS_NEED_MORE;
  2136. }
  2137. /***/
  2138. }
  2139. return BS_BLOCK_DONE;
  2140. };
  2141. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  2142. * the desired pack level (0..9). The values given below have been tuned to
  2143. * exclude worst case performance for pathological files. Better values may be
  2144. * found for specific files.
  2145. */
  2146. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  2147. this.good_length = good_length;
  2148. this.max_lazy = max_lazy;
  2149. this.nice_length = nice_length;
  2150. this.max_chain = max_chain;
  2151. this.func = func;
  2152. }
  2153. const configuration_table = [
  2154. /* good lazy nice chain */
  2155. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  2156. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  2157. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  2158. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  2159. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  2160. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  2161. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  2162. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  2163. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  2164. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  2165. ];
  2166. /* ===========================================================================
  2167. * Initialize the "longest match" routines for a new zlib stream
  2168. */
  2169. const lm_init = (s) => {
  2170. s.window_size = 2 * s.w_size;
  2171. /*** CLEAR_HASH(s); ***/
  2172. zero(s.head); // Fill with NIL (= 0);
  2173. /* Set the default configuration parameters:
  2174. */
  2175. s.max_lazy_match = configuration_table[s.level].max_lazy;
  2176. s.good_match = configuration_table[s.level].good_length;
  2177. s.nice_match = configuration_table[s.level].nice_length;
  2178. s.max_chain_length = configuration_table[s.level].max_chain;
  2179. s.strstart = 0;
  2180. s.block_start = 0;
  2181. s.lookahead = 0;
  2182. s.insert = 0;
  2183. s.match_length = s.prev_length = MIN_MATCH - 1;
  2184. s.match_available = 0;
  2185. s.ins_h = 0;
  2186. };
  2187. function DeflateState() {
  2188. this.strm = null; /* pointer back to this zlib stream */
  2189. this.status = 0; /* as the name implies */
  2190. this.pending_buf = null; /* output still pending */
  2191. this.pending_buf_size = 0; /* size of pending_buf */
  2192. this.pending_out = 0; /* next pending byte to output to the stream */
  2193. this.pending = 0; /* nb of bytes in the pending buffer */
  2194. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  2195. this.gzhead = null; /* gzip header information to write */
  2196. this.gzindex = 0; /* where in extra, name, or comment */
  2197. this.method = Z_DEFLATED$1; /* can only be DEFLATED */
  2198. this.last_flush = -1; /* value of flush param for previous deflate call */
  2199. this.w_size = 0; /* LZ77 window size (32K by default) */
  2200. this.w_bits = 0; /* log2(w_size) (8..16) */
  2201. this.w_mask = 0; /* w_size - 1 */
  2202. this.window = null;
  2203. /* Sliding window. Input bytes are read into the second half of the window,
  2204. * and move to the first half later to keep a dictionary of at least wSize
  2205. * bytes. With this organization, matches are limited to a distance of
  2206. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  2207. * performed with a length multiple of the block size.
  2208. */
  2209. this.window_size = 0;
  2210. /* Actual size of window: 2*wSize, except when the user input buffer
  2211. * is directly used as sliding window.
  2212. */
  2213. this.prev = null;
  2214. /* Link to older string with same hash index. To limit the size of this
  2215. * array to 64K, this link is maintained only for the last 32K strings.
  2216. * An index in this array is thus a window index modulo 32K.
  2217. */
  2218. this.head = null; /* Heads of the hash chains or NIL. */
  2219. this.ins_h = 0; /* hash index of string to be inserted */
  2220. this.hash_size = 0; /* number of elements in hash table */
  2221. this.hash_bits = 0; /* log2(hash_size) */
  2222. this.hash_mask = 0; /* hash_size-1 */
  2223. this.hash_shift = 0;
  2224. /* Number of bits by which ins_h must be shifted at each input
  2225. * step. It must be such that after MIN_MATCH steps, the oldest
  2226. * byte no longer takes part in the hash key, that is:
  2227. * hash_shift * MIN_MATCH >= hash_bits
  2228. */
  2229. this.block_start = 0;
  2230. /* Window position at the beginning of the current output block. Gets
  2231. * negative when the window is moved backwards.
  2232. */
  2233. this.match_length = 0; /* length of best match */
  2234. this.prev_match = 0; /* previous match */
  2235. this.match_available = 0; /* set if previous match exists */
  2236. this.strstart = 0; /* start of string to insert */
  2237. this.match_start = 0; /* start of matching string */
  2238. this.lookahead = 0; /* number of valid bytes ahead in window */
  2239. this.prev_length = 0;
  2240. /* Length of the best match at previous step. Matches not greater than this
  2241. * are discarded. This is used in the lazy match evaluation.
  2242. */
  2243. this.max_chain_length = 0;
  2244. /* To speed up deflation, hash chains are never searched beyond this
  2245. * length. A higher limit improves compression ratio but degrades the
  2246. * speed.
  2247. */
  2248. this.max_lazy_match = 0;
  2249. /* Attempt to find a better match only when the current match is strictly
  2250. * smaller than this value. This mechanism is used only for compression
  2251. * levels >= 4.
  2252. */
  2253. // That's alias to max_lazy_match, don't use directly
  2254. //this.max_insert_length = 0;
  2255. /* Insert new strings in the hash table only if the match length is not
  2256. * greater than this length. This saves time but degrades compression.
  2257. * max_insert_length is used only for compression levels <= 3.
  2258. */
  2259. this.level = 0; /* compression level (1..9) */
  2260. this.strategy = 0; /* favor or force Huffman coding*/
  2261. this.good_match = 0;
  2262. /* Use a faster search when the previous match is longer than this */
  2263. this.nice_match = 0; /* Stop searching when current match exceeds this */
  2264. /* used by trees.c: */
  2265. /* Didn't use ct_data typedef below to suppress compiler warning */
  2266. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  2267. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  2268. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  2269. // Use flat array of DOUBLE size, with interleaved fata,
  2270. // because JS does not support effective
  2271. this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);
  2272. this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);
  2273. this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);
  2274. zero(this.dyn_ltree);
  2275. zero(this.dyn_dtree);
  2276. zero(this.bl_tree);
  2277. this.l_desc = null; /* desc. for literal tree */
  2278. this.d_desc = null; /* desc. for distance tree */
  2279. this.bl_desc = null; /* desc. for bit length tree */
  2280. //ush bl_count[MAX_BITS+1];
  2281. this.bl_count = new Uint16Array(MAX_BITS + 1);
  2282. /* number of codes at each bit length for an optimal tree */
  2283. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  2284. this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  2285. zero(this.heap);
  2286. this.heap_len = 0; /* number of elements in the heap */
  2287. this.heap_max = 0; /* element of largest frequency */
  2288. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  2289. * The same heap array is used to build all trees.
  2290. */
  2291. this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  2292. zero(this.depth);
  2293. /* Depth of each subtree used as tie breaker for trees of equal frequency
  2294. */
  2295. this.sym_buf = 0; /* buffer for distances and literals/lengths */
  2296. this.lit_bufsize = 0;
  2297. /* Size of match buffer for literals/lengths. There are 4 reasons for
  2298. * limiting lit_bufsize to 64K:
  2299. * - frequencies can be kept in 16 bit counters
  2300. * - if compression is not successful for the first block, all input
  2301. * data is still in the window so we can still emit a stored block even
  2302. * when input comes from standard input. (This can also be done for
  2303. * all blocks if lit_bufsize is not greater than 32K.)
  2304. * - if compression is not successful for a file smaller than 64K, we can
  2305. * even emit a stored file instead of a stored block (saving 5 bytes).
  2306. * This is applicable only for zip (not gzip or zlib).
  2307. * - creating new Huffman trees less frequently may not provide fast
  2308. * adaptation to changes in the input data statistics. (Take for
  2309. * example a binary file with poorly compressible code followed by
  2310. * a highly compressible string table.) Smaller buffer sizes give
  2311. * fast adaptation but have of course the overhead of transmitting
  2312. * trees more frequently.
  2313. * - I can't count above 4
  2314. */
  2315. this.sym_next = 0; /* running index in sym_buf */
  2316. this.sym_end = 0; /* symbol table full when sym_next reaches this */
  2317. this.opt_len = 0; /* bit length of current block with optimal trees */
  2318. this.static_len = 0; /* bit length of current block with static trees */
  2319. this.matches = 0; /* number of string matches in current block */
  2320. this.insert = 0; /* bytes at end of window left to insert */
  2321. this.bi_buf = 0;
  2322. /* Output buffer. bits are inserted starting at the bottom (least
  2323. * significant bits).
  2324. */
  2325. this.bi_valid = 0;
  2326. /* Number of valid bits in bi_buf. All bits above the last valid bit
  2327. * are always zero.
  2328. */
  2329. // Used for window memory init. We safely ignore it for JS. That makes
  2330. // sense only for pointers and memory check tools.
  2331. //this.high_water = 0;
  2332. /* High water mark offset in window for initialized bytes -- bytes above
  2333. * this are set to zero in order to avoid memory check warnings when
  2334. * longest match routines access bytes past the input. This is then
  2335. * updated to the new high water mark.
  2336. */
  2337. }
  2338. /* =========================================================================
  2339. * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
  2340. */
  2341. const deflateStateCheck = (strm) => {
  2342. if (!strm) {
  2343. return 1;
  2344. }
  2345. const s = strm.state;
  2346. if (!s || s.strm !== strm || (s.status !== INIT_STATE &&
  2347. //#ifdef GZIP
  2348. s.status !== GZIP_STATE &&
  2349. //#endif
  2350. s.status !== EXTRA_STATE &&
  2351. s.status !== NAME_STATE &&
  2352. s.status !== COMMENT_STATE &&
  2353. s.status !== HCRC_STATE &&
  2354. s.status !== BUSY_STATE &&
  2355. s.status !== FINISH_STATE)) {
  2356. return 1;
  2357. }
  2358. return 0;
  2359. };
  2360. const deflateResetKeep = (strm) => {
  2361. if (deflateStateCheck(strm)) {
  2362. return err(strm, Z_STREAM_ERROR);
  2363. }
  2364. strm.total_in = strm.total_out = 0;
  2365. strm.data_type = Z_UNKNOWN;
  2366. const s = strm.state;
  2367. s.pending = 0;
  2368. s.pending_out = 0;
  2369. if (s.wrap < 0) {
  2370. s.wrap = -s.wrap;
  2371. /* was made negative by deflate(..., Z_FINISH); */
  2372. }
  2373. s.status =
  2374. //#ifdef GZIP
  2375. s.wrap === 2 ? GZIP_STATE :
  2376. //#endif
  2377. s.wrap ? INIT_STATE : BUSY_STATE;
  2378. strm.adler = (s.wrap === 2) ?
  2379. 0 // crc32(0, Z_NULL, 0)
  2380. :
  2381. 1; // adler32(0, Z_NULL, 0)
  2382. s.last_flush = -2;
  2383. _tr_init(s);
  2384. return Z_OK$1;
  2385. };
  2386. const deflateReset = (strm) => {
  2387. const ret = deflateResetKeep(strm);
  2388. if (ret === Z_OK$1) {
  2389. lm_init(strm.state);
  2390. }
  2391. return ret;
  2392. };
  2393. const deflateSetHeader = (strm, head) => {
  2394. if (deflateStateCheck(strm) || strm.state.wrap !== 2) {
  2395. return Z_STREAM_ERROR;
  2396. }
  2397. strm.state.gzhead = head;
  2398. return Z_OK$1;
  2399. };
  2400. const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
  2401. if (!strm) { // === Z_NULL
  2402. return Z_STREAM_ERROR;
  2403. }
  2404. let wrap = 1;
  2405. if (level === Z_DEFAULT_COMPRESSION$1) {
  2406. level = 6;
  2407. }
  2408. if (windowBits < 0) { /* suppress zlib wrapper */
  2409. wrap = 0;
  2410. windowBits = -windowBits;
  2411. }
  2412. else if (windowBits > 15) {
  2413. wrap = 2; /* write gzip wrapper instead */
  2414. windowBits -= 16;
  2415. }
  2416. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$1 ||
  2417. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  2418. strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {
  2419. return err(strm, Z_STREAM_ERROR);
  2420. }
  2421. if (windowBits === 8) {
  2422. windowBits = 9;
  2423. }
  2424. /* until 256-byte window bug fixed */
  2425. const s = new DeflateState();
  2426. strm.state = s;
  2427. s.strm = strm;
  2428. s.status = INIT_STATE; /* to pass state test in deflateReset() */
  2429. s.wrap = wrap;
  2430. s.gzhead = null;
  2431. s.w_bits = windowBits;
  2432. s.w_size = 1 << s.w_bits;
  2433. s.w_mask = s.w_size - 1;
  2434. s.hash_bits = memLevel + 7;
  2435. s.hash_size = 1 << s.hash_bits;
  2436. s.hash_mask = s.hash_size - 1;
  2437. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  2438. s.window = new Uint8Array(s.w_size * 2);
  2439. s.head = new Uint16Array(s.hash_size);
  2440. s.prev = new Uint16Array(s.w_size);
  2441. // Don't need mem init magic for JS.
  2442. //s.high_water = 0; /* nothing written to s->window yet */
  2443. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  2444. /* We overlay pending_buf and sym_buf. This works since the average size
  2445. * for length/distance pairs over any compressed block is assured to be 31
  2446. * bits or less.
  2447. *
  2448. * Analysis: The longest fixed codes are a length code of 8 bits plus 5
  2449. * extra bits, for lengths 131 to 257. The longest fixed distance codes are
  2450. * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
  2451. * possible fixed-codes length/distance pair is then 31 bits total.
  2452. *
  2453. * sym_buf starts one-fourth of the way into pending_buf. So there are
  2454. * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
  2455. * in sym_buf is three bytes -- two for the distance and one for the
  2456. * literal/length. As each symbol is consumed, the pointer to the next
  2457. * sym_buf value to read moves forward three bytes. From that symbol, up to
  2458. * 31 bits are written to pending_buf. The closest the written pending_buf
  2459. * bits gets to the next sym_buf symbol to read is just before the last
  2460. * code is written. At that time, 31*(n-2) bits have been written, just
  2461. * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
  2462. * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
  2463. * symbols are written.) The closest the writing gets to what is unread is
  2464. * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
  2465. * can range from 128 to 32768.
  2466. *
  2467. * Therefore, at a minimum, there are 142 bits of space between what is
  2468. * written and what is read in the overlain buffers, so the symbols cannot
  2469. * be overwritten by the compressed data. That space is actually 139 bits,
  2470. * due to the three-bit fixed-code block header.
  2471. *
  2472. * That covers the case where either Z_FIXED is specified, forcing fixed
  2473. * codes, or when the use of fixed codes is chosen, because that choice
  2474. * results in a smaller compressed block than dynamic codes. That latter
  2475. * condition then assures that the above analysis also covers all dynamic
  2476. * blocks. A dynamic-code block will only be chosen to be emitted if it has
  2477. * fewer bits than a fixed-code block would for the same set of symbols.
  2478. * Therefore its average symbol length is assured to be less than 31. So
  2479. * the compressed data for a dynamic block also cannot overwrite the
  2480. * symbols from which it is being constructed.
  2481. */
  2482. s.pending_buf_size = s.lit_bufsize * 4;
  2483. s.pending_buf = new Uint8Array(s.pending_buf_size);
  2484. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  2485. //s->sym_buf = s->pending_buf + s->lit_bufsize;
  2486. s.sym_buf = s.lit_bufsize;
  2487. //s->sym_end = (s->lit_bufsize - 1) * 3;
  2488. s.sym_end = (s.lit_bufsize - 1) * 3;
  2489. /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
  2490. * on 16 bit machines and because stored blocks are restricted to
  2491. * 64K-1 bytes.
  2492. */
  2493. s.level = level;
  2494. s.strategy = strategy;
  2495. s.method = method;
  2496. return deflateReset(strm);
  2497. };
  2498. const deflateInit = (strm, level) => {
  2499. return deflateInit2(strm, level, Z_DEFLATED$1, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);
  2500. };
  2501. /* ========================================================================= */
  2502. const deflate$1 = (strm, flush) => {
  2503. if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
  2504. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  2505. }
  2506. const s = strm.state;
  2507. if (!strm.output ||
  2508. (strm.avail_in !== 0 && !strm.input) ||
  2509. (s.status === FINISH_STATE && flush !== Z_FINISH$1)) {
  2510. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  2511. }
  2512. const old_flush = s.last_flush;
  2513. s.last_flush = flush;
  2514. /* Flush as much pending output as possible */
  2515. if (s.pending !== 0) {
  2516. flush_pending(strm);
  2517. if (strm.avail_out === 0) {
  2518. /* Since avail_out is 0, deflate will be called again with
  2519. * more output space, but possibly with both pending and
  2520. * avail_in equal to zero. There won't be anything to do,
  2521. * but this is not an error situation so make sure we
  2522. * return OK instead of BUF_ERROR at next call of deflate:
  2523. */
  2524. s.last_flush = -1;
  2525. return Z_OK$1;
  2526. }
  2527. /* Make sure there is something to do and avoid duplicate consecutive
  2528. * flushes. For repeated and useless calls with Z_FINISH, we keep
  2529. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  2530. */
  2531. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  2532. flush !== Z_FINISH$1) {
  2533. return err(strm, Z_BUF_ERROR);
  2534. }
  2535. /* User must not provide more input after the first FINISH: */
  2536. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  2537. return err(strm, Z_BUF_ERROR);
  2538. }
  2539. /* Write the header */
  2540. if (s.status === INIT_STATE && s.wrap === 0) {
  2541. s.status = BUSY_STATE;
  2542. }
  2543. if (s.status === INIT_STATE) {
  2544. /* zlib header */
  2545. let header = (Z_DEFLATED$1 + ((s.w_bits - 8) << 4)) << 8;
  2546. let level_flags = -1;
  2547. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  2548. level_flags = 0;
  2549. } else if (s.level < 6) {
  2550. level_flags = 1;
  2551. } else if (s.level === 6) {
  2552. level_flags = 2;
  2553. } else {
  2554. level_flags = 3;
  2555. }
  2556. header |= (level_flags << 6);
  2557. if (s.strstart !== 0) { header |= PRESET_DICT; }
  2558. header += 31 - (header % 31);
  2559. putShortMSB(s, header);
  2560. /* Save the adler32 of the preset dictionary: */
  2561. if (s.strstart !== 0) {
  2562. putShortMSB(s, strm.adler >>> 16);
  2563. putShortMSB(s, strm.adler & 0xffff);
  2564. }
  2565. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  2566. s.status = BUSY_STATE;
  2567. /* Compression must start with an empty pending buffer */
  2568. flush_pending(strm);
  2569. if (s.pending !== 0) {
  2570. s.last_flush = -1;
  2571. return Z_OK$1;
  2572. }
  2573. }
  2574. //#ifdef GZIP
  2575. if (s.status === GZIP_STATE) {
  2576. /* gzip header */
  2577. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  2578. put_byte(s, 31);
  2579. put_byte(s, 139);
  2580. put_byte(s, 8);
  2581. if (!s.gzhead) { // s->gzhead == Z_NULL
  2582. put_byte(s, 0);
  2583. put_byte(s, 0);
  2584. put_byte(s, 0);
  2585. put_byte(s, 0);
  2586. put_byte(s, 0);
  2587. put_byte(s, s.level === 9 ? 2 :
  2588. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  2589. 4 : 0));
  2590. put_byte(s, OS_CODE);
  2591. s.status = BUSY_STATE;
  2592. /* Compression must start with an empty pending buffer */
  2593. flush_pending(strm);
  2594. if (s.pending !== 0) {
  2595. s.last_flush = -1;
  2596. return Z_OK$1;
  2597. }
  2598. }
  2599. else {
  2600. put_byte(s, (s.gzhead.text ? 1 : 0) +
  2601. (s.gzhead.hcrc ? 2 : 0) +
  2602. (!s.gzhead.extra ? 0 : 4) +
  2603. (!s.gzhead.name ? 0 : 8) +
  2604. (!s.gzhead.comment ? 0 : 16)
  2605. );
  2606. put_byte(s, s.gzhead.time & 0xff);
  2607. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  2608. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  2609. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  2610. put_byte(s, s.level === 9 ? 2 :
  2611. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  2612. 4 : 0));
  2613. put_byte(s, s.gzhead.os & 0xff);
  2614. if (s.gzhead.extra && s.gzhead.extra.length) {
  2615. put_byte(s, s.gzhead.extra.length & 0xff);
  2616. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  2617. }
  2618. if (s.gzhead.hcrc) {
  2619. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
  2620. }
  2621. s.gzindex = 0;
  2622. s.status = EXTRA_STATE;
  2623. }
  2624. }
  2625. if (s.status === EXTRA_STATE) {
  2626. if (s.gzhead.extra/* != Z_NULL*/) {
  2627. let beg = s.pending; /* start of bytes to update crc */
  2628. let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;
  2629. while (s.pending + left > s.pending_buf_size) {
  2630. let copy = s.pending_buf_size - s.pending;
  2631. // zmemcpy(s.pending_buf + s.pending,
  2632. // s.gzhead.extra + s.gzindex, copy);
  2633. s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);
  2634. s.pending = s.pending_buf_size;
  2635. //--- HCRC_UPDATE(beg) ---//
  2636. if (s.gzhead.hcrc && s.pending > beg) {
  2637. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2638. }
  2639. //---//
  2640. s.gzindex += copy;
  2641. flush_pending(strm);
  2642. if (s.pending !== 0) {
  2643. s.last_flush = -1;
  2644. return Z_OK$1;
  2645. }
  2646. beg = 0;
  2647. left -= copy;
  2648. }
  2649. // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility
  2650. // TypedArray.slice and TypedArray.from don't exist in IE10-IE11
  2651. let gzhead_extra = new Uint8Array(s.gzhead.extra);
  2652. // zmemcpy(s->pending_buf + s->pending,
  2653. // s->gzhead->extra + s->gzindex, left);
  2654. s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);
  2655. s.pending += left;
  2656. //--- HCRC_UPDATE(beg) ---//
  2657. if (s.gzhead.hcrc && s.pending > beg) {
  2658. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2659. }
  2660. //---//
  2661. s.gzindex = 0;
  2662. }
  2663. s.status = NAME_STATE;
  2664. }
  2665. if (s.status === NAME_STATE) {
  2666. if (s.gzhead.name/* != Z_NULL*/) {
  2667. let beg = s.pending; /* start of bytes to update crc */
  2668. let val;
  2669. do {
  2670. if (s.pending === s.pending_buf_size) {
  2671. //--- HCRC_UPDATE(beg) ---//
  2672. if (s.gzhead.hcrc && s.pending > beg) {
  2673. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2674. }
  2675. //---//
  2676. flush_pending(strm);
  2677. if (s.pending !== 0) {
  2678. s.last_flush = -1;
  2679. return Z_OK$1;
  2680. }
  2681. beg = 0;
  2682. }
  2683. // JS specific: little magic to add zero terminator to end of string
  2684. if (s.gzindex < s.gzhead.name.length) {
  2685. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  2686. } else {
  2687. val = 0;
  2688. }
  2689. put_byte(s, val);
  2690. } while (val !== 0);
  2691. //--- HCRC_UPDATE(beg) ---//
  2692. if (s.gzhead.hcrc && s.pending > beg) {
  2693. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2694. }
  2695. //---//
  2696. s.gzindex = 0;
  2697. }
  2698. s.status = COMMENT_STATE;
  2699. }
  2700. if (s.status === COMMENT_STATE) {
  2701. if (s.gzhead.comment/* != Z_NULL*/) {
  2702. let beg = s.pending; /* start of bytes to update crc */
  2703. let val;
  2704. do {
  2705. if (s.pending === s.pending_buf_size) {
  2706. //--- HCRC_UPDATE(beg) ---//
  2707. if (s.gzhead.hcrc && s.pending > beg) {
  2708. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2709. }
  2710. //---//
  2711. flush_pending(strm);
  2712. if (s.pending !== 0) {
  2713. s.last_flush = -1;
  2714. return Z_OK$1;
  2715. }
  2716. beg = 0;
  2717. }
  2718. // JS specific: little magic to add zero terminator to end of string
  2719. if (s.gzindex < s.gzhead.comment.length) {
  2720. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  2721. } else {
  2722. val = 0;
  2723. }
  2724. put_byte(s, val);
  2725. } while (val !== 0);
  2726. //--- HCRC_UPDATE(beg) ---//
  2727. if (s.gzhead.hcrc && s.pending > beg) {
  2728. strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
  2729. }
  2730. //---//
  2731. }
  2732. s.status = HCRC_STATE;
  2733. }
  2734. if (s.status === HCRC_STATE) {
  2735. if (s.gzhead.hcrc) {
  2736. if (s.pending + 2 > s.pending_buf_size) {
  2737. flush_pending(strm);
  2738. if (s.pending !== 0) {
  2739. s.last_flush = -1;
  2740. return Z_OK$1;
  2741. }
  2742. }
  2743. put_byte(s, strm.adler & 0xff);
  2744. put_byte(s, (strm.adler >> 8) & 0xff);
  2745. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  2746. }
  2747. s.status = BUSY_STATE;
  2748. /* Compression must start with an empty pending buffer */
  2749. flush_pending(strm);
  2750. if (s.pending !== 0) {
  2751. s.last_flush = -1;
  2752. return Z_OK$1;
  2753. }
  2754. }
  2755. //#endif
  2756. /* Start a new block or continue the current one.
  2757. */
  2758. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  2759. (flush !== Z_NO_FLUSH$1 && s.status !== FINISH_STATE)) {
  2760. let bstate = s.level === 0 ? deflate_stored(s, flush) :
  2761. s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
  2762. s.strategy === Z_RLE ? deflate_rle(s, flush) :
  2763. configuration_table[s.level].func(s, flush);
  2764. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  2765. s.status = FINISH_STATE;
  2766. }
  2767. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  2768. if (strm.avail_out === 0) {
  2769. s.last_flush = -1;
  2770. /* avoid BUF_ERROR next call, see above */
  2771. }
  2772. return Z_OK$1;
  2773. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  2774. * of deflate should use the same flush parameter to make sure
  2775. * that the flush is complete. So we don't have to output an
  2776. * empty block here, this will be done at next call. This also
  2777. * ensures that for a very small output buffer, we emit at most
  2778. * one empty block.
  2779. */
  2780. }
  2781. if (bstate === BS_BLOCK_DONE) {
  2782. if (flush === Z_PARTIAL_FLUSH) {
  2783. _tr_align(s);
  2784. }
  2785. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  2786. _tr_stored_block(s, 0, 0, false);
  2787. /* For a full flush, this empty block will be recognized
  2788. * as a special marker by inflate_sync().
  2789. */
  2790. if (flush === Z_FULL_FLUSH$1) {
  2791. /*** CLEAR_HASH(s); ***/ /* forget history */
  2792. zero(s.head); // Fill with NIL (= 0);
  2793. if (s.lookahead === 0) {
  2794. s.strstart = 0;
  2795. s.block_start = 0;
  2796. s.insert = 0;
  2797. }
  2798. }
  2799. }
  2800. flush_pending(strm);
  2801. if (strm.avail_out === 0) {
  2802. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  2803. return Z_OK$1;
  2804. }
  2805. }
  2806. }
  2807. if (flush !== Z_FINISH$1) { return Z_OK$1; }
  2808. if (s.wrap <= 0) { return Z_STREAM_END$1; }
  2809. /* Write the trailer */
  2810. if (s.wrap === 2) {
  2811. put_byte(s, strm.adler & 0xff);
  2812. put_byte(s, (strm.adler >> 8) & 0xff);
  2813. put_byte(s, (strm.adler >> 16) & 0xff);
  2814. put_byte(s, (strm.adler >> 24) & 0xff);
  2815. put_byte(s, strm.total_in & 0xff);
  2816. put_byte(s, (strm.total_in >> 8) & 0xff);
  2817. put_byte(s, (strm.total_in >> 16) & 0xff);
  2818. put_byte(s, (strm.total_in >> 24) & 0xff);
  2819. }
  2820. else
  2821. {
  2822. putShortMSB(s, strm.adler >>> 16);
  2823. putShortMSB(s, strm.adler & 0xffff);
  2824. }
  2825. flush_pending(strm);
  2826. /* If avail_out is zero, the application will call deflate again
  2827. * to flush the rest.
  2828. */
  2829. if (s.wrap > 0) { s.wrap = -s.wrap; }
  2830. /* write the trailer only once! */
  2831. return s.pending !== 0 ? Z_OK$1 : Z_STREAM_END$1;
  2832. };
  2833. const deflateEnd = (strm) => {
  2834. if (deflateStateCheck(strm)) {
  2835. return Z_STREAM_ERROR;
  2836. }
  2837. const status = strm.state.status;
  2838. strm.state = null;
  2839. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK$1;
  2840. };
  2841. /* =========================================================================
  2842. * Initializes the compression dictionary from the given byte
  2843. * sequence without producing any compressed output.
  2844. */
  2845. const deflateSetDictionary = (strm, dictionary) => {
  2846. let dictLength = dictionary.length;
  2847. if (deflateStateCheck(strm)) {
  2848. return Z_STREAM_ERROR;
  2849. }
  2850. const s = strm.state;
  2851. const wrap = s.wrap;
  2852. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  2853. return Z_STREAM_ERROR;
  2854. }
  2855. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  2856. if (wrap === 1) {
  2857. /* adler32(strm->adler, dictionary, dictLength); */
  2858. strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
  2859. }
  2860. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  2861. /* if dictionary would fill window, just replace the history */
  2862. if (dictLength >= s.w_size) {
  2863. if (wrap === 0) { /* already empty otherwise */
  2864. /*** CLEAR_HASH(s); ***/
  2865. zero(s.head); // Fill with NIL (= 0);
  2866. s.strstart = 0;
  2867. s.block_start = 0;
  2868. s.insert = 0;
  2869. }
  2870. /* use the tail */
  2871. // dictionary = dictionary.slice(dictLength - s.w_size);
  2872. let tmpDict = new Uint8Array(s.w_size);
  2873. tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
  2874. dictionary = tmpDict;
  2875. dictLength = s.w_size;
  2876. }
  2877. /* insert dictionary into window and hash */
  2878. const avail = strm.avail_in;
  2879. const next = strm.next_in;
  2880. const input = strm.input;
  2881. strm.avail_in = dictLength;
  2882. strm.next_in = 0;
  2883. strm.input = dictionary;
  2884. fill_window(s);
  2885. while (s.lookahead >= MIN_MATCH) {
  2886. let str = s.strstart;
  2887. let n = s.lookahead - (MIN_MATCH - 1);
  2888. do {
  2889. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  2890. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  2891. s.prev[str & s.w_mask] = s.head[s.ins_h];
  2892. s.head[s.ins_h] = str;
  2893. str++;
  2894. } while (--n);
  2895. s.strstart = str;
  2896. s.lookahead = MIN_MATCH - 1;
  2897. fill_window(s);
  2898. }
  2899. s.strstart += s.lookahead;
  2900. s.block_start = s.strstart;
  2901. s.insert = s.lookahead;
  2902. s.lookahead = 0;
  2903. s.match_length = s.prev_length = MIN_MATCH - 1;
  2904. s.match_available = 0;
  2905. strm.next_in = next;
  2906. strm.input = input;
  2907. strm.avail_in = avail;
  2908. s.wrap = wrap;
  2909. return Z_OK$1;
  2910. };
  2911. var deflateInit_1 = deflateInit;
  2912. var deflateInit2_1 = deflateInit2;
  2913. var deflateReset_1 = deflateReset;
  2914. var deflateResetKeep_1 = deflateResetKeep;
  2915. var deflateSetHeader_1 = deflateSetHeader;
  2916. var deflate_2$1 = deflate$1;
  2917. var deflateEnd_1 = deflateEnd;
  2918. var deflateSetDictionary_1 = deflateSetDictionary;
  2919. var deflateInfo = 'pako deflate (from Nodeca project)';
  2920. /* Not implemented
  2921. module.exports.deflateBound = deflateBound;
  2922. module.exports.deflateCopy = deflateCopy;
  2923. module.exports.deflateGetDictionary = deflateGetDictionary;
  2924. module.exports.deflateParams = deflateParams;
  2925. module.exports.deflatePending = deflatePending;
  2926. module.exports.deflatePrime = deflatePrime;
  2927. module.exports.deflateTune = deflateTune;
  2928. */
  2929. var deflate_1$1 = {
  2930. deflateInit: deflateInit_1,
  2931. deflateInit2: deflateInit2_1,
  2932. deflateReset: deflateReset_1,
  2933. deflateResetKeep: deflateResetKeep_1,
  2934. deflateSetHeader: deflateSetHeader_1,
  2935. deflate: deflate_2$1,
  2936. deflateEnd: deflateEnd_1,
  2937. deflateSetDictionary: deflateSetDictionary_1,
  2938. deflateInfo: deflateInfo
  2939. };
  2940. const _has = (obj, key) => {
  2941. return Object.prototype.hasOwnProperty.call(obj, key);
  2942. };
  2943. var assign = function (obj /*from1, from2, from3, ...*/) {
  2944. const sources = Array.prototype.slice.call(arguments, 1);
  2945. while (sources.length) {
  2946. const source = sources.shift();
  2947. if (!source) { continue; }
  2948. if (typeof source !== 'object') {
  2949. throw new TypeError(source + 'must be non-object');
  2950. }
  2951. for (const p in source) {
  2952. if (_has(source, p)) {
  2953. obj[p] = source[p];
  2954. }
  2955. }
  2956. }
  2957. return obj;
  2958. };
  2959. // Join array of chunks to single array.
  2960. var flattenChunks = (chunks) => {
  2961. // calculate data length
  2962. let len = 0;
  2963. for (let i = 0, l = chunks.length; i < l; i++) {
  2964. len += chunks[i].length;
  2965. }
  2966. // join chunks
  2967. const result = new Uint8Array(len);
  2968. for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
  2969. let chunk = chunks[i];
  2970. result.set(chunk, pos);
  2971. pos += chunk.length;
  2972. }
  2973. return result;
  2974. };
  2975. var common = {
  2976. assign: assign,
  2977. flattenChunks: flattenChunks
  2978. };
  2979. // String encode/decode helpers
  2980. // Quick check if we can use fast array to bin string conversion
  2981. //
  2982. // - apply(Array) can fail on Android 2.2
  2983. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  2984. //
  2985. let STR_APPLY_UIA_OK = true;
  2986. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  2987. // Table with utf8 lengths (calculated by first byte of sequence)
  2988. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2989. // because max possible codepoint is 0x10ffff
  2990. const _utf8len = new Uint8Array(256);
  2991. for (let q = 0; q < 256; q++) {
  2992. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  2993. }
  2994. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  2995. // convert string to array (typed, when possible)
  2996. var string2buf = (str) => {
  2997. if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
  2998. return new TextEncoder().encode(str);
  2999. }
  3000. let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3001. // count binary size
  3002. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3003. c = str.charCodeAt(m_pos);
  3004. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  3005. c2 = str.charCodeAt(m_pos + 1);
  3006. if ((c2 & 0xfc00) === 0xdc00) {
  3007. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3008. m_pos++;
  3009. }
  3010. }
  3011. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3012. }
  3013. // allocate buffer
  3014. buf = new Uint8Array(buf_len);
  3015. // convert
  3016. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  3017. c = str.charCodeAt(m_pos);
  3018. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  3019. c2 = str.charCodeAt(m_pos + 1);
  3020. if ((c2 & 0xfc00) === 0xdc00) {
  3021. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3022. m_pos++;
  3023. }
  3024. }
  3025. if (c < 0x80) {
  3026. /* one byte */
  3027. buf[i++] = c;
  3028. } else if (c < 0x800) {
  3029. /* two bytes */
  3030. buf[i++] = 0xC0 | (c >>> 6);
  3031. buf[i++] = 0x80 | (c & 0x3f);
  3032. } else if (c < 0x10000) {
  3033. /* three bytes */
  3034. buf[i++] = 0xE0 | (c >>> 12);
  3035. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3036. buf[i++] = 0x80 | (c & 0x3f);
  3037. } else {
  3038. /* four bytes */
  3039. buf[i++] = 0xf0 | (c >>> 18);
  3040. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3041. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3042. buf[i++] = 0x80 | (c & 0x3f);
  3043. }
  3044. }
  3045. return buf;
  3046. };
  3047. // Helper
  3048. const buf2binstring = (buf, len) => {
  3049. // On Chrome, the arguments in a function call that are allowed is `65534`.
  3050. // If the length of the buffer is smaller than that, we can use this optimization,
  3051. // otherwise we will take a slower path.
  3052. if (len < 65534) {
  3053. if (buf.subarray && STR_APPLY_UIA_OK) {
  3054. return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
  3055. }
  3056. }
  3057. let result = '';
  3058. for (let i = 0; i < len; i++) {
  3059. result += String.fromCharCode(buf[i]);
  3060. }
  3061. return result;
  3062. };
  3063. // convert array to string
  3064. var buf2string = (buf, max) => {
  3065. const len = max || buf.length;
  3066. if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
  3067. return new TextDecoder().decode(buf.subarray(0, max));
  3068. }
  3069. let i, out;
  3070. // Reserve max possible length (2 words per char)
  3071. // NB: by unknown reasons, Array is significantly faster for
  3072. // String.fromCharCode.apply than Uint16Array.
  3073. const utf16buf = new Array(len * 2);
  3074. for (out = 0, i = 0; i < len;) {
  3075. let c = buf[i++];
  3076. // quick process ascii
  3077. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3078. let c_len = _utf8len[c];
  3079. // skip 5 & 6 byte codes
  3080. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  3081. // apply mask on first byte
  3082. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3083. // join the rest
  3084. while (c_len > 1 && i < len) {
  3085. c = (c << 6) | (buf[i++] & 0x3f);
  3086. c_len--;
  3087. }
  3088. // terminated by end of string?
  3089. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3090. if (c < 0x10000) {
  3091. utf16buf[out++] = c;
  3092. } else {
  3093. c -= 0x10000;
  3094. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3095. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3096. }
  3097. }
  3098. return buf2binstring(utf16buf, out);
  3099. };
  3100. // Calculate max possible position in utf8 buffer,
  3101. // that will not break sequence. If that's not possible
  3102. // - (very small limits) return max size as is.
  3103. //
  3104. // buf[] - utf8 bytes array
  3105. // max - length limit (mandatory);
  3106. var utf8border = (buf, max) => {
  3107. max = max || buf.length;
  3108. if (max > buf.length) { max = buf.length; }
  3109. // go back from last position, until start of sequence found
  3110. let pos = max - 1;
  3111. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3112. // Very small and broken sequence,
  3113. // return max, because we should return something anyway.
  3114. if (pos < 0) { return max; }
  3115. // If we came to start of buffer - that means buffer is too small,
  3116. // return max too.
  3117. if (pos === 0) { return max; }
  3118. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3119. };
  3120. var strings = {
  3121. string2buf: string2buf,
  3122. buf2string: buf2string,
  3123. utf8border: utf8border
  3124. };
  3125. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  3126. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  3127. //
  3128. // This software is provided 'as-is', without any express or implied
  3129. // warranty. In no event will the authors be held liable for any damages
  3130. // arising from the use of this software.
  3131. //
  3132. // Permission is granted to anyone to use this software for any purpose,
  3133. // including commercial applications, and to alter it and redistribute it
  3134. // freely, subject to the following restrictions:
  3135. //
  3136. // 1. The origin of this software must not be misrepresented; you must not
  3137. // claim that you wrote the original software. If you use this software
  3138. // in a product, an acknowledgment in the product documentation would be
  3139. // appreciated but is not required.
  3140. // 2. Altered source versions must be plainly marked as such, and must not be
  3141. // misrepresented as being the original software.
  3142. // 3. This notice may not be removed or altered from any source distribution.
  3143. function ZStream() {
  3144. /* next input byte */
  3145. this.input = null; // JS specific, because we have no pointers
  3146. this.next_in = 0;
  3147. /* number of bytes available at input */
  3148. this.avail_in = 0;
  3149. /* total number of input bytes read so far */
  3150. this.total_in = 0;
  3151. /* next output byte should be put there */
  3152. this.output = null; // JS specific, because we have no pointers
  3153. this.next_out = 0;
  3154. /* remaining free space at output */
  3155. this.avail_out = 0;
  3156. /* total number of bytes output so far */
  3157. this.total_out = 0;
  3158. /* last error message, NULL if no error */
  3159. this.msg = ''/*Z_NULL*/;
  3160. /* not visible by applications */
  3161. this.state = null;
  3162. /* best guess about the data type: binary or text */
  3163. this.data_type = 2/*Z_UNKNOWN*/;
  3164. /* adler32 value of the uncompressed data */
  3165. this.adler = 0;
  3166. }
  3167. var zstream = ZStream;
  3168. const toString = Object.prototype.toString;
  3169. /* Public constants ==========================================================*/
  3170. /* ===========================================================================*/
  3171. const {
  3172. Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH,
  3173. Z_OK, Z_STREAM_END,
  3174. Z_DEFAULT_COMPRESSION,
  3175. Z_DEFAULT_STRATEGY,
  3176. Z_DEFLATED
  3177. } = constants$1;
  3178. /* ===========================================================================*/
  3179. /**
  3180. * class Deflate
  3181. *
  3182. * Generic JS-style wrapper for zlib calls. If you don't need
  3183. * streaming behaviour - use more simple functions: [[deflate]],
  3184. * [[deflateRaw]] and [[gzip]].
  3185. **/
  3186. /* internal
  3187. * Deflate.chunks -> Array
  3188. *
  3189. * Chunks of output data, if [[Deflate#onData]] not overridden.
  3190. **/
  3191. /**
  3192. * Deflate.result -> Uint8Array
  3193. *
  3194. * Compressed result, generated by default [[Deflate#onData]]
  3195. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  3196. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  3197. **/
  3198. /**
  3199. * Deflate.err -> Number
  3200. *
  3201. * Error code after deflate finished. 0 (Z_OK) on success.
  3202. * You will not need it in real life, because deflate errors
  3203. * are possible only on wrong options or bad `onData` / `onEnd`
  3204. * custom handlers.
  3205. **/
  3206. /**
  3207. * Deflate.msg -> String
  3208. *
  3209. * Error message, if [[Deflate.err]] != 0
  3210. **/
  3211. /**
  3212. * new Deflate(options)
  3213. * - options (Object): zlib deflate options.
  3214. *
  3215. * Creates new deflator instance with specified params. Throws exception
  3216. * on bad params. Supported options:
  3217. *
  3218. * - `level`
  3219. * - `windowBits`
  3220. * - `memLevel`
  3221. * - `strategy`
  3222. * - `dictionary`
  3223. *
  3224. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3225. * for more information on these.
  3226. *
  3227. * Additional options, for internal needs:
  3228. *
  3229. * - `chunkSize` - size of generated data chunks (16K by default)
  3230. * - `raw` (Boolean) - do raw deflate
  3231. * - `gzip` (Boolean) - create gzip wrapper
  3232. * - `header` (Object) - custom header for gzip
  3233. * - `text` (Boolean) - true if compressed data believed to be text
  3234. * - `time` (Number) - modification time, unix timestamp
  3235. * - `os` (Number) - operation system code
  3236. * - `extra` (Array) - array of bytes with extra data (max 65536)
  3237. * - `name` (String) - file name (binary string)
  3238. * - `comment` (String) - comment (binary string)
  3239. * - `hcrc` (Boolean) - true if header crc should be added
  3240. *
  3241. * ##### Example:
  3242. *
  3243. * ```javascript
  3244. * const pako = require('pako')
  3245. * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
  3246. * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  3247. *
  3248. * const deflate = new pako.Deflate({ level: 3});
  3249. *
  3250. * deflate.push(chunk1, false);
  3251. * deflate.push(chunk2, true); // true -> last chunk
  3252. *
  3253. * if (deflate.err) { throw new Error(deflate.err); }
  3254. *
  3255. * console.log(deflate.result);
  3256. * ```
  3257. **/
  3258. function Deflate(options) {
  3259. this.options = common.assign({
  3260. level: Z_DEFAULT_COMPRESSION,
  3261. method: Z_DEFLATED,
  3262. chunkSize: 16384,
  3263. windowBits: 15,
  3264. memLevel: 8,
  3265. strategy: Z_DEFAULT_STRATEGY
  3266. }, options || {});
  3267. let opt = this.options;
  3268. if (opt.raw && (opt.windowBits > 0)) {
  3269. opt.windowBits = -opt.windowBits;
  3270. }
  3271. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  3272. opt.windowBits += 16;
  3273. }
  3274. this.err = 0; // error code, if happens (0 = Z_OK)
  3275. this.msg = ''; // error message
  3276. this.ended = false; // used to avoid multiple onEnd() calls
  3277. this.chunks = []; // chunks of compressed data
  3278. this.strm = new zstream();
  3279. this.strm.avail_out = 0;
  3280. let status = deflate_1$1.deflateInit2(
  3281. this.strm,
  3282. opt.level,
  3283. opt.method,
  3284. opt.windowBits,
  3285. opt.memLevel,
  3286. opt.strategy
  3287. );
  3288. if (status !== Z_OK) {
  3289. throw new Error(messages[status]);
  3290. }
  3291. if (opt.header) {
  3292. deflate_1$1.deflateSetHeader(this.strm, opt.header);
  3293. }
  3294. if (opt.dictionary) {
  3295. let dict;
  3296. // Convert data if needed
  3297. if (typeof opt.dictionary === 'string') {
  3298. // If we need to compress text, change encoding to utf8.
  3299. dict = strings.string2buf(opt.dictionary);
  3300. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  3301. dict = new Uint8Array(opt.dictionary);
  3302. } else {
  3303. dict = opt.dictionary;
  3304. }
  3305. status = deflate_1$1.deflateSetDictionary(this.strm, dict);
  3306. if (status !== Z_OK) {
  3307. throw new Error(messages[status]);
  3308. }
  3309. this._dict_set = true;
  3310. }
  3311. }
  3312. /**
  3313. * Deflate#push(data[, flush_mode]) -> Boolean
  3314. * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
  3315. * converted to utf8 byte sequence.
  3316. * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3317. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  3318. *
  3319. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  3320. * new compressed chunks. Returns `true` on success. The last data block must
  3321. * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
  3322. * buffers and call [[Deflate#onEnd]].
  3323. *
  3324. * On fail call [[Deflate#onEnd]] with error code and return false.
  3325. *
  3326. * ##### Example
  3327. *
  3328. * ```javascript
  3329. * push(chunk, false); // push one of data chunks
  3330. * ...
  3331. * push(chunk, true); // push last chunk
  3332. * ```
  3333. **/
  3334. Deflate.prototype.push = function (data, flush_mode) {
  3335. const strm = this.strm;
  3336. const chunkSize = this.options.chunkSize;
  3337. let status, _flush_mode;
  3338. if (this.ended) { return false; }
  3339. if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
  3340. else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;
  3341. // Convert data if needed
  3342. if (typeof data === 'string') {
  3343. // If we need to compress text, change encoding to utf8.
  3344. strm.input = strings.string2buf(data);
  3345. } else if (toString.call(data) === '[object ArrayBuffer]') {
  3346. strm.input = new Uint8Array(data);
  3347. } else {
  3348. strm.input = data;
  3349. }
  3350. strm.next_in = 0;
  3351. strm.avail_in = strm.input.length;
  3352. for (;;) {
  3353. if (strm.avail_out === 0) {
  3354. strm.output = new Uint8Array(chunkSize);
  3355. strm.next_out = 0;
  3356. strm.avail_out = chunkSize;
  3357. }
  3358. // Make sure avail_out > 6 to avoid repeating markers
  3359. if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
  3360. this.onData(strm.output.subarray(0, strm.next_out));
  3361. strm.avail_out = 0;
  3362. continue;
  3363. }
  3364. status = deflate_1$1.deflate(strm, _flush_mode);
  3365. // Ended => flush and finish
  3366. if (status === Z_STREAM_END) {
  3367. if (strm.next_out > 0) {
  3368. this.onData(strm.output.subarray(0, strm.next_out));
  3369. }
  3370. status = deflate_1$1.deflateEnd(this.strm);
  3371. this.onEnd(status);
  3372. this.ended = true;
  3373. return status === Z_OK;
  3374. }
  3375. // Flush if out buffer full
  3376. if (strm.avail_out === 0) {
  3377. this.onData(strm.output);
  3378. continue;
  3379. }
  3380. // Flush if requested and has data
  3381. if (_flush_mode > 0 && strm.next_out > 0) {
  3382. this.onData(strm.output.subarray(0, strm.next_out));
  3383. strm.avail_out = 0;
  3384. continue;
  3385. }
  3386. if (strm.avail_in === 0) break;
  3387. }
  3388. return true;
  3389. };
  3390. /**
  3391. * Deflate#onData(chunk) -> Void
  3392. * - chunk (Uint8Array): output data.
  3393. *
  3394. * By default, stores data blocks in `chunks[]` property and glue
  3395. * those in `onEnd`. Override this handler, if you need another behaviour.
  3396. **/
  3397. Deflate.prototype.onData = function (chunk) {
  3398. this.chunks.push(chunk);
  3399. };
  3400. /**
  3401. * Deflate#onEnd(status) -> Void
  3402. * - status (Number): deflate status. 0 (Z_OK) on success,
  3403. * other if not.
  3404. *
  3405. * Called once after you tell deflate that the input stream is
  3406. * complete (Z_FINISH). By default - join collected chunks,
  3407. * free memory and fill `results` / `err` properties.
  3408. **/
  3409. Deflate.prototype.onEnd = function (status) {
  3410. // On success - join
  3411. if (status === Z_OK) {
  3412. this.result = common.flattenChunks(this.chunks);
  3413. }
  3414. this.chunks = [];
  3415. this.err = status;
  3416. this.msg = this.strm.msg;
  3417. };
  3418. /**
  3419. * deflate(data[, options]) -> Uint8Array
  3420. * - data (Uint8Array|ArrayBuffer|String): input data to compress.
  3421. * - options (Object): zlib deflate options.
  3422. *
  3423. * Compress `data` with deflate algorithm and `options`.
  3424. *
  3425. * Supported options are:
  3426. *
  3427. * - level
  3428. * - windowBits
  3429. * - memLevel
  3430. * - strategy
  3431. * - dictionary
  3432. *
  3433. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3434. * for more information on these.
  3435. *
  3436. * Sugar (options):
  3437. *
  3438. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3439. * negative windowBits implicitly.
  3440. *
  3441. * ##### Example:
  3442. *
  3443. * ```javascript
  3444. * const pako = require('pako')
  3445. * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
  3446. *
  3447. * console.log(pako.deflate(data));
  3448. * ```
  3449. **/
  3450. function deflate(input, options) {
  3451. const deflator = new Deflate(options);
  3452. deflator.push(input, true);
  3453. // That will never happens, if you don't cheat with options :)
  3454. if (deflator.err) { throw deflator.msg || messages[deflator.err]; }
  3455. return deflator.result;
  3456. }
  3457. /**
  3458. * deflateRaw(data[, options]) -> Uint8Array
  3459. * - data (Uint8Array|ArrayBuffer|String): input data to compress.
  3460. * - options (Object): zlib deflate options.
  3461. *
  3462. * The same as [[deflate]], but creates raw data, without wrapper
  3463. * (header and adler32 crc).
  3464. **/
  3465. function deflateRaw(input, options) {
  3466. options = options || {};
  3467. options.raw = true;
  3468. return deflate(input, options);
  3469. }
  3470. /**
  3471. * gzip(data[, options]) -> Uint8Array
  3472. * - data (Uint8Array|ArrayBuffer|String): input data to compress.
  3473. * - options (Object): zlib deflate options.
  3474. *
  3475. * The same as [[deflate]], but create gzip wrapper instead of
  3476. * deflate one.
  3477. **/
  3478. function gzip(input, options) {
  3479. options = options || {};
  3480. options.gzip = true;
  3481. return deflate(input, options);
  3482. }
  3483. var Deflate_1 = Deflate;
  3484. var deflate_2 = deflate;
  3485. var deflateRaw_1 = deflateRaw;
  3486. var gzip_1 = gzip;
  3487. var constants = constants$1;
  3488. var deflate_1 = {
  3489. Deflate: Deflate_1,
  3490. deflate: deflate_2,
  3491. deflateRaw: deflateRaw_1,
  3492. gzip: gzip_1,
  3493. constants: constants
  3494. };
  3495. exports.Deflate = Deflate_1;
  3496. exports.constants = constants;
  3497. exports["default"] = deflate_1;
  3498. exports.deflate = deflate_2;
  3499. exports.deflateRaw = deflateRaw_1;
  3500. exports.gzip = gzip_1;
  3501. Object.defineProperty(exports, '__esModule', { value: true });
  3502. }));