Debian Codegraph @

polyfills/zlib-lib/deflate.js

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