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