deflate.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. 'use strict';
  2. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  3. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. // 2. Altered source versions must be plainly marked as such, and must not be
  18. // misrepresented as being the original software.
  19. // 3. This notice may not be removed or altered from any source distribution.
  20. const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = require('./trees');
  21. const adler32 = require('./adler32');
  22. const crc32 = require('./crc32');
  23. const msg = require('./messages');
  24. /* Public constants ==========================================================*/
  25. /* ===========================================================================*/
  26. const {
  27. Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK,
  28. Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,
  29. Z_DEFAULT_COMPRESSION,
  30. Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY,
  31. Z_UNKNOWN,
  32. Z_DEFLATED
  33. } = require('./constants');
  34. /*============================================================================*/
  35. const MAX_MEM_LEVEL = 9;
  36. /* Maximum value for memLevel in deflateInit2 */
  37. const MAX_WBITS = 15;
  38. /* 32K LZ77 window */
  39. const DEF_MEM_LEVEL = 8;
  40. const LENGTH_CODES = 29;
  41. /* number of length codes, not counting the special END_BLOCK code */
  42. const LITERALS = 256;
  43. /* number of literal bytes 0..255 */
  44. const L_CODES = LITERALS + 1 + LENGTH_CODES;
  45. /* number of Literal or Length codes, including the END_BLOCK code */
  46. const D_CODES = 30;
  47. /* number of distance codes */
  48. const BL_CODES = 19;
  49. /* number of codes used to transfer the bit lengths */
  50. const HEAP_SIZE = 2 * L_CODES + 1;
  51. /* maximum heap size */
  52. const MAX_BITS = 15;
  53. /* All codes must not exceed MAX_BITS bits */
  54. const MIN_MATCH = 3;
  55. const MAX_MATCH = 258;
  56. const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  57. const PRESET_DICT = 0x20;
  58. const INIT_STATE = 42; /* zlib header -> BUSY_STATE */
  59. //#ifdef GZIP
  60. const GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */
  61. //#endif
  62. const EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */
  63. const NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */
  64. const COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */
  65. const HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */
  66. const BUSY_STATE = 113; /* deflate -> FINISH_STATE */
  67. const FINISH_STATE = 666; /* stream complete */
  68. const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  69. const BS_BLOCK_DONE = 2; /* block flush performed */
  70. const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  71. const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  72. const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  73. const err = (strm, errorCode) => {
  74. strm.msg = msg[errorCode];
  75. return errorCode;
  76. };
  77. const rank = (f) => {
  78. return ((f) * 2) - ((f) > 4 ? 9 : 0);
  79. };
  80. const zero = (buf) => {
  81. let len = buf.length; while (--len >= 0) { buf[len] = 0; }
  82. };
  83. /* ===========================================================================
  84. * Slide the hash table when sliding the window down (could be avoided with 32
  85. * bit values at the expense of memory usage). We slide even when level == 0 to
  86. * keep the hash table consistent if we switch back to level > 0 later.
  87. */
  88. const slide_hash = (s) => {
  89. let n, m;
  90. let p;
  91. let wsize = s.w_size;
  92. n = s.hash_size;
  93. p = n;
  94. do {
  95. m = s.head[--p];
  96. s.head[p] = (m >= wsize ? m - wsize : 0);
  97. } while (--n);
  98. n = wsize;
  99. //#ifndef FASTEST
  100. p = n;
  101. do {
  102. m = s.prev[--p];
  103. s.prev[p] = (m >= wsize ? m - wsize : 0);
  104. /* If n is not on any hash chain, prev[n] is garbage but
  105. * its value will never be used.
  106. */
  107. } while (--n);
  108. //#endif
  109. };
  110. /* eslint-disable new-cap */
  111. let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;
  112. // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
  113. // But breaks binary compatibility
  114. //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
  115. let HASH = HASH_ZLIB;
  116. /* =========================================================================
  117. * Flush as much pending output as possible. All deflate() output, except for
  118. * some deflate_stored() output, goes through this function so some
  119. * applications may wish to modify it to avoid allocating a large
  120. * strm->next_out buffer and copying into it. (See also read_buf()).
  121. */
  122. const flush_pending = (strm) => {
  123. const s = strm.state;
  124. //_tr_flush_bits(s);
  125. let len = s.pending;
  126. if (len > strm.avail_out) {
  127. len = strm.avail_out;
  128. }
  129. if (len === 0) { return; }
  130. strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
  131. strm.next_out += len;
  132. s.pending_out += len;
  133. strm.total_out += len;
  134. strm.avail_out -= len;
  135. s.pending -= len;
  136. if (s.pending === 0) {
  137. s.pending_out = 0;
  138. }
  139. };
  140. const flush_block_only = (s, last) => {
  141. _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  142. s.block_start = s.strstart;
  143. flush_pending(s.strm);
  144. };
  145. const put_byte = (s, b) => {
  146. s.pending_buf[s.pending++] = b;
  147. };
  148. /* =========================================================================
  149. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  150. * IN assertion: the stream state is correct and there is enough room in
  151. * pending_buf.
  152. */
  153. const putShortMSB = (s, b) => {
  154. // put_byte(s, (Byte)(b >> 8));
  155. // put_byte(s, (Byte)(b & 0xff));
  156. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  157. s.pending_buf[s.pending++] = b & 0xff;
  158. };
  159. /* ===========================================================================
  160. * Read a new buffer from the current input stream, update the adler32
  161. * and total number of bytes read. All deflate() input goes through
  162. * this function so some applications may wish to modify it to avoid
  163. * allocating a large strm->input buffer and copying from it.
  164. * (See also flush_pending()).
  165. */
  166. const read_buf = (strm, buf, start, size) => {
  167. let len = strm.avail_in;
  168. if (len > size) { len = size; }
  169. if (len === 0) { return 0; }
  170. strm.avail_in -= len;
  171. // zmemcpy(buf, strm->next_in, len);
  172. buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
  173. if (strm.state.wrap === 1) {
  174. strm.adler = adler32(strm.adler, buf, len, start);
  175. }
  176. else if (strm.state.wrap === 2) {
  177. strm.adler = crc32(strm.adler, buf, len, start);
  178. }
  179. strm.next_in += len;
  180. strm.total_in += len;
  181. return len;
  182. };
  183. /* ===========================================================================
  184. * Set match_start to the longest match starting at the given string and
  185. * return its length. Matches shorter or equal to prev_length are discarded,
  186. * in which case the result is equal to prev_length and match_start is
  187. * garbage.
  188. * IN assertions: cur_match is the head of the hash chain for the current
  189. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  190. * OUT assertion: the match length is not greater than s->lookahead.
  191. */
  192. const longest_match = (s, cur_match) => {
  193. let chain_length = s.max_chain_length; /* max hash chain length */
  194. let scan = s.strstart; /* current string */
  195. let match; /* matched string */
  196. let len; /* length of current match */
  197. let best_len = s.prev_length; /* best match length so far */
  198. let nice_match = s.nice_match; /* stop if match long enough */
  199. const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  200. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  201. const _win = s.window; // shortcut
  202. const wmask = s.w_mask;
  203. const prev = s.prev;
  204. /* Stop when cur_match becomes <= limit. To simplify the code,
  205. * we prevent matches with the string of window index 0.
  206. */
  207. const strend = s.strstart + MAX_MATCH;
  208. let scan_end1 = _win[scan + best_len - 1];
  209. let scan_end = _win[scan + best_len];
  210. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  211. * It is easy to get rid of this optimization if necessary.
  212. */
  213. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  214. /* Do not waste too much time if we already have a good match: */
  215. if (s.prev_length >= s.good_match) {
  216. chain_length >>= 2;
  217. }
  218. /* Do not look for matches beyond the end of the input. This is necessary
  219. * to make deflate deterministic.
  220. */
  221. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  222. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  223. do {
  224. // Assert(cur_match < s->strstart, "no future");
  225. match = cur_match;
  226. /* Skip to next match if the match length cannot increase
  227. * or if the match length is less than 2. Note that the checks below
  228. * for insufficient lookahead only occur occasionally for performance
  229. * reasons. Therefore uninitialized memory will be accessed, and
  230. * conditional jumps will be made that depend on those values.
  231. * However the length of the match is limited to the lookahead, so
  232. * the output of deflate is not affected by the uninitialized values.
  233. */
  234. if (_win[match + best_len] !== scan_end ||
  235. _win[match + best_len - 1] !== scan_end1 ||
  236. _win[match] !== _win[scan] ||
  237. _win[++match] !== _win[scan + 1]) {
  238. continue;
  239. }
  240. /* The check at best_len-1 can be removed because it will be made
  241. * again later. (This heuristic is not always a win.)
  242. * It is not necessary to compare scan[2] and match[2] since they
  243. * are always equal when the other bytes match, given that
  244. * the hash keys are equal and that HASH_BITS >= 8.
  245. */
  246. scan += 2;
  247. match++;
  248. // Assert(*scan == *match, "match[2]?");
  249. /* We check for insufficient lookahead only every 8th comparison;
  250. * the 256th check will be made at strstart+258.
  251. */
  252. do {
  253. /*jshint noempty:false*/
  254. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  255. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  256. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  257. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  258. scan < strend);
  259. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  260. len = MAX_MATCH - (strend - scan);
  261. scan = strend - MAX_MATCH;
  262. if (len > best_len) {
  263. s.match_start = cur_match;
  264. best_len = len;
  265. if (len >= nice_match) {
  266. break;
  267. }
  268. scan_end1 = _win[scan + best_len - 1];
  269. scan_end = _win[scan + best_len];
  270. }
  271. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  272. if (best_len <= s.lookahead) {
  273. return best_len;
  274. }
  275. return s.lookahead;
  276. };
  277. /* ===========================================================================
  278. * Fill the window when the lookahead becomes insufficient.
  279. * Updates strstart and lookahead.
  280. *
  281. * IN assertion: lookahead < MIN_LOOKAHEAD
  282. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  283. * At least one byte has been read, or avail_in == 0; reads are
  284. * performed for at least two bytes (required for the zip translate_eol
  285. * option -- not supported here).
  286. */
  287. const fill_window = (s) => {
  288. const _w_size = s.w_size;
  289. let n, more, str;
  290. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  291. do {
  292. more = s.window_size - s.lookahead - s.strstart;
  293. // JS ints have 32 bit, block below not needed
  294. /* Deal with !@#$% 64K limit: */
  295. //if (sizeof(int) <= 2) {
  296. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  297. // more = wsize;
  298. //
  299. // } else if (more == (unsigned)(-1)) {
  300. // /* Very unlikely, but possible on 16 bit machine if
  301. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  302. // */
  303. // more--;
  304. // }
  305. //}
  306. /* If the window is almost full and there is insufficient lookahead,
  307. * move the upper half to the lower one to make room in the upper half.
  308. */
  309. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  310. s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);
  311. s.match_start -= _w_size;
  312. s.strstart -= _w_size;
  313. /* we now have strstart >= MAX_DIST */
  314. s.block_start -= _w_size;
  315. if (s.insert > s.strstart) {
  316. s.insert = s.strstart;
  317. }
  318. slide_hash(s);
  319. more += _w_size;
  320. }
  321. if (s.strm.avail_in === 0) {
  322. break;
  323. }
  324. /* If there was no sliding:
  325. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  326. * more == window_size - lookahead - strstart
  327. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  328. * => more >= window_size - 2*WSIZE + 2
  329. * In the BIG_MEM or MMAP case (not yet supported),
  330. * window_size == input_size + MIN_LOOKAHEAD &&
  331. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  332. * Otherwise, window_size == 2*WSIZE so more >= 2.
  333. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  334. */
  335. //Assert(more >= 2, "more < 2");
  336. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  337. s.lookahead += n;
  338. /* Initialize the hash value now that we have some input: */
  339. if (s.lookahead + s.insert >= MIN_MATCH) {
  340. str = s.strstart - s.insert;
  341. s.ins_h = s.window[str];
  342. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  343. s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);
  344. //#if MIN_MATCH != 3
  345. // Call update_hash() MIN_MATCH-3 more times
  346. //#endif
  347. while (s.insert) {
  348. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  349. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  350. s.prev[str & s.w_mask] = s.head[s.ins_h];
  351. s.head[s.ins_h] = str;
  352. str++;
  353. s.insert--;
  354. if (s.lookahead + s.insert < MIN_MATCH) {
  355. break;
  356. }
  357. }
  358. }
  359. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  360. * but this is not important since only literal bytes will be emitted.
  361. */
  362. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  363. /* If the WIN_INIT bytes after the end of the current data have never been
  364. * written, then zero those bytes in order to avoid memory check reports of
  365. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  366. * the longest match routines. Update the high water mark for the next
  367. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  368. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  369. */
  370. // if (s.high_water < s.window_size) {
  371. // const curr = s.strstart + s.lookahead;
  372. // let init = 0;
  373. //
  374. // if (s.high_water < curr) {
  375. // /* Previous high water mark below current data -- zero WIN_INIT
  376. // * bytes or up to end of window, whichever is less.
  377. // */
  378. // init = s.window_size - curr;
  379. // if (init > WIN_INIT)
  380. // init = WIN_INIT;
  381. // zmemzero(s->window + curr, (unsigned)init);
  382. // s->high_water = curr + init;
  383. // }
  384. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  385. // /* High water mark at or above current data, but below current data
  386. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  387. // * to end of window, whichever is less.
  388. // */
  389. // init = (ulg)curr + WIN_INIT - s->high_water;
  390. // if (init > s->window_size - s->high_water)
  391. // init = s->window_size - s->high_water;
  392. // zmemzero(s->window + s->high_water, (unsigned)init);
  393. // s->high_water += init;
  394. // }
  395. // }
  396. //
  397. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  398. // "not enough room for search");
  399. };
  400. /* ===========================================================================
  401. * Copy without compression as much as possible from the input stream, return
  402. * the current block state.
  403. *
  404. * In case deflateParams() is used to later switch to a non-zero compression
  405. * level, s->matches (otherwise unused when storing) keeps track of the number
  406. * of hash table slides to perform. If s->matches is 1, then one hash table
  407. * slide will be done when switching. If s->matches is 2, the maximum value
  408. * allowed here, then the hash table will be cleared, since two or more slides
  409. * is the same as a clear.
  410. *
  411. * deflate_stored() is written to minimize the number of times an input byte is
  412. * copied. It is most efficient with large input and output buffers, which
  413. * maximizes the opportunites to have a single copy from next_in to next_out.
  414. */
  415. const deflate_stored = (s, flush) => {
  416. /* Smallest worthy block size when not flushing or finishing. By default
  417. * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
  418. * large input and output buffers, the stored block size will be larger.
  419. */
  420. let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;
  421. /* Copy as many min_block or larger stored blocks directly to next_out as
  422. * possible. If flushing, copy the remaining available input to next_out as
  423. * stored blocks, if there is enough space.
  424. */
  425. let len, left, have, last = 0;
  426. let used = s.strm.avail_in;
  427. do {
  428. /* Set len to the maximum size block that we can copy directly with the
  429. * available input data and output space. Set left to how much of that
  430. * would be copied from what's left in the window.
  431. */
  432. len = 65535/* MAX_STORED */; /* maximum deflate stored block length */
  433. have = (s.bi_valid + 42) >> 3; /* number of header bytes */
  434. if (s.strm.avail_out < have) { /* need room for header */
  435. break;
  436. }
  437. /* maximum stored block length that will fit in avail_out: */
  438. have = s.strm.avail_out - have;
  439. left = s.strstart - s.block_start; /* bytes left in window */
  440. if (len > left + s.strm.avail_in) {
  441. len = left + s.strm.avail_in; /* limit len to the input */
  442. }
  443. if (len > have) {
  444. len = have; /* limit len to the output */
  445. }
  446. /* If the stored block would be less than min_block in length, or if
  447. * unable to copy all of the available input when flushing, then try
  448. * copying to the window and the pending buffer instead. Also don't
  449. * write an empty block when flushing -- deflate() does that.
  450. */
  451. if (len < min_block && ((len === 0 && flush !== Z_FINISH) ||
  452. flush === Z_NO_FLUSH ||
  453. len !== left + s.strm.avail_in)) {
  454. break;
  455. }
  456. /* Make a dummy stored block in pending to get the header bytes,
  457. * including any pending bits. This also updates the debugging counts.
  458. */
  459. last = flush === Z_FINISH && len === left + s.strm.avail_in ? 1 : 0;
  460. _tr_stored_block(s, 0, 0, last);
  461. /* Replace the lengths in the dummy stored block with len. */
  462. s.pending_buf[s.pending - 4] = len;
  463. s.pending_buf[s.pending - 3] = len >> 8;
  464. s.pending_buf[s.pending - 2] = ~len;
  465. s.pending_buf[s.pending - 1] = ~len >> 8;
  466. /* Write the stored block header bytes. */
  467. flush_pending(s.strm);
  468. //#ifdef ZLIB_DEBUG
  469. // /* Update debugging counts for the data about to be copied. */
  470. // s->compressed_len += len << 3;
  471. // s->bits_sent += len << 3;
  472. //#endif
  473. /* Copy uncompressed bytes from the window to next_out. */
  474. if (left) {
  475. if (left > len) {
  476. left = len;
  477. }
  478. //zmemcpy(s->strm->next_out, s->window + s->block_start, left);
  479. s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
  480. s.strm.next_out += left;
  481. s.strm.avail_out -= left;
  482. s.strm.total_out += left;
  483. s.block_start += left;
  484. len -= left;
  485. }
  486. /* Copy uncompressed bytes directly from next_in to next_out, updating
  487. * the check value.
  488. */
  489. if (len) {
  490. read_buf(s.strm, s.strm.output, s.strm.next_out, len);
  491. s.strm.next_out += len;
  492. s.strm.avail_out -= len;
  493. s.strm.total_out += len;
  494. }
  495. } while (last === 0);
  496. /* Update the sliding window with the last s->w_size bytes of the copied
  497. * data, or append all of the copied data to the existing window if less
  498. * than s->w_size bytes were copied. Also update the number of bytes to
  499. * insert in the hash tables, in the event that deflateParams() switches to
  500. * a non-zero compression level.
  501. */
  502. used -= s.strm.avail_in; /* number of input bytes directly copied */
  503. if (used) {
  504. /* If any input was used, then no unused input remains in the window,
  505. * therefore s->block_start == s->strstart.
  506. */
  507. if (used >= s.w_size) { /* supplant the previous history */
  508. s.matches = 2; /* clear hash */
  509. //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
  510. s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);
  511. s.strstart = s.w_size;
  512. s.insert = s.strstart;
  513. }
  514. else {
  515. if (s.window_size - s.strstart <= used) {
  516. /* Slide the window down. */
  517. s.strstart -= s.w_size;
  518. //zmemcpy(s->window, s->window + s->w_size, s->strstart);
  519. s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
  520. if (s.matches < 2) {
  521. s.matches++; /* add a pending slide_hash() */
  522. }
  523. if (s.insert > s.strstart) {
  524. s.insert = s.strstart;
  525. }
  526. }
  527. //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
  528. s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);
  529. s.strstart += used;
  530. s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;
  531. }
  532. s.block_start = s.strstart;
  533. }
  534. if (s.high_water < s.strstart) {
  535. s.high_water = s.strstart;
  536. }
  537. /* If the last block was written to next_out, then done. */
  538. if (last) {
  539. return BS_FINISH_DONE;
  540. }
  541. /* If flushing and all input has been consumed, then done. */
  542. if (flush !== Z_NO_FLUSH && flush !== Z_FINISH &&
  543. s.strm.avail_in === 0 && s.strstart === s.block_start) {
  544. return BS_BLOCK_DONE;
  545. }
  546. /* Fill the window with any remaining input. */
  547. have = s.window_size - s.strstart;
  548. if (s.strm.avail_in > have && s.block_start >= s.w_size) {
  549. /* Slide the window down. */
  550. s.block_start -= s.w_size;
  551. s.strstart -= s.w_size;
  552. //zmemcpy(s->window, s->window + s->w_size, s->strstart);
  553. s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
  554. if (s.matches < 2) {
  555. s.matches++; /* add a pending slide_hash() */
  556. }
  557. have += s.w_size; /* more space now */
  558. if (s.insert > s.strstart) {
  559. s.insert = s.strstart;
  560. }
  561. }
  562. if (have > s.strm.avail_in) {
  563. have = s.strm.avail_in;
  564. }
  565. if (have) {
  566. read_buf(s.strm, s.window, s.strstart, have);
  567. s.strstart += have;
  568. s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;
  569. }
  570. if (s.high_water < s.strstart) {
  571. s.high_water = s.strstart;
  572. }
  573. /* There was not enough avail_out to write a complete worthy or flushed
  574. * stored block to next_out. Write a stored block to pending instead, if we
  575. * have enough input for a worthy block, or if flushing and there is enough
  576. * room for the remaining input as a stored block in the pending buffer.
  577. */
  578. have = (s.bi_valid + 42) >> 3; /* number of header bytes */
  579. /* maximum stored block length that will fit in pending: */
  580. have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;
  581. min_block = have > s.w_size ? s.w_size : have;
  582. left = s.strstart - s.block_start;
  583. if (left >= min_block ||
  584. ((left || flush === Z_FINISH) && flush !== Z_NO_FLUSH &&
  585. s.strm.avail_in === 0 && left <= have)) {
  586. len = left > have ? have : left;
  587. last = flush === Z_FINISH && s.strm.avail_in === 0 &&
  588. len === left ? 1 : 0;
  589. _tr_stored_block(s, s.block_start, len, last);
  590. s.block_start += len;
  591. flush_pending(s.strm);
  592. }
  593. /* We've done all we can with the available input and output. */
  594. return last ? BS_FINISH_STARTED : BS_NEED_MORE;
  595. };
  596. /* ===========================================================================
  597. * Compress as much as possible from the input stream, return the current
  598. * block state.
  599. * This function does not perform lazy evaluation of matches and inserts
  600. * new strings in the dictionary only for unmatched strings or for short
  601. * matches. It is used only for the fast compression options.
  602. */
  603. const deflate_fast = (s, flush) => {
  604. let hash_head; /* head of the hash chain */
  605. let bflush; /* set if current block must be flushed */
  606. for (;;) {
  607. /* Make sure that we always have enough lookahead, except
  608. * at the end of the input file. We need MAX_MATCH bytes
  609. * for the next match, plus MIN_MATCH bytes to insert the
  610. * string following the next match.
  611. */
  612. if (s.lookahead < MIN_LOOKAHEAD) {
  613. fill_window(s);
  614. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  615. return BS_NEED_MORE;
  616. }
  617. if (s.lookahead === 0) {
  618. break; /* flush the current block */
  619. }
  620. }
  621. /* Insert the string window[strstart .. strstart+2] in the
  622. * dictionary, and set hash_head to the head of the hash chain:
  623. */
  624. hash_head = 0/*NIL*/;
  625. if (s.lookahead >= MIN_MATCH) {
  626. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  627. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  628. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  629. s.head[s.ins_h] = s.strstart;
  630. /***/
  631. }
  632. /* Find the longest match, discarding those <= prev_length.
  633. * At this point we have always match_length < MIN_MATCH
  634. */
  635. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  636. /* To simplify the code, we prevent matches with the string
  637. * of window index 0 (in particular we have to avoid a match
  638. * of the string with itself at the start of the input file).
  639. */
  640. s.match_length = longest_match(s, hash_head);
  641. /* longest_match() sets match_start */
  642. }
  643. if (s.match_length >= MIN_MATCH) {
  644. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  645. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  646. s.match_length - MIN_MATCH, bflush); ***/
  647. bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  648. s.lookahead -= s.match_length;
  649. /* Insert new strings in the hash table only if the match length
  650. * is not too large. This saves time but degrades compression.
  651. */
  652. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  653. s.match_length--; /* string at strstart already in table */
  654. do {
  655. s.strstart++;
  656. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  657. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  658. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  659. s.head[s.ins_h] = s.strstart;
  660. /***/
  661. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  662. * always MIN_MATCH bytes ahead.
  663. */
  664. } while (--s.match_length !== 0);
  665. s.strstart++;
  666. } else
  667. {
  668. s.strstart += s.match_length;
  669. s.match_length = 0;
  670. s.ins_h = s.window[s.strstart];
  671. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  672. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);
  673. //#if MIN_MATCH != 3
  674. // Call UPDATE_HASH() MIN_MATCH-3 more times
  675. //#endif
  676. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  677. * matter since it will be recomputed at next deflate call.
  678. */
  679. }
  680. } else {
  681. /* No match, output a literal byte */
  682. //Tracevv((stderr,"%c", s.window[s.strstart]));
  683. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  684. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  685. s.lookahead--;
  686. s.strstart++;
  687. }
  688. if (bflush) {
  689. /*** FLUSH_BLOCK(s, 0); ***/
  690. flush_block_only(s, false);
  691. if (s.strm.avail_out === 0) {
  692. return BS_NEED_MORE;
  693. }
  694. /***/
  695. }
  696. }
  697. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  698. if (flush === Z_FINISH) {
  699. /*** FLUSH_BLOCK(s, 1); ***/
  700. flush_block_only(s, true);
  701. if (s.strm.avail_out === 0) {
  702. return BS_FINISH_STARTED;
  703. }
  704. /***/
  705. return BS_FINISH_DONE;
  706. }
  707. if (s.sym_next) {
  708. /*** FLUSH_BLOCK(s, 0); ***/
  709. flush_block_only(s, false);
  710. if (s.strm.avail_out === 0) {
  711. return BS_NEED_MORE;
  712. }
  713. /***/
  714. }
  715. return BS_BLOCK_DONE;
  716. };
  717. /* ===========================================================================
  718. * Same as above, but achieves better compression. We use a lazy
  719. * evaluation for matches: a match is finally adopted only if there is
  720. * no better match at the next window position.
  721. */
  722. const deflate_slow = (s, flush) => {
  723. let hash_head; /* head of hash chain */
  724. let bflush; /* set if current block must be flushed */
  725. let max_insert;
  726. /* Process the input block. */
  727. for (;;) {
  728. /* Make sure that we always have enough lookahead, except
  729. * at the end of the input file. We need MAX_MATCH bytes
  730. * for the next match, plus MIN_MATCH bytes to insert the
  731. * string following the next match.
  732. */
  733. if (s.lookahead < MIN_LOOKAHEAD) {
  734. fill_window(s);
  735. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  736. return BS_NEED_MORE;
  737. }
  738. if (s.lookahead === 0) { break; } /* flush the current block */
  739. }
  740. /* Insert the string window[strstart .. strstart+2] in the
  741. * dictionary, and set hash_head to the head of the hash chain:
  742. */
  743. hash_head = 0/*NIL*/;
  744. if (s.lookahead >= MIN_MATCH) {
  745. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  746. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  747. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  748. s.head[s.ins_h] = s.strstart;
  749. /***/
  750. }
  751. /* Find the longest match, discarding those <= prev_length.
  752. */
  753. s.prev_length = s.match_length;
  754. s.prev_match = s.match_start;
  755. s.match_length = MIN_MATCH - 1;
  756. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  757. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  758. /* To simplify the code, we prevent matches with the string
  759. * of window index 0 (in particular we have to avoid a match
  760. * of the string with itself at the start of the input file).
  761. */
  762. s.match_length = longest_match(s, hash_head);
  763. /* longest_match() sets match_start */
  764. if (s.match_length <= 5 &&
  765. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  766. /* If prev_match is also MIN_MATCH, match_start is garbage
  767. * but we will ignore the current match anyway.
  768. */
  769. s.match_length = MIN_MATCH - 1;
  770. }
  771. }
  772. /* If there was a match at the previous step and the current
  773. * match is not better, output the previous match:
  774. */
  775. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  776. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  777. /* Do not insert strings in hash table beyond this. */
  778. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  779. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  780. s.prev_length - MIN_MATCH, bflush);***/
  781. bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  782. /* Insert in hash table all strings up to the end of the match.
  783. * strstart-1 and strstart are already inserted. If there is not
  784. * enough lookahead, the last two strings are not inserted in
  785. * the hash table.
  786. */
  787. s.lookahead -= s.prev_length - 1;
  788. s.prev_length -= 2;
  789. do {
  790. if (++s.strstart <= max_insert) {
  791. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  792. s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
  793. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  794. s.head[s.ins_h] = s.strstart;
  795. /***/
  796. }
  797. } while (--s.prev_length !== 0);
  798. s.match_available = 0;
  799. s.match_length = MIN_MATCH - 1;
  800. s.strstart++;
  801. if (bflush) {
  802. /*** FLUSH_BLOCK(s, 0); ***/
  803. flush_block_only(s, false);
  804. if (s.strm.avail_out === 0) {
  805. return BS_NEED_MORE;
  806. }
  807. /***/
  808. }
  809. } else if (s.match_available) {
  810. /* If there was no match at the previous position, output a
  811. * single literal. If there was a match but the current match
  812. * is longer, truncate the previous match to a single literal.
  813. */
  814. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  815. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  816. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  817. if (bflush) {
  818. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  819. flush_block_only(s, false);
  820. /***/
  821. }
  822. s.strstart++;
  823. s.lookahead--;
  824. if (s.strm.avail_out === 0) {
  825. return BS_NEED_MORE;
  826. }
  827. } else {
  828. /* There is no previous match to compare with, wait for
  829. * the next step to decide.
  830. */
  831. s.match_available = 1;
  832. s.strstart++;
  833. s.lookahead--;
  834. }
  835. }
  836. //Assert (flush != Z_NO_FLUSH, "no flush?");
  837. if (s.match_available) {
  838. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  839. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  840. bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
  841. s.match_available = 0;
  842. }
  843. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  844. if (flush === Z_FINISH) {
  845. /*** FLUSH_BLOCK(s, 1); ***/
  846. flush_block_only(s, true);
  847. if (s.strm.avail_out === 0) {
  848. return BS_FINISH_STARTED;
  849. }
  850. /***/
  851. return BS_FINISH_DONE;
  852. }
  853. if (s.sym_next) {
  854. /*** FLUSH_BLOCK(s, 0); ***/
  855. flush_block_only(s, false);
  856. if (s.strm.avail_out === 0) {
  857. return BS_NEED_MORE;
  858. }
  859. /***/
  860. }
  861. return BS_BLOCK_DONE;
  862. };
  863. /* ===========================================================================
  864. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  865. * one. Do not maintain a hash table. (It will be regenerated if this run of
  866. * deflate switches away from Z_RLE.)
  867. */
  868. const deflate_rle = (s, flush) => {
  869. let bflush; /* set if current block must be flushed */
  870. let prev; /* byte at distance one to match */
  871. let scan, strend; /* scan goes up to strend for length of run */
  872. const _win = s.window;
  873. for (;;) {
  874. /* Make sure that we always have enough lookahead, except
  875. * at the end of the input file. We need MAX_MATCH bytes
  876. * for the longest run, plus one for the unrolled loop.
  877. */
  878. if (s.lookahead <= MAX_MATCH) {
  879. fill_window(s);
  880. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  881. return BS_NEED_MORE;
  882. }
  883. if (s.lookahead === 0) { break; } /* flush the current block */
  884. }
  885. /* See how many times the previous byte repeats */
  886. s.match_length = 0;
  887. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  888. scan = s.strstart - 1;
  889. prev = _win[scan];
  890. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  891. strend = s.strstart + MAX_MATCH;
  892. do {
  893. /*jshint noempty:false*/
  894. } while (prev === _win[++scan] && prev === _win[++scan] &&
  895. prev === _win[++scan] && prev === _win[++scan] &&
  896. prev === _win[++scan] && prev === _win[++scan] &&
  897. prev === _win[++scan] && prev === _win[++scan] &&
  898. scan < strend);
  899. s.match_length = MAX_MATCH - (strend - scan);
  900. if (s.match_length > s.lookahead) {
  901. s.match_length = s.lookahead;
  902. }
  903. }
  904. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  905. }
  906. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  907. if (s.match_length >= MIN_MATCH) {
  908. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  909. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  910. bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
  911. s.lookahead -= s.match_length;
  912. s.strstart += s.match_length;
  913. s.match_length = 0;
  914. } else {
  915. /* No match, output a literal byte */
  916. //Tracevv((stderr,"%c", s->window[s->strstart]));
  917. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  918. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  919. s.lookahead--;
  920. s.strstart++;
  921. }
  922. if (bflush) {
  923. /*** FLUSH_BLOCK(s, 0); ***/
  924. flush_block_only(s, false);
  925. if (s.strm.avail_out === 0) {
  926. return BS_NEED_MORE;
  927. }
  928. /***/
  929. }
  930. }
  931. s.insert = 0;
  932. if (flush === Z_FINISH) {
  933. /*** FLUSH_BLOCK(s, 1); ***/
  934. flush_block_only(s, true);
  935. if (s.strm.avail_out === 0) {
  936. return BS_FINISH_STARTED;
  937. }
  938. /***/
  939. return BS_FINISH_DONE;
  940. }
  941. if (s.sym_next) {
  942. /*** FLUSH_BLOCK(s, 0); ***/
  943. flush_block_only(s, false);
  944. if (s.strm.avail_out === 0) {
  945. return BS_NEED_MORE;
  946. }
  947. /***/
  948. }
  949. return BS_BLOCK_DONE;
  950. };
  951. /* ===========================================================================
  952. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  953. * (It will be regenerated if this run of deflate switches away from Huffman.)
  954. */
  955. const deflate_huff = (s, flush) => {
  956. let bflush; /* set if current block must be flushed */
  957. for (;;) {
  958. /* Make sure that we have a literal to write. */
  959. if (s.lookahead === 0) {
  960. fill_window(s);
  961. if (s.lookahead === 0) {
  962. if (flush === Z_NO_FLUSH) {
  963. return BS_NEED_MORE;
  964. }
  965. break; /* flush the current block */
  966. }
  967. }
  968. /* Output a literal byte */
  969. s.match_length = 0;
  970. //Tracevv((stderr,"%c", s->window[s->strstart]));
  971. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  972. bflush = _tr_tally(s, 0, s.window[s.strstart]);
  973. s.lookahead--;
  974. s.strstart++;
  975. if (bflush) {
  976. /*** FLUSH_BLOCK(s, 0); ***/
  977. flush_block_only(s, false);
  978. if (s.strm.avail_out === 0) {
  979. return BS_NEED_MORE;
  980. }
  981. /***/
  982. }
  983. }
  984. s.insert = 0;
  985. if (flush === Z_FINISH) {
  986. /*** FLUSH_BLOCK(s, 1); ***/
  987. flush_block_only(s, true);
  988. if (s.strm.avail_out === 0) {
  989. return BS_FINISH_STARTED;
  990. }
  991. /***/
  992. return BS_FINISH_DONE;
  993. }
  994. if (s.sym_next) {
  995. /*** FLUSH_BLOCK(s, 0); ***/
  996. flush_block_only(s, false);
  997. if (s.strm.avail_out === 0) {
  998. return BS_NEED_MORE;
  999. }
  1000. /***/
  1001. }
  1002. return BS_BLOCK_DONE;
  1003. };
  1004. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  1005. * the desired pack level (0..9). The values given below have been tuned to
  1006. * exclude worst case performance for pathological files. Better values may be
  1007. * found for specific files.
  1008. */
  1009. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  1010. this.good_length = good_length;
  1011. this.max_lazy = max_lazy;
  1012. this.nice_length = nice_length;
  1013. this.max_chain = max_chain;
  1014. this.func = func;
  1015. }
  1016. const configuration_table = [
  1017. /* good lazy nice chain */
  1018. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  1019. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  1020. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  1021. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  1022. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  1023. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  1024. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  1025. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  1026. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  1027. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  1028. ];
  1029. /* ===========================================================================
  1030. * Initialize the "longest match" routines for a new zlib stream
  1031. */
  1032. const lm_init = (s) => {
  1033. s.window_size = 2 * s.w_size;
  1034. /*** CLEAR_HASH(s); ***/
  1035. zero(s.head); // Fill with NIL (= 0);
  1036. /* Set the default configuration parameters:
  1037. */
  1038. s.max_lazy_match = configuration_table[s.level].max_lazy;
  1039. s.good_match = configuration_table[s.level].good_length;
  1040. s.nice_match = configuration_table[s.level].nice_length;
  1041. s.max_chain_length = configuration_table[s.level].max_chain;
  1042. s.strstart = 0;
  1043. s.block_start = 0;
  1044. s.lookahead = 0;
  1045. s.insert = 0;
  1046. s.match_length = s.prev_length = MIN_MATCH - 1;
  1047. s.match_available = 0;
  1048. s.ins_h = 0;
  1049. };
  1050. function DeflateState() {
  1051. this.strm = null; /* pointer back to this zlib stream */
  1052. this.status = 0; /* as the name implies */
  1053. this.pending_buf = null; /* output still pending */
  1054. this.pending_buf_size = 0; /* size of pending_buf */
  1055. this.pending_out = 0; /* next pending byte to output to the stream */
  1056. this.pending = 0; /* nb of bytes in the pending buffer */
  1057. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  1058. this.gzhead = null; /* gzip header information to write */
  1059. this.gzindex = 0; /* where in extra, name, or comment */
  1060. this.method = Z_DEFLATED; /* can only be DEFLATED */
  1061. this.last_flush = -1; /* value of flush param for previous deflate call */
  1062. this.w_size = 0; /* LZ77 window size (32K by default) */
  1063. this.w_bits = 0; /* log2(w_size) (8..16) */
  1064. this.w_mask = 0; /* w_size - 1 */
  1065. this.window = null;
  1066. /* Sliding window. Input bytes are read into the second half of the window,
  1067. * and move to the first half later to keep a dictionary of at least wSize
  1068. * bytes. With this organization, matches are limited to a distance of
  1069. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  1070. * performed with a length multiple of the block size.
  1071. */
  1072. this.window_size = 0;
  1073. /* Actual size of window: 2*wSize, except when the user input buffer
  1074. * is directly used as sliding window.
  1075. */
  1076. this.prev = null;
  1077. /* Link to older string with same hash index. To limit the size of this
  1078. * array to 64K, this link is maintained only for the last 32K strings.
  1079. * An index in this array is thus a window index modulo 32K.
  1080. */
  1081. this.head = null; /* Heads of the hash chains or NIL. */
  1082. this.ins_h = 0; /* hash index of string to be inserted */
  1083. this.hash_size = 0; /* number of elements in hash table */
  1084. this.hash_bits = 0; /* log2(hash_size) */
  1085. this.hash_mask = 0; /* hash_size-1 */
  1086. this.hash_shift = 0;
  1087. /* Number of bits by which ins_h must be shifted at each input
  1088. * step. It must be such that after MIN_MATCH steps, the oldest
  1089. * byte no longer takes part in the hash key, that is:
  1090. * hash_shift * MIN_MATCH >= hash_bits
  1091. */
  1092. this.block_start = 0;
  1093. /* Window position at the beginning of the current output block. Gets
  1094. * negative when the window is moved backwards.
  1095. */
  1096. this.match_length = 0; /* length of best match */
  1097. this.prev_match = 0; /* previous match */
  1098. this.match_available = 0; /* set if previous match exists */
  1099. this.strstart = 0; /* start of string to insert */
  1100. this.match_start = 0; /* start of matching string */
  1101. this.lookahead = 0; /* number of valid bytes ahead in window */
  1102. this.prev_length = 0;
  1103. /* Length of the best match at previous step. Matches not greater than this
  1104. * are discarded. This is used in the lazy match evaluation.
  1105. */
  1106. this.max_chain_length = 0;
  1107. /* To speed up deflation, hash chains are never searched beyond this
  1108. * length. A higher limit improves compression ratio but degrades the
  1109. * speed.
  1110. */
  1111. this.max_lazy_match = 0;
  1112. /* Attempt to find a better match only when the current match is strictly
  1113. * smaller than this value. This mechanism is used only for compression
  1114. * levels >= 4.
  1115. */
  1116. // That's alias to max_lazy_match, don't use directly
  1117. //this.max_insert_length = 0;
  1118. /* Insert new strings in the hash table only if the match length is not
  1119. * greater than this length. This saves time but degrades compression.
  1120. * max_insert_length is used only for compression levels <= 3.
  1121. */
  1122. this.level = 0; /* compression level (1..9) */
  1123. this.strategy = 0; /* favor or force Huffman coding*/
  1124. this.good_match = 0;
  1125. /* Use a faster search when the previous match is longer than this */
  1126. this.nice_match = 0; /* Stop searching when current match exceeds this */
  1127. /* used by trees.c: */
  1128. /* Didn't use ct_data typedef below to suppress compiler warning */
  1129. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  1130. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  1131. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  1132. // Use flat array of DOUBLE size, with interleaved fata,
  1133. // because JS does not support effective
  1134. this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);
  1135. this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);
  1136. this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);
  1137. zero(this.dyn_ltree);
  1138. zero(this.dyn_dtree);
  1139. zero(this.bl_tree);
  1140. this.l_desc = null; /* desc. for literal tree */
  1141. this.d_desc = null; /* desc. for distance tree */
  1142. this.bl_desc = null; /* desc. for bit length tree */
  1143. //ush bl_count[MAX_BITS+1];
  1144. this.bl_count = new Uint16Array(MAX_BITS + 1);
  1145. /* number of codes at each bit length for an optimal tree */
  1146. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  1147. this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  1148. zero(this.heap);
  1149. this.heap_len = 0; /* number of elements in the heap */
  1150. this.heap_max = 0; /* element of largest frequency */
  1151. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  1152. * The same heap array is used to build all trees.
  1153. */
  1154. this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  1155. zero(this.depth);
  1156. /* Depth of each subtree used as tie breaker for trees of equal frequency
  1157. */
  1158. this.sym_buf = 0; /* buffer for distances and literals/lengths */
  1159. this.lit_bufsize = 0;
  1160. /* Size of match buffer for literals/lengths. There are 4 reasons for
  1161. * limiting lit_bufsize to 64K:
  1162. * - frequencies can be kept in 16 bit counters
  1163. * - if compression is not successful for the first block, all input
  1164. * data is still in the window so we can still emit a stored block even
  1165. * when input comes from standard input. (This can also be done for
  1166. * all blocks if lit_bufsize is not greater than 32K.)
  1167. * - if compression is not successful for a file smaller than 64K, we can
  1168. * even emit a stored file instead of a stored block (saving 5 bytes).
  1169. * This is applicable only for zip (not gzip or zlib).
  1170. * - creating new Huffman trees less frequently may not provide fast
  1171. * adaptation to changes in the input data statistics. (Take for
  1172. * example a binary file with poorly compressible code followed by
  1173. * a highly compressible string table.) Smaller buffer sizes give
  1174. * fast adaptation but have of course the overhead of transmitting
  1175. * trees more frequently.
  1176. * - I can't count above 4
  1177. */
  1178. this.sym_next = 0; /* running index in sym_buf */
  1179. this.sym_end = 0; /* symbol table full when sym_next reaches this */
  1180. this.opt_len = 0; /* bit length of current block with optimal trees */
  1181. this.static_len = 0; /* bit length of current block with static trees */
  1182. this.matches = 0; /* number of string matches in current block */
  1183. this.insert = 0; /* bytes at end of window left to insert */
  1184. this.bi_buf = 0;
  1185. /* Output buffer. bits are inserted starting at the bottom (least
  1186. * significant bits).
  1187. */
  1188. this.bi_valid = 0;
  1189. /* Number of valid bits in bi_buf. All bits above the last valid bit
  1190. * are always zero.
  1191. */
  1192. // Used for window memory init. We safely ignore it for JS. That makes
  1193. // sense only for pointers and memory check tools.
  1194. //this.high_water = 0;
  1195. /* High water mark offset in window for initialized bytes -- bytes above
  1196. * this are set to zero in order to avoid memory check warnings when
  1197. * longest match routines access bytes past the input. This is then
  1198. * updated to the new high water mark.
  1199. */
  1200. }
  1201. /* =========================================================================
  1202. * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
  1203. */
  1204. const deflateStateCheck = (strm) => {
  1205. if (!strm) {
  1206. return 1;
  1207. }
  1208. const s = strm.state;
  1209. if (!s || s.strm !== strm || (s.status !== INIT_STATE &&
  1210. //#ifdef GZIP
  1211. s.status !== GZIP_STATE &&
  1212. //#endif
  1213. s.status !== EXTRA_STATE &&
  1214. s.status !== NAME_STATE &&
  1215. s.status !== COMMENT_STATE &&
  1216. s.status !== HCRC_STATE &&
  1217. s.status !== BUSY_STATE &&
  1218. s.status !== FINISH_STATE)) {
  1219. return 1;
  1220. }
  1221. return 0;
  1222. };
  1223. const deflateResetKeep = (strm) => {
  1224. if (deflateStateCheck(strm)) {
  1225. return err(strm, Z_STREAM_ERROR);
  1226. }
  1227. strm.total_in = strm.total_out = 0;
  1228. strm.data_type = Z_UNKNOWN;
  1229. const s = strm.state;
  1230. s.pending = 0;
  1231. s.pending_out = 0;
  1232. if (s.wrap < 0) {
  1233. s.wrap = -s.wrap;
  1234. /* was made negative by deflate(..., Z_FINISH); */
  1235. }
  1236. s.status =
  1237. //#ifdef GZIP
  1238. s.wrap === 2 ? GZIP_STATE :
  1239. //#endif
  1240. s.wrap ? INIT_STATE : BUSY_STATE;
  1241. strm.adler = (s.wrap === 2) ?
  1242. 0 // crc32(0, Z_NULL, 0)
  1243. :
  1244. 1; // adler32(0, Z_NULL, 0)
  1245. s.last_flush = -2;
  1246. _tr_init(s);
  1247. return Z_OK;
  1248. };
  1249. const deflateReset = (strm) => {
  1250. const ret = deflateResetKeep(strm);
  1251. if (ret === Z_OK) {
  1252. lm_init(strm.state);
  1253. }
  1254. return ret;
  1255. };
  1256. const deflateSetHeader = (strm, head) => {
  1257. if (deflateStateCheck(strm) || strm.state.wrap !== 2) {
  1258. return Z_STREAM_ERROR;
  1259. }
  1260. strm.state.gzhead = head;
  1261. return Z_OK;
  1262. };
  1263. const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
  1264. if (!strm) { // === Z_NULL
  1265. return Z_STREAM_ERROR;
  1266. }
  1267. let wrap = 1;
  1268. if (level === Z_DEFAULT_COMPRESSION) {
  1269. level = 6;
  1270. }
  1271. if (windowBits < 0) { /* suppress zlib wrapper */
  1272. wrap = 0;
  1273. windowBits = -windowBits;
  1274. }
  1275. else if (windowBits > 15) {
  1276. wrap = 2; /* write gzip wrapper instead */
  1277. windowBits -= 16;
  1278. }
  1279. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  1280. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  1281. strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {
  1282. return err(strm, Z_STREAM_ERROR);
  1283. }
  1284. if (windowBits === 8) {
  1285. windowBits = 9;
  1286. }
  1287. /* until 256-byte window bug fixed */
  1288. const s = new DeflateState();
  1289. strm.state = s;
  1290. s.strm = strm;
  1291. s.status = INIT_STATE; /* to pass state test in deflateReset() */
  1292. s.wrap = wrap;
  1293. s.gzhead = null;
  1294. s.w_bits = windowBits;
  1295. s.w_size = 1 << s.w_bits;
  1296. s.w_mask = s.w_size - 1;
  1297. s.hash_bits = memLevel + 7;
  1298. s.hash_size = 1 << s.hash_bits;
  1299. s.hash_mask = s.hash_size - 1;
  1300. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  1301. s.window = new Uint8Array(s.w_size * 2);
  1302. s.head = new Uint16Array(s.hash_size);
  1303. s.prev = new Uint16Array(s.w_size);
  1304. // Don't need mem init magic for JS.
  1305. //s.high_water = 0; /* nothing written to s->window yet */
  1306. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  1307. /* We overlay pending_buf and sym_buf. This works since the average size
  1308. * for length/distance pairs over any compressed block is assured to be 31
  1309. * bits or less.
  1310. *
  1311. * Analysis: The longest fixed codes are a length code of 8 bits plus 5
  1312. * extra bits, for lengths 131 to 257. The longest fixed distance codes are
  1313. * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
  1314. * possible fixed-codes length/distance pair is then 31 bits total.
  1315. *
  1316. * sym_buf starts one-fourth of the way into pending_buf. So there are
  1317. * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
  1318. * in sym_buf is three bytes -- two for the distance and one for the
  1319. * literal/length. As each symbol is consumed, the pointer to the next
  1320. * sym_buf value to read moves forward three bytes. From that symbol, up to
  1321. * 31 bits are written to pending_buf. The closest the written pending_buf
  1322. * bits gets to the next sym_buf symbol to read is just before the last
  1323. * code is written. At that time, 31*(n-2) bits have been written, just
  1324. * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
  1325. * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
  1326. * symbols are written.) The closest the writing gets to what is unread is
  1327. * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
  1328. * can range from 128 to 32768.
  1329. *
  1330. * Therefore, at a minimum, there are 142 bits of space between what is
  1331. * written and what is read in the overlain buffers, so the symbols cannot
  1332. * be overwritten by the compressed data. That space is actually 139 bits,
  1333. * due to the three-bit fixed-code block header.
  1334. *
  1335. * That covers the case where either Z_FIXED is specified, forcing fixed
  1336. * codes, or when the use of fixed codes is chosen, because that choice
  1337. * results in a smaller compressed block than dynamic codes. That latter
  1338. * condition then assures that the above analysis also covers all dynamic
  1339. * blocks. A dynamic-code block will only be chosen to be emitted if it has
  1340. * fewer bits than a fixed-code block would for the same set of symbols.
  1341. * Therefore its average symbol length is assured to be less than 31. So
  1342. * the compressed data for a dynamic block also cannot overwrite the
  1343. * symbols from which it is being constructed.
  1344. */
  1345. s.pending_buf_size = s.lit_bufsize * 4;
  1346. s.pending_buf = new Uint8Array(s.pending_buf_size);
  1347. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  1348. //s->sym_buf = s->pending_buf + s->lit_bufsize;
  1349. s.sym_buf = s.lit_bufsize;
  1350. //s->sym_end = (s->lit_bufsize - 1) * 3;
  1351. s.sym_end = (s.lit_bufsize - 1) * 3;
  1352. /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
  1353. * on 16 bit machines and because stored blocks are restricted to
  1354. * 64K-1 bytes.
  1355. */
  1356. s.level = level;
  1357. s.strategy = strategy;
  1358. s.method = method;
  1359. return deflateReset(strm);
  1360. };
  1361. const deflateInit = (strm, level) => {
  1362. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  1363. };
  1364. /* ========================================================================= */
  1365. const deflate = (strm, flush) => {
  1366. if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
  1367. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  1368. }
  1369. const s = strm.state;
  1370. if (!strm.output ||
  1371. (strm.avail_in !== 0 && !strm.input) ||
  1372. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  1373. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  1374. }
  1375. const old_flush = s.last_flush;
  1376. s.last_flush = flush;
  1377. /* Flush as much pending output as possible */
  1378. if (s.pending !== 0) {
  1379. flush_pending(strm);
  1380. if (strm.avail_out === 0) {
  1381. /* Since avail_out is 0, deflate will be called again with
  1382. * more output space, but possibly with both pending and
  1383. * avail_in equal to zero. There won't be anything to do,
  1384. * but this is not an error situation so make sure we
  1385. * return OK instead of BUF_ERROR at next call of deflate:
  1386. */
  1387. s.last_flush = -1;
  1388. return Z_OK;
  1389. }
  1390. /* Make sure there is something to do and avoid duplicate consecutive
  1391. * flushes. For repeated and useless calls with Z_FINISH, we keep
  1392. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  1393. */
  1394. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  1395. flush !== Z_FINISH) {
  1396. return err(strm, Z_BUF_ERROR);
  1397. }
  1398. /* User must not provide more input after the first FINISH: */
  1399. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  1400. return err(strm, Z_BUF_ERROR);
  1401. }
  1402. /* Write the header */
  1403. if (s.status === INIT_STATE && s.wrap === 0) {
  1404. s.status = BUSY_STATE;
  1405. }
  1406. if (s.status === INIT_STATE) {
  1407. /* zlib header */
  1408. let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  1409. let level_flags = -1;
  1410. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  1411. level_flags = 0;
  1412. } else if (s.level < 6) {
  1413. level_flags = 1;
  1414. } else if (s.level === 6) {
  1415. level_flags = 2;
  1416. } else {
  1417. level_flags = 3;
  1418. }
  1419. header |= (level_flags << 6);
  1420. if (s.strstart !== 0) { header |= PRESET_DICT; }
  1421. header += 31 - (header % 31);
  1422. putShortMSB(s, header);
  1423. /* Save the adler32 of the preset dictionary: */
  1424. if (s.strstart !== 0) {
  1425. putShortMSB(s, strm.adler >>> 16);
  1426. putShortMSB(s, strm.adler & 0xffff);
  1427. }
  1428. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  1429. s.status = BUSY_STATE;
  1430. /* Compression must start with an empty pending buffer */
  1431. flush_pending(strm);
  1432. if (s.pending !== 0) {
  1433. s.last_flush = -1;
  1434. return Z_OK;
  1435. }
  1436. }
  1437. //#ifdef GZIP
  1438. if (s.status === GZIP_STATE) {
  1439. /* gzip header */
  1440. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  1441. put_byte(s, 31);
  1442. put_byte(s, 139);
  1443. put_byte(s, 8);
  1444. if (!s.gzhead) { // s->gzhead == Z_NULL
  1445. put_byte(s, 0);
  1446. put_byte(s, 0);
  1447. put_byte(s, 0);
  1448. put_byte(s, 0);
  1449. put_byte(s, 0);
  1450. put_byte(s, s.level === 9 ? 2 :
  1451. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  1452. 4 : 0));
  1453. put_byte(s, OS_CODE);
  1454. s.status = BUSY_STATE;
  1455. /* Compression must start with an empty pending buffer */
  1456. flush_pending(strm);
  1457. if (s.pending !== 0) {
  1458. s.last_flush = -1;
  1459. return Z_OK;
  1460. }
  1461. }
  1462. else {
  1463. put_byte(s, (s.gzhead.text ? 1 : 0) +
  1464. (s.gzhead.hcrc ? 2 : 0) +
  1465. (!s.gzhead.extra ? 0 : 4) +
  1466. (!s.gzhead.name ? 0 : 8) +
  1467. (!s.gzhead.comment ? 0 : 16)
  1468. );
  1469. put_byte(s, s.gzhead.time & 0xff);
  1470. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  1471. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  1472. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  1473. put_byte(s, s.level === 9 ? 2 :
  1474. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  1475. 4 : 0));
  1476. put_byte(s, s.gzhead.os & 0xff);
  1477. if (s.gzhead.extra && s.gzhead.extra.length) {
  1478. put_byte(s, s.gzhead.extra.length & 0xff);
  1479. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  1480. }
  1481. if (s.gzhead.hcrc) {
  1482. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  1483. }
  1484. s.gzindex = 0;
  1485. s.status = EXTRA_STATE;
  1486. }
  1487. }
  1488. if (s.status === EXTRA_STATE) {
  1489. if (s.gzhead.extra/* != Z_NULL*/) {
  1490. let beg = s.pending; /* start of bytes to update crc */
  1491. let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;
  1492. while (s.pending + left > s.pending_buf_size) {
  1493. let copy = s.pending_buf_size - s.pending;
  1494. // zmemcpy(s.pending_buf + s.pending,
  1495. // s.gzhead.extra + s.gzindex, copy);
  1496. s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);
  1497. s.pending = s.pending_buf_size;
  1498. //--- HCRC_UPDATE(beg) ---//
  1499. if (s.gzhead.hcrc && s.pending > beg) {
  1500. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1501. }
  1502. //---//
  1503. s.gzindex += copy;
  1504. flush_pending(strm);
  1505. if (s.pending !== 0) {
  1506. s.last_flush = -1;
  1507. return Z_OK;
  1508. }
  1509. beg = 0;
  1510. left -= copy;
  1511. }
  1512. // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility
  1513. // TypedArray.slice and TypedArray.from don't exist in IE10-IE11
  1514. let gzhead_extra = new Uint8Array(s.gzhead.extra);
  1515. // zmemcpy(s->pending_buf + s->pending,
  1516. // s->gzhead->extra + s->gzindex, left);
  1517. s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);
  1518. s.pending += left;
  1519. //--- HCRC_UPDATE(beg) ---//
  1520. if (s.gzhead.hcrc && s.pending > beg) {
  1521. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1522. }
  1523. //---//
  1524. s.gzindex = 0;
  1525. }
  1526. s.status = NAME_STATE;
  1527. }
  1528. if (s.status === NAME_STATE) {
  1529. if (s.gzhead.name/* != Z_NULL*/) {
  1530. let beg = s.pending; /* start of bytes to update crc */
  1531. let val;
  1532. do {
  1533. if (s.pending === s.pending_buf_size) {
  1534. //--- HCRC_UPDATE(beg) ---//
  1535. if (s.gzhead.hcrc && s.pending > beg) {
  1536. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1537. }
  1538. //---//
  1539. flush_pending(strm);
  1540. if (s.pending !== 0) {
  1541. s.last_flush = -1;
  1542. return Z_OK;
  1543. }
  1544. beg = 0;
  1545. }
  1546. // JS specific: little magic to add zero terminator to end of string
  1547. if (s.gzindex < s.gzhead.name.length) {
  1548. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  1549. } else {
  1550. val = 0;
  1551. }
  1552. put_byte(s, val);
  1553. } while (val !== 0);
  1554. //--- HCRC_UPDATE(beg) ---//
  1555. if (s.gzhead.hcrc && s.pending > beg) {
  1556. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1557. }
  1558. //---//
  1559. s.gzindex = 0;
  1560. }
  1561. s.status = COMMENT_STATE;
  1562. }
  1563. if (s.status === COMMENT_STATE) {
  1564. if (s.gzhead.comment/* != Z_NULL*/) {
  1565. let beg = s.pending; /* start of bytes to update crc */
  1566. let val;
  1567. do {
  1568. if (s.pending === s.pending_buf_size) {
  1569. //--- HCRC_UPDATE(beg) ---//
  1570. if (s.gzhead.hcrc && s.pending > beg) {
  1571. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1572. }
  1573. //---//
  1574. flush_pending(strm);
  1575. if (s.pending !== 0) {
  1576. s.last_flush = -1;
  1577. return Z_OK;
  1578. }
  1579. beg = 0;
  1580. }
  1581. // JS specific: little magic to add zero terminator to end of string
  1582. if (s.gzindex < s.gzhead.comment.length) {
  1583. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  1584. } else {
  1585. val = 0;
  1586. }
  1587. put_byte(s, val);
  1588. } while (val !== 0);
  1589. //--- HCRC_UPDATE(beg) ---//
  1590. if (s.gzhead.hcrc && s.pending > beg) {
  1591. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  1592. }
  1593. //---//
  1594. }
  1595. s.status = HCRC_STATE;
  1596. }
  1597. if (s.status === HCRC_STATE) {
  1598. if (s.gzhead.hcrc) {
  1599. if (s.pending + 2 > s.pending_buf_size) {
  1600. flush_pending(strm);
  1601. if (s.pending !== 0) {
  1602. s.last_flush = -1;
  1603. return Z_OK;
  1604. }
  1605. }
  1606. put_byte(s, strm.adler & 0xff);
  1607. put_byte(s, (strm.adler >> 8) & 0xff);
  1608. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  1609. }
  1610. s.status = BUSY_STATE;
  1611. /* Compression must start with an empty pending buffer */
  1612. flush_pending(strm);
  1613. if (s.pending !== 0) {
  1614. s.last_flush = -1;
  1615. return Z_OK;
  1616. }
  1617. }
  1618. //#endif
  1619. /* Start a new block or continue the current one.
  1620. */
  1621. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  1622. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  1623. let bstate = s.level === 0 ? deflate_stored(s, flush) :
  1624. s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
  1625. s.strategy === Z_RLE ? deflate_rle(s, flush) :
  1626. configuration_table[s.level].func(s, flush);
  1627. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  1628. s.status = FINISH_STATE;
  1629. }
  1630. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  1631. if (strm.avail_out === 0) {
  1632. s.last_flush = -1;
  1633. /* avoid BUF_ERROR next call, see above */
  1634. }
  1635. return Z_OK;
  1636. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  1637. * of deflate should use the same flush parameter to make sure
  1638. * that the flush is complete. So we don't have to output an
  1639. * empty block here, this will be done at next call. This also
  1640. * ensures that for a very small output buffer, we emit at most
  1641. * one empty block.
  1642. */
  1643. }
  1644. if (bstate === BS_BLOCK_DONE) {
  1645. if (flush === Z_PARTIAL_FLUSH) {
  1646. _tr_align(s);
  1647. }
  1648. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  1649. _tr_stored_block(s, 0, 0, false);
  1650. /* For a full flush, this empty block will be recognized
  1651. * as a special marker by inflate_sync().
  1652. */
  1653. if (flush === Z_FULL_FLUSH) {
  1654. /*** CLEAR_HASH(s); ***/ /* forget history */
  1655. zero(s.head); // Fill with NIL (= 0);
  1656. if (s.lookahead === 0) {
  1657. s.strstart = 0;
  1658. s.block_start = 0;
  1659. s.insert = 0;
  1660. }
  1661. }
  1662. }
  1663. flush_pending(strm);
  1664. if (strm.avail_out === 0) {
  1665. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  1666. return Z_OK;
  1667. }
  1668. }
  1669. }
  1670. if (flush !== Z_FINISH) { return Z_OK; }
  1671. if (s.wrap <= 0) { return Z_STREAM_END; }
  1672. /* Write the trailer */
  1673. if (s.wrap === 2) {
  1674. put_byte(s, strm.adler & 0xff);
  1675. put_byte(s, (strm.adler >> 8) & 0xff);
  1676. put_byte(s, (strm.adler >> 16) & 0xff);
  1677. put_byte(s, (strm.adler >> 24) & 0xff);
  1678. put_byte(s, strm.total_in & 0xff);
  1679. put_byte(s, (strm.total_in >> 8) & 0xff);
  1680. put_byte(s, (strm.total_in >> 16) & 0xff);
  1681. put_byte(s, (strm.total_in >> 24) & 0xff);
  1682. }
  1683. else
  1684. {
  1685. putShortMSB(s, strm.adler >>> 16);
  1686. putShortMSB(s, strm.adler & 0xffff);
  1687. }
  1688. flush_pending(strm);
  1689. /* If avail_out is zero, the application will call deflate again
  1690. * to flush the rest.
  1691. */
  1692. if (s.wrap > 0) { s.wrap = -s.wrap; }
  1693. /* write the trailer only once! */
  1694. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  1695. };
  1696. const deflateEnd = (strm) => {
  1697. if (deflateStateCheck(strm)) {
  1698. return Z_STREAM_ERROR;
  1699. }
  1700. const status = strm.state.status;
  1701. strm.state = null;
  1702. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  1703. };
  1704. /* =========================================================================
  1705. * Initializes the compression dictionary from the given byte
  1706. * sequence without producing any compressed output.
  1707. */
  1708. const deflateSetDictionary = (strm, dictionary) => {
  1709. let dictLength = dictionary.length;
  1710. if (deflateStateCheck(strm)) {
  1711. return Z_STREAM_ERROR;
  1712. }
  1713. const s = strm.state;
  1714. const wrap = s.wrap;
  1715. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  1716. return Z_STREAM_ERROR;
  1717. }
  1718. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  1719. if (wrap === 1) {
  1720. /* adler32(strm->adler, dictionary, dictLength); */
  1721. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  1722. }
  1723. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  1724. /* if dictionary would fill window, just replace the history */
  1725. if (dictLength >= s.w_size) {
  1726. if (wrap === 0) { /* already empty otherwise */
  1727. /*** CLEAR_HASH(s); ***/
  1728. zero(s.head); // Fill with NIL (= 0);
  1729. s.strstart = 0;
  1730. s.block_start = 0;
  1731. s.insert = 0;
  1732. }
  1733. /* use the tail */
  1734. // dictionary = dictionary.slice(dictLength - s.w_size);
  1735. let tmpDict = new Uint8Array(s.w_size);
  1736. tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
  1737. dictionary = tmpDict;
  1738. dictLength = s.w_size;
  1739. }
  1740. /* insert dictionary into window and hash */
  1741. const avail = strm.avail_in;
  1742. const next = strm.next_in;
  1743. const input = strm.input;
  1744. strm.avail_in = dictLength;
  1745. strm.next_in = 0;
  1746. strm.input = dictionary;
  1747. fill_window(s);
  1748. while (s.lookahead >= MIN_MATCH) {
  1749. let str = s.strstart;
  1750. let n = s.lookahead - (MIN_MATCH - 1);
  1751. do {
  1752. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  1753. s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
  1754. s.prev[str & s.w_mask] = s.head[s.ins_h];
  1755. s.head[s.ins_h] = str;
  1756. str++;
  1757. } while (--n);
  1758. s.strstart = str;
  1759. s.lookahead = MIN_MATCH - 1;
  1760. fill_window(s);
  1761. }
  1762. s.strstart += s.lookahead;
  1763. s.block_start = s.strstart;
  1764. s.insert = s.lookahead;
  1765. s.lookahead = 0;
  1766. s.match_length = s.prev_length = MIN_MATCH - 1;
  1767. s.match_available = 0;
  1768. strm.next_in = next;
  1769. strm.input = input;
  1770. strm.avail_in = avail;
  1771. s.wrap = wrap;
  1772. return Z_OK;
  1773. };
  1774. module.exports.deflateInit = deflateInit;
  1775. module.exports.deflateInit2 = deflateInit2;
  1776. module.exports.deflateReset = deflateReset;
  1777. module.exports.deflateResetKeep = deflateResetKeep;
  1778. module.exports.deflateSetHeader = deflateSetHeader;
  1779. module.exports.deflate = deflate;
  1780. module.exports.deflateEnd = deflateEnd;
  1781. module.exports.deflateSetDictionary = deflateSetDictionary;
  1782. module.exports.deflateInfo = 'pako deflate (from Nodeca project)';
  1783. /* Not implemented
  1784. module.exports.deflateBound = deflateBound;
  1785. module.exports.deflateCopy = deflateCopy;
  1786. module.exports.deflateGetDictionary = deflateGetDictionary;
  1787. module.exports.deflateParams = deflateParams;
  1788. module.exports.deflatePending = deflatePending;
  1789. module.exports.deflatePrime = deflatePrime;
  1790. module.exports.deflateTune = deflateTune;
  1791. */