You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1850 lines
59 KiB

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