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 zlib_deflate = require('./zlib/deflate.js');
6
var utils = require('./utils/common');
7
var strings = require('./utils/strings');
8
var msg = require('./zlib/messages');
9
var zstream = require('./zlib/zstream');
10
11
var toString = Object.prototype.toString;
12
13
/* Public constants ==========================================================*/
14
/* ===========================================================================*/
15
16
var Z_NO_FLUSH = 0;
17
var Z_FINISH = 4;
18
19
var Z_OK = 0;
20
var Z_STREAM_END = 1;
21
22
var Z_DEFAULT_COMPRESSION = -1;
23
24
var Z_DEFAULT_STRATEGY = 0;
25
26
var Z_DEFLATED = 8;
27
28
/* ===========================================================================*/
29
30
31
/**
32
* class Deflate
33
*
34
* Generic JS-style wrapper for zlib calls. If you don't need
35
* streaming behaviour - use more simple functions: [[deflate]],
36
* [[deflateRaw]] and [[gzip]].
37
**/
38
39
/* internal
40
* Deflate.chunks -> Array
41
*
42
* Chunks of output data, if [[Deflate#onData]] not overriden.
43
**/
44
45
/**
46
* Deflate.result -> Uint8Array|Array
47
*
48
* Compressed result, generated by default [[Deflate#onData]]
49
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
50
* (call [[Deflate#push]] with `Z_FINISH` / `true` param).
51
**/
52
53
/**
54
* Deflate.err -> Number
55
*
56
* Error code after deflate finished. 0 (Z_OK) on success.
57
* You will not need it in real life, because deflate errors
58
* are possible only on wrong options or bad `onData` / `onEnd`
59
* custom handlers.
60
**/
61
62
/**
63
* Deflate.msg -> String
64
*
65
* Error message, if [[Deflate.err]] != 0
66
**/
67
68
69
/**
70
* new Deflate(options)
71
* - options (Object): zlib deflate options.
72
*
73
* Creates new deflator instance with specified params. Throws exception
74
* on bad params. Supported options:
75
*
76
* - `level`
77
* - `windowBits`
78
* - `memLevel`
79
* - `strategy`
80
*
81
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
82
* for more information on these.
83
*
84
* Additional options, for internal needs:
85
*
86
* - `chunkSize` - size of generated data chunks (16K by default)
87
* - `raw` (Boolean) - do raw deflate
88
* - `gzip` (Boolean) - create gzip wrapper
89
* - `to` (String) - if equal to 'string', then result will be "binary string"
90
* (each char code [0..255])
91
* - `header` (Object) - custom header for gzip
92
* - `text` (Boolean) - true if compressed data believed to be text
93
* - `time` (Number) - modification time, unix timestamp
94
* - `os` (Number) - operation system code
95
* - `extra` (Array) - array of bytes with extra data (max 65536)
96
* - `name` (String) - file name (binary string)
97
* - `comment` (String) - comment (binary string)
98
* - `hcrc` (Boolean) - true if header crc should be added
99
*
100
* ##### Example:
101
*
102
* ```javascript
103
* var pako = require('pako')
104
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
105
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
106
*
107
* var deflate = new pako.Deflate({ level: 3});
108
*
109
* deflate.push(chunk1, false);
110
* deflate.push(chunk2, true); // true -> last chunk
111
*
112
* if (deflate.err) { throw new Error(deflate.err); }
113
*
114
* console.log(deflate.result);
115
* ```
116
**/
117
var Deflate = function(options) {
118
119
this.options = utils.assign({
120
level: Z_DEFAULT_COMPRESSION,
121
method: Z_DEFLATED,
122
chunkSize: 16384,
123
windowBits: 15,
124
memLevel: 8,
125
strategy: Z_DEFAULT_STRATEGY,
126
to: ''
127
}, options || {});
128
129
var opt = this.options;
130
131
if (opt.raw && (opt.windowBits > 0)) {
132
opt.windowBits = -opt.windowBits;
133
}
134
135
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
136
opt.windowBits += 16;
137
}
138
139
this.err = 0; // error code, if happens (0 = Z_OK)
140
this.msg = ''; // error message
141
this.ended = false; // used to avoid multiple onEnd() calls
142
this.chunks = []; // chunks of compressed data
143
144
this.strm = new zstream();
145
this.strm.avail_out = 0;
146
147
var status = zlib_deflate.deflateInit2(
148
this.strm,
149
opt.level,
150
opt.method,
151
opt.windowBits,
152
opt.memLevel,
153
opt.strategy
154
);
155
156
if (status !== Z_OK) {
157
throw new Error(msg[status]);
158
}
159
160
if (opt.header) {
161
zlib_deflate.deflateSetHeader(this.strm, opt.header);
162
}
163
};
164
165
/**
166
* Deflate#push(data[, mode]) -> Boolean
167
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
168
* converted to utf8 byte sequence.
169
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
170
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
171
*
172
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
173
* new compressed chunks. Returns `true` on success. The last data block must have
174
* mode Z_FINISH (or `true`). That flush internal pending buffers and call
175
* [[Deflate#onEnd]].
176
*
177
* On fail call [[Deflate#onEnd]] with error code and return false.
178
*
179
* We strongly recommend to use `Uint8Array` on input for best speed (output
180
* array format is detected automatically). Also, don't skip last param and always
181
* use the same type in your code (boolean or number). That will improve JS speed.
182
*
183
* For regular `Array`-s make sure all elements are [0..255].
184
*
185
* ##### Example
186
*
187
* ```javascript
188
* push(chunk, false); // push one of data chunks
189
* ...
190
* push(chunk, true); // push last chunk
191
* ```
192
**/
193
Deflate.prototype.push = function(data, mode) {
194
var strm = this.strm;
195
var chunkSize = this.options.chunkSize;
196
var status, _mode;
197
198
if (this.ended) { return false; }
199
200
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
201
202
// Convert data if needed
203
if (typeof data === 'string') {
204
// If we need to compress text, change encoding to utf8.
205
strm.input = strings.string2buf(data);
206
} else if (toString.call(data) === '[object ArrayBuffer]') {
207
strm.input = new Uint8Array(data);
208
} else {
209
strm.input = data;
210
}
211
212
strm.next_in = 0;
213
strm.avail_in = strm.input.length;
214
215
do {
216
if (strm.avail_out === 0) {
217
strm.output = new utils.Buf8(chunkSize);
218
strm.next_out = 0;
219
strm.avail_out = chunkSize;
220
}
221
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
222
223
if (status !== Z_STREAM_END && status !== Z_OK) {
224
this.onEnd(status);
225
this.ended = true;
226
return false;
227
}
228
if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
229
if (this.options.to === 'string') {
230
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
231
} else {
232
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
233
}
234
}
235
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
236
237
// Finalize on the last chunk.
238
if (_mode === Z_FINISH) {
239
status = zlib_deflate.deflateEnd(this.strm);
240
this.onEnd(status);
241
this.ended = true;
242
return status === Z_OK;
243
}
244
245
return true;
246
};
247
248
249
/**
250
* Deflate#onData(chunk) -> Void
251
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
252
* on js engine support. When string output requested, each chunk
253
* will be string.
254
*
255
* By default, stores data blocks in `chunks[]` property and glue
256
* those in `onEnd`. Override this handler, if you need another behaviour.
257
**/
258
Deflate.prototype.onData = function(chunk) {
259
this.chunks.push(chunk);
260
};
261
262
263
/**
264
* Deflate#onEnd(status) -> Void
265
* - status (Number): deflate status. 0 (Z_OK) on success,
266
* other if not.
267
*
268
* Called once after you tell deflate that input stream complete
269
* or error happenned. By default - join collected chunks,
270
* free memory and fill `results` / `err` properties.
271
**/
272
Deflate.prototype.onEnd = function(status) {
273
// On success - join
274
if (status === Z_OK) {
275
if (this.options.to === 'string') {
276
this.result = this.chunks.join('');
277
} else {
278
this.result = utils.flattenChunks(this.chunks);
279
}
280
}
281
this.chunks = [];
282
this.err = status;
283
this.msg = this.strm.msg;
284
};
285
286
287
/**
288
* deflate(data[, options]) -> Uint8Array|Array|String
289
* - data (Uint8Array|Array|String): input data to compress.
290
* - options (Object): zlib deflate options.
291
*
292
* Compress `data` with deflate alrorythm and `options`.
293
*
294
* Supported options are:
295
*
296
* - level
297
* - windowBits
298
* - memLevel
299
* - strategy
300
*
301
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
302
* for more information on these.
303
*
304
* Sugar (options):
305
*
306
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
307
* negative windowBits implicitly.
308
* - `to` (String) - if equal to 'string', then result will be "binary string"
309
* (each char code [0..255])
310
*
311
* ##### Example:
312
*
313
* ```javascript
314
* var pako = require('pako')
315
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
316
*
317
* console.log(pako.deflate(data));
318
* ```
319
**/
320
function deflate(input, options) {
321
var deflator = new Deflate(options);
322
323
deflator.push(input, true);
324
325
// That will never happens, if you don't cheat with options :)
326
if (deflator.err) { throw deflator.msg; }
327
328
return deflator.result;
329
}
330
331
332
/**
333
* deflateRaw(data[, options]) -> Uint8Array|Array|String
334
* - data (Uint8Array|Array|String): input data to compress.
335
* - options (Object): zlib deflate options.
336
*
337
* The same as [[deflate]], but creates raw data, without wrapper
338
* (header and adler32 crc).
339
**/
340
function deflateRaw(input, options) {
341
options = options || {};
342
options.raw = true;
343
return deflate(input, options);
344
}
345
346
347
/**
348
* gzip(data[, options]) -> Uint8Array|Array|String
349
* - data (Uint8Array|Array|String): input data to compress.
350
* - options (Object): zlib deflate options.
351
*
352
* The same as [[deflate]], but create gzip wrapper instead of
353
* deflate one.
354
**/
355
function gzip(input, options) {
356
options = options || {};
357
options.gzip = true;
358
return deflate(input, options);
359
}
360
361
362
exports.Deflate = Deflate;
363
exports.deflate = deflate;
364
exports.deflateRaw = deflateRaw;
365
exports.gzip = gzip;
366
},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate.js":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(require,module,exports){
367
'use strict';
368
369
370
var zlib_inflate = require('./zlib/inflate.js');
371
var utils = require('./utils/common');
372
var strings = require('./utils/strings');
373
var c = require('./zlib/constants');
374
var msg = require('./zlib/messages');
375
var zstream = require('./zlib/zstream');
376
var gzheader = require('./zlib/gzheader');
377
378
var toString = Object.prototype.toString;
379
380
/**
381
* class Inflate
382
*
383
* Generic JS-style wrapper for zlib calls. If you don't need
384
* streaming behaviour - use more simple functions: [[inflate]]
385
* and [[inflateRaw]].
386
**/
387
388
/* internal
389
* inflate.chunks -> Array
390
*
391
* Chunks of output data, if [[Inflate#onData]] not overriden.
392
**/
393
394
/**
395
* Inflate.result -> Uint8Array|Array|String
396
*
397
* Uncompressed result, generated by default [[Inflate#onData]]
398
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
399
* (call [[Inflate#push]] with `Z_FINISH` / `true` param).
400
**/
401
402
/**
403
* Inflate.err -> Number
404
*
405
* Error code after inflate finished. 0 (Z_OK) on success.
406
* Should be checked if broken data possible.
407
**/
408
409
/**
410
* Inflate.msg -> String
411
*
412
* Error message, if [[Inflate.err]] != 0
413
**/
414
415
416
/**
417
* new Inflate(options)
418
* - options (Object): zlib inflate options.
419
*
420
* Creates new inflator instance with specified params. Throws exception
421
* on bad params. Supported options:
422
*
423
* - `windowBits`
424
*
425
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
426
* for more information on these.
427
*
428
* Additional options, for internal needs:
429
*
430
* - `chunkSize` - size of generated data chunks (16K by default)
431
* - `raw` (Boolean) - do raw inflate
432
* - `to` (String) - if equal to 'string', then result will be converted
433
* from utf8 to utf16 (javascript) string. When string output requested,
434
* chunk length can differ from `chunkSize`, depending on content.
435
*
436
* By default, when no options set, autodetect deflate/gzip data format via
437
* wrapper header.
438
*
439
* ##### Example:
440
*
441
* ```javascript
442
* var pako = require('pako')
443
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
444
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
445
*
446
* var inflate = new pako.Inflate({ level: 3});
447
*
448
* inflate.push(chunk1, false);
449
* inflate.push(chunk2, true); // true -> last chunk
450
*
451
* if (inflate.err) { throw new Error(inflate.err); }
452
*
453
* console.log(inflate.result);
454
* ```
455
**/
456
var Inflate = function(options) {
457
458
this.options = utils.assign({
459
chunkSize: 16384,
460
windowBits: 0,
461
to: ''
462
}, options || {});
463
464
var opt = this.options;
465
466
// Force window size for `raw` data, if not set directly,
467
// because we have no header for autodetect.
468
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
469
opt.windowBits = -opt.windowBits;
470
if (opt.windowBits === 0) { opt.windowBits = -15; }
471
}
472
473
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
474
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
475
!(options && options.windowBits)) {
476
opt.windowBits += 32;
477
}
478
479
// Gzip header has no info about windows size, we can do autodetect only
480
// for deflate. So, if window size not set, force it to max when gzip possible
481
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
482
// bit 3 (16) -> gzipped data
483
// bit 4 (32) -> autodetect gzip/deflate
484
if ((opt.windowBits & 15) === 0) {
485
opt.windowBits |= 15;
486
}
487
}
488
489
this.err = 0; // error code, if happens (0 = Z_OK)
490
this.msg = ''; // error message
491
this.ended = false; // used to avoid multiple onEnd() calls
492
this.chunks = []; // chunks of compressed data
493
494
this.strm = new zstream();
495
this.strm.avail_out = 0;
496
497
var status = zlib_inflate.inflateInit2(
498
this.strm,
499
opt.windowBits
500
);
501
502
if (status !== c.Z_OK) {
503
throw new Error(msg[status]);
504
}
505
506
this.header = new gzheader();
507
508
zlib_inflate.inflateGetHeader(this.strm, this.header);
509
};
510
511
/**
512
* Inflate#push(data[, mode]) -> Boolean
513
* - data (Uint8Array|Array|ArrayBuffer|String): input data
514
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
515
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
516
*
517
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
518
* new output chunks. Returns `true` on success. The last data block must have
519
* mode Z_FINISH (or `true`). That flush internal pending buffers and call
520
* [[Inflate#onEnd]].
521
*
522
* On fail call [[Inflate#onEnd]] with error code and return false.
523
*
524
* We strongly recommend to use `Uint8Array` on input for best speed (output
525
* format is detected automatically). Also, don't skip last param and always
526
* use the same type in your code (boolean or number). That will improve JS speed.
527
*
528
* For regular `Array`-s make sure all elements are [0..255].
529
*
530
* ##### Example
531
*
532
* ```javascript
533
* push(chunk, false); // push one of data chunks
534
* ...
535
* push(chunk, true); // push last chunk
536
* ```
537
**/
538
Inflate.prototype.push = function(data, mode) {
539
var strm = this.strm;
540
var chunkSize = this.options.chunkSize;
541
var status, _mode;
542
var next_out_utf8, tail, utf8str;
543
544
if (this.ended) { return false; }
545
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
546
547
// Convert data if needed
548
if (typeof data === 'string') {
549
// Only binary strings can be decompressed on practice
550
strm.input = strings.binstring2buf(data);
551
} else if (toString.call(data) === '[object ArrayBuffer]') {
552
strm.input = new Uint8Array(data);
553
} else {
554
strm.input = data;
555
}
556
557
strm.next_in = 0;
558
strm.avail_in = strm.input.length;
559
560
do {
561
if (strm.avail_out === 0) {
562
strm.output = new utils.Buf8(chunkSize);
563
strm.next_out = 0;
564
strm.avail_out = chunkSize;
565
}
566
567
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
568
569
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
570
this.onEnd(status);
571
this.ended = true;
572
return false;
573
}
574
575
if (strm.next_out) {
576
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
577
578
if (this.options.to === 'string') {
579
580
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
581
582
tail = strm.next_out - next_out_utf8;
583
utf8str = strings.buf2string(strm.output, next_out_utf8);
584
585
// move tail
586
strm.next_out = tail;
587
strm.avail_out = chunkSize - tail;
588
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
589
590
this.onData(utf8str);
591
592
} else {
593
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
594
}
595
}
596
}
597
} while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
598
599
if (status === c.Z_STREAM_END) {
600
_mode = c.Z_FINISH;
601
}
602
// Finalize on the last chunk.
603
if (_mode === c.Z_FINISH) {
604
status = zlib_inflate.inflateEnd(this.strm);
605
this.onEnd(status);
606
this.ended = true;
607
return status === c.Z_OK;
608
}
609
610
return true;
611
};
612
613
614
/**
615
* Inflate#onData(chunk) -> Void
616
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
617
* on js engine support. When string output requested, each chunk
618
* will be string.
619
*
620
* By default, stores data blocks in `chunks[]` property and glue
621
* those in `onEnd`. Override this handler, if you need another behaviour.
622
**/
623
Inflate.prototype.onData = function(chunk) {
624
this.chunks.push(chunk);
625
};
626
627
628
/**
629
* Inflate#onEnd(status) -> Void
630
* - status (Number): inflate status. 0 (Z_OK) on success,
631
* other if not.
632
*
633
* Called once after you tell inflate that input stream complete
634
* or error happenned. By default - join collected chunks,
635
* free memory and fill `results` / `err` properties.
636
**/
637
Inflate.prototype.onEnd = function(status) {
638
// On success - join
639
if (status === c.Z_OK) {
640
if (this.options.to === 'string') {
641
// Glue & convert here, until we teach pako to send
642
// utf8 alligned strings to onData
643
this.result = this.chunks.join('');
644
} else {
645
this.result = utils.flattenChunks(this.chunks);
646
}
647
}
648
this.chunks = [];
649
this.err = status;
650
this.msg = this.strm.msg;
651
};
652
653
654
/**
655
* inflate(data[, options]) -> Uint8Array|Array|String
656
* - data (Uint8Array|Array|String): input data to decompress.
657
* - options (Object): zlib inflate options.
658
*
659
* Decompress `data` with inflate/ungzip and `options`. Autodetect
660
* format via wrapper header by default. That's why we don't provide
661
* separate `ungzip` method.
662
*
663
* Supported options are:
664
*
665
* - windowBits
666
*
667
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
668
* for more information.
669
*
670
* Sugar (options):
671
*
672
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
673
* negative windowBits implicitly.
674
* - `to` (String) - if equal to 'string', then result will be converted
675
* from utf8 to utf16 (javascript) string. When string output requested,
676
* chunk length can differ from `chunkSize`, depending on content.
677
*
678
*
679
* ##### Example:
680
*
681
* ```javascript
682
* var pako = require('pako')
683
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
684
* , output;
685
*
686
* try {
687
* output = pako.inflate(input);
688
* } catch (err)
689
* console.log(err);
690
* }
691
* ```
692
**/
693
function inflate(input, options) {
694
var inflator = new Inflate(options);
695
696
inflator.push(input, true);
697
698
// That will never happens, if you don't cheat with options :)
699
if (inflator.err) { throw inflator.msg; }
700
701
return inflator.result;
702
}
703
704
705
/**
706
* inflateRaw(data[, options]) -> Uint8Array|Array|String
707
* - data (Uint8Array|Array|String): input data to decompress.
708
* - options (Object): zlib inflate options.
709
*
710
* The same as [[inflate]], but creates raw data, without wrapper
711
* (header and adler32 crc).
712
**/
713
function inflateRaw(input, options) {
714
options = options || {};
715
options.raw = true;
716
return inflate(input, options);
717
}
718
719
720
/**
721
* ungzip(data[, options]) -> Uint8Array|Array|String
722
* - data (Uint8Array|Array|String): input data to decompress.
723
* - options (Object): zlib inflate options.
724
*
725
* Just shortcut to [[inflate]], because it autodetects format
726
* by header.content. Done for convenience.
727
**/
728
729
730
exports.Inflate = Inflate;
731
exports.inflate = inflate;
732
exports.inflateRaw = inflateRaw;
733
exports.ungzip = inflate;
734
735
},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate.js":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(require,module,exports){
736
'use strict';
737
738
739
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
740
(typeof Uint16Array !== 'undefined') &&
741
(typeof Int32Array !== 'undefined');
742
743
744
exports.assign = function (obj /*from1, from2, from3, ...*/) {
745
var sources = Array.prototype.slice.call(arguments, 1);
746
while (sources.length) {
747
var source = sources.shift();
748
if (!source) { continue; }
749
750
if (typeof(source) !== 'object') {
751
throw new TypeError(source + 'must be non-object');
752
}
753
754
for (var p in source) {
755
if (source.hasOwnProperty(p)) {
756
obj[p] = source[p];
757
}
758
}
759
}
760
761
return obj;
762
};
763
764
765
// reduce buffer size, avoiding mem copy
766
exports.shrinkBuf = function (buf, size) {
767
if (buf.length === size) { return buf; }
768
if (buf.subarray) { return buf.subarray(0, size); }
769
buf.length = size;
770
return buf;
771
};
772
773
774
var fnTyped = {
775
arraySet: function (dest, src, src_offs, len, dest_offs) {
776
if (src.subarray && dest.subarray) {
777
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
778
return;
779
}
780
// Fallback to ordinary array
781
for(var i=0; i<len; i++) {
782
dest[dest_offs + i] = src[src_offs + i];
783
}
784
},
785
// Join array of chunks to single array.
786
flattenChunks: function(chunks) {
787
var i, l, len, pos, chunk, result;
788
789
// calculate data length
790
len = 0;
791
for (i=0, l=chunks.length; i<l; i++) {
792
len += chunks[i].length;
793
}
794
795
// join chunks
796
result = new Uint8Array(len);
797
pos = 0;
798
for (i=0, l=chunks.length; i<l; i++) {
799
chunk = chunks[i];
800
result.set(chunk, pos);
801
pos += chunk.length;
802
}
803
804
return result;
805
}
806
};
807
808
var fnUntyped = {
809
arraySet: function (dest, src, src_offs, len, dest_offs) {
810
for(var i=0; i<len; i++) {
811
dest[dest_offs + i] = src[src_offs + i];
812
}
813
},
814
// Join array of chunks to single array.
815
flattenChunks: function(chunks) {
816
return [].concat.apply([], chunks);
817
}
818
};
819
820
821
// Enable/Disable typed arrays use, for testing
822
//
823
exports.setTyped = function (on) {
824
if (on) {
825
exports.Buf8 = Uint8Array;
826
exports.Buf16 = Uint16Array;
827
exports.Buf32 = Int32Array;
828
exports.assign(exports, fnTyped);
829
} else {
830
exports.Buf8 = Array;
831
exports.Buf16 = Array;
832
exports.Buf32 = Array;
833
exports.assign(exports, fnUntyped);
834
}
835
};
836
837
exports.setTyped(TYPED_OK);
838
},{}],4:[function(require,module,exports){
839
// String encode/decode helpers
840
'use strict';
841
842
843
var utils = require('./common');
844
845
846
// Quick check if we can use fast array to bin string conversion
847
//
848
// - apply(Array) can fail on Android 2.2
849
// - apply(Uint8Array) can fail on iOS 5.1 Safary
850
//
851
var STR_APPLY_OK = true;
852
var STR_APPLY_UIA_OK = true;
853
854
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
855
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
856
857
858
// Table with utf8 lengths (calculated by first byte of sequence)
859
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
860
// because max possible codepoint is 0x10ffff
861
var _utf8len = new utils.Buf8(256);
862
for (var i=0; i<256; i++) {
863
_utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
864
}
865
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
866
867
868
// convert string to array (typed, when possible)
869
exports.string2buf = function (str) {
870
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
871
872
// count binary size
873
for (m_pos = 0; m_pos < str_len; m_pos++) {
874
c = str.charCodeAt(m_pos);
875
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
876
c2 = str.charCodeAt(m_pos+1);
877
if ((c2 & 0xfc00) === 0xdc00) {
878
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
879
m_pos++;
880
}
881
}
882
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
883
}
884
885
// allocate buffer
886
buf = new utils.Buf8(buf_len);
887
888
// convert
889
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
890
c = str.charCodeAt(m_pos);
891
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
892
c2 = str.charCodeAt(m_pos+1);
893
if ((c2 & 0xfc00) === 0xdc00) {
894
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
895
m_pos++;
896
}
897
}
898
if (c < 0x80) {
899
/* one byte */
900
buf[i++] = c;
901
} else if (c < 0x800) {
902
/* two bytes */
903
buf[i++] = 0xC0 | (c >>> 6);
904
buf[i++] = 0x80 | (c & 0x3f);
905
} else if (c < 0x10000) {
906
/* three bytes */
907
buf[i++] = 0xE0 | (c >>> 12);
908
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
909
buf[i++] = 0x80 | (c & 0x3f);
910
} else {
911
/* four bytes */
912
buf[i++] = 0xf0 | (c >>> 18);
913
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
914
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
915
buf[i++] = 0x80 | (c & 0x3f);
916
}
917
}
918
919
return buf;
920
};
921
922
// Helper (used in 2 places)
923
function buf2binstring(buf, len) {
924
// use fallback for big arrays to avoid stack overflow
925
if (len < 65537) {
926
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
927
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
928
}
929
}
930
931
var result = '';
932
for(var i=0; i < len; i++) {
933
result += String.fromCharCode(buf[i]);
934
}
935
return result;
936
}
937
938
939
// Convert byte array to binary string
940
exports.buf2binstring = function(buf) {
941
return buf2binstring(buf, buf.length);
942
};
943
944
945
// Convert binary string (typed, when possible)
946
exports.binstring2buf = function(str) {
947
var buf = new utils.Buf8(str.length);
948
for(var i=0, len=buf.length; i < len; i++) {
949
buf[i] = str.charCodeAt(i);
950
}
951
return buf;
952
};
953
954
955
// convert array to string
956
exports.buf2string = function (buf, max) {
957
var i, out, c, c_len;
958
var len = max || buf.length;
959
960
// Reserve max possible length (2 words per char)
961
// NB: by unknown reasons, Array is significantly faster for
962
// String.fromCharCode.apply than Uint16Array.
963
var utf16buf = new Array(len*2);
964
965
for (out=0, i=0; i<len;) {
966
c = buf[i++];
967
// quick process ascii
968
if (c < 0x80) { utf16buf[out++] = c; continue; }
969
970
c_len = _utf8len[c];
971
// skip 5 & 6 byte codes
972
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
973
974
// apply mask on first byte
975
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
976
// join the rest
977
while (c_len > 1 && i < len) {
978
c = (c << 6) | (buf[i++] & 0x3f);
979
c_len--;
980
}
981
982
// terminated by end of string?
983
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
984
985
if (c < 0x10000) {
986
utf16buf[out++] = c;
987
} else {
988
c -= 0x10000;
989
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
990
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
991
}
992
}
993
994
return buf2binstring(utf16buf, out);
995
};
996
997
998
// Calculate max possible position in utf8 buffer,
999
// that will not break sequence. If that's not possible
1000
// - (very small limits) return max size as is.
1001
//
1002
// buf[] - utf8 bytes array
1003
// max - length limit (mandatory);
1004
exports.utf8border = function(buf, max) {
1005
var pos;
1006
1007
max = max || buf.length;
1008
if (max > buf.length) { max = buf.length; }
1009
1010
// go back from last position, until start of sequence found
1011
pos = max-1;
1012
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
1013
1014
// Fuckup - very small and broken sequence,
1015
// return max, because we should return something anyway.
1016
if (pos < 0) { return max; }
1017
1018
// If we came to start of buffer - that means vuffer is too small,
1019
// return max too.
1020
if (pos === 0) { return max; }
1021
1022
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
1023
};
1024
1025
},{"./common":3}],5:[function(require,module,exports){
1026
'use strict';
1027
1028
// Note: adler32 takes 12% for level 0 and 2% for level 6.
1029
// It doesn't worth to make additional optimizationa as in original.
1030
// Small size is preferable.
1031
1032
function adler32(adler, buf, len, pos) {
1033
var s1 = (adler & 0xffff) |0
1034
, s2 = ((adler >>> 16) & 0xffff) |0
1035
, n = 0;
1036
1037
while (len !== 0) {
1038
// Set limit ~ twice less than 5552, to keep
1039
// s2 in 31-bits, because we force signed ints.
1040
// in other case %= will fail.
1041
n = len > 2000 ? 2000 : len;
1042
len -= n;
1043
1044
do {
1045
s1 = (s1 + buf[pos++]) |0;
1046
s2 = (s2 + s1) |0;
1047
} while (--n);
1048
1049
s1 %= 65521;
1050
s2 %= 65521;
1051
}
1052
1053
return (s1 | (s2 << 16)) |0;
1054
}
1055
1056
1057
module.exports = adler32;
1058
},{}],6:[function(require,module,exports){
1059
module.exports = {
1060
1061
/* Allowed flush values; see deflate() and inflate() below for details */
1062
Z_NO_FLUSH: 0,
1063
Z_PARTIAL_FLUSH: 1,
1064
Z_SYNC_FLUSH: 2,
1065
Z_FULL_FLUSH: 3,
1066
Z_FINISH: 4,
1067
Z_BLOCK: 5,
1068
Z_TREES: 6,
1069
1070
/* Return codes for the compression/decompression functions. Negative values
1071
* are errors, positive values are used for special but normal events.
1072
*/
1073
Z_OK: 0,
1074
Z_STREAM_END: 1,
1075
Z_NEED_DICT: 2,
1076
Z_ERRNO: -1,
1077
Z_STREAM_ERROR: -2,
1078
Z_DATA_ERROR: -3,
1079
//Z_MEM_ERROR: -4,
1080
Z_BUF_ERROR: -5,
1081
//Z_VERSION_ERROR: -6,
1082
1083
/* compression levels */
1084
Z_NO_COMPRESSION: 0,
1085
Z_BEST_SPEED: 1,
1086
Z_BEST_COMPRESSION: 9,
1087
Z_DEFAULT_COMPRESSION: -1,
1088
1089
1090
Z_FILTERED: 1,
1091
Z_HUFFMAN_ONLY: 2,
1092
Z_RLE: 3,
1093
Z_FIXED: 4,
1094
Z_DEFAULT_STRATEGY: 0,
1095
1096
/* Possible values of the data_type field (though see inflate()) */
1097
Z_BINARY: 0,
1098
Z_TEXT: 1,
1099
//Z_ASCII: 1, // = Z_TEXT (deprecated)
1100
Z_UNKNOWN: 2,
1101
1102
/* The deflate compression method */
1103
Z_DEFLATED: 8
1104
//Z_NULL: null // Use -1 or null inline, depending on var type
1105
};
1106
},{}],7:[function(require,module,exports){
1107
'use strict';
1108
1109
// Note: we can't get significant speed boost here.
1110
// So write code to minimize size - no pregenerated tables
1111
// and array tools dependencies.
1112
1113
1114
// Use ordinary array, since untyped makes no boost here
1115
function makeTable() {
1116
var c, table = [];
1117
1118
for(var n =0; n < 256; n++){
1119
c = n;
1120
for(var k =0; k < 8; k++){
1121
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
1122
}
1123
table[n] = c;
1124
}
1125
1126
return table;
1127
}
1128
1129
// Create table on load. Just 255 signed longs. Not a problem.
1130
var crcTable = makeTable();
1131
1132
1133
function crc32(crc, buf, len, pos) {
1134
var t = crcTable
1135
, end = pos + len;
1136
1137
crc = crc ^ (-1);
1138
1139
for (var i = pos; i < end; i++ ) {
1140
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
1141
}
1142
1143
return (crc ^ (-1)); // >>> 0;
1144
}
1145
1146
1147
module.exports = crc32;
1148
},{}],8:[function(require,module,exports){
1149
'use strict';
1150
1151
var utils = require('../utils/common');
1152
var trees = require('./trees');
1153
var adler32 = require('./adler32');
1154
var crc32 = require('./crc32');
1155
var msg = require('./messages');
1156
1157
/* Public constants ==========================================================*/
1158
/* ===========================================================================*/
1159
1160
1161
/* Allowed flush values; see deflate() and inflate() below for details */
1162
var Z_NO_FLUSH = 0;
1163
var Z_PARTIAL_FLUSH = 1;
1164
//var Z_SYNC_FLUSH = 2;
1165
var Z_FULL_FLUSH = 3;
1166
var Z_FINISH = 4;
1167
var Z_BLOCK = 5;
1168
//var Z_TREES = 6;
1169
1170
1171
/* Return codes for the compression/decompression functions. Negative values
1172
* are errors, positive values are used for special but normal events.
1173
*/
1174
var Z_OK = 0;
1175
var Z_STREAM_END = 1;
1176
//var Z_NEED_DICT = 2;
1177
//var Z_ERRNO = -1;
1178
var Z_STREAM_ERROR = -2;
1179
var Z_DATA_ERROR = -3;
1180
//var Z_MEM_ERROR = -4;
1181
var Z_BUF_ERROR = -5;
1182
//var Z_VERSION_ERROR = -6;
1183
1184
1185
/* compression levels */
1186
//var Z_NO_COMPRESSION = 0;
1187
//var Z_BEST_SPEED = 1;
1188
//var Z_BEST_COMPRESSION = 9;
1189
var Z_DEFAULT_COMPRESSION = -1;
1190
1191
1192
var Z_FILTERED = 1;
1193
var Z_HUFFMAN_ONLY = 2;
1194
var Z_RLE = 3;
1195
var Z_FIXED = 4;
1196
var Z_DEFAULT_STRATEGY = 0;
1197
1198
/* Possible values of the data_type field (though see inflate()) */
1199
//var Z_BINARY = 0;
1200
//var Z_TEXT = 1;
1201
//var Z_ASCII = 1; // = Z_TEXT
1202
var Z_UNKNOWN = 2;
1203
1204
1205
/* The deflate compression method */
1206
var Z_DEFLATED = 8;
1207
1208
/*============================================================================*/
1209
1210
1211
var MAX_MEM_LEVEL = 9;
1212
/* Maximum value for memLevel in deflateInit2 */
1213
var MAX_WBITS = 15;
1214
/* 32K LZ77 window */
1215
var DEF_MEM_LEVEL = 8;
1216
1217
1218
var LENGTH_CODES = 29;
1219
/* number of length codes, not counting the special END_BLOCK code */
1220
var LITERALS = 256;
1221
/* number of literal bytes 0..255 */
1222
var L_CODES = LITERALS + 1 + LENGTH_CODES;
1223
/* number of Literal or Length codes, including the END_BLOCK code */
1224
var D_CODES = 30;
1225
/* number of distance codes */
1226
var BL_CODES = 19;
1227
/* number of codes used to transfer the bit lengths */
1228
var HEAP_SIZE = 2*L_CODES + 1;
1229
/* maximum heap size */
1230
var MAX_BITS = 15;
1231
/* All codes must not exceed MAX_BITS bits */
1232
1233
var MIN_MATCH = 3;
1234
var MAX_MATCH = 258;
1235
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
1236
1237
var PRESET_DICT = 0x20;
1238
1239
var INIT_STATE = 42;
1240
var EXTRA_STATE = 69;
1241
var NAME_STATE = 73;
1242
var COMMENT_STATE = 91;
1243
var HCRC_STATE = 103;
1244
var BUSY_STATE = 113;
1245
var FINISH_STATE = 666;
1246
1247
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
1248
var BS_BLOCK_DONE = 2; /* block flush performed */
1249
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
1250
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
1251
1252
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
1253
1254
function err(strm, errorCode) {
1255
strm.msg = msg[errorCode];
1256
return errorCode;
1257
}
1258
1259
function rank(f) {
1260
return ((f) << 1) - ((f) > 4 ? 9 : 0);
1261
}
1262
1263
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
1264
1265
1266
/* =========================================================================
1267
* Flush as much pending output as possible. All deflate() output goes
1268
* through this function so some applications may wish to modify it
1269
* to avoid allocating a large strm->output buffer and copying into it.
1270
* (See also read_buf()).
1271
*/
1272
function flush_pending(strm) {
1273
var s = strm.state;
1274
1275
//_tr_flush_bits(s);
1276
var len = s.pending;
1277
if (len > strm.avail_out) {
1278
len = strm.avail_out;
1279
}
1280
if (len === 0) { return; }
1281
1282
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
1283
strm.next_out += len;
1284
s.pending_out += len;
1285
strm.total_out += len;
1286
strm.avail_out -= len;
1287
s.pending -= len;
1288
if (s.pending === 0) {
1289
s.pending_out = 0;
1290
}
1291
}
1292
1293
1294
function flush_block_only (s, last) {
1295
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
1296
s.block_start = s.strstart;
1297
flush_pending(s.strm);
1298
}
1299
1300
1301
function put_byte(s, b) {
1302
s.pending_buf[s.pending++] = b;
1303
}
1304
1305
1306
/* =========================================================================
1307
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
1308
* IN assertion: the stream state is correct and there is enough room in
1309
* pending_buf.
1310
*/
1311
function putShortMSB(s, b) {
1312
// put_byte(s, (Byte)(b >> 8));
1313
// put_byte(s, (Byte)(b & 0xff));
1314
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
1315
s.pending_buf[s.pending++] = b & 0xff;
1316
}
1317
1318
1319
/* ===========================================================================
1320
* Read a new buffer from the current input stream, update the adler32
1321
* and total number of bytes read. All deflate() input goes through
1322
* this function so some applications may wish to modify it to avoid
1323
* allocating a large strm->input buffer and copying from it.
1324
* (See also flush_pending()).
1325
*/
1326
function read_buf(strm, buf, start, size) {
1327
var len = strm.avail_in;
1328
1329
if (len > size) { len = size; }
1330
if (len === 0) { return 0; }
1331
1332
strm.avail_in -= len;
1333
1334
utils.arraySet(buf, strm.input, strm.next_in, len, start);
1335
if (strm.state.wrap === 1) {
1336
strm.adler = adler32(strm.adler, buf, len, start);
1337
}
1338
1339
else if (strm.state.wrap === 2) {
1340
strm.adler = crc32(strm.adler, buf, len, start);
1341
}
1342
1343
strm.next_in += len;
1344
strm.total_in += len;
1345
1346
return len;
1347
}
1348
1349
1350
/* ===========================================================================
1351
* Set match_start to the longest match starting at the given string and
1352
* return its length. Matches shorter or equal to prev_length are discarded,
1353
* in which case the result is equal to prev_length and match_start is
1354
* garbage.
1355
* IN assertions: cur_match is the head of the hash chain for the current
1356
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1357
* OUT assertion: the match length is not greater than s->lookahead.
1358
*/
1359
function longest_match(s, cur_match) {
1360
var chain_length = s.max_chain_length; /* max hash chain length */
1361
var scan = s.strstart; /* current string */
1362
var match; /* matched string */
1363
var len; /* length of current match */
1364
var best_len = s.prev_length; /* best match length so far */
1365
var nice_match = s.nice_match; /* stop if match long enough */
1366
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
1367
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
1368
1369
var _win = s.window; // shortcut
1370
1371
var wmask = s.w_mask;
1372
var prev = s.prev;
1373
1374
/* Stop when cur_match becomes <= limit. To simplify the code,
1375
* we prevent matches with the string of window index 0.
1376
*/
1377
1378
var strend = s.strstart + MAX_MATCH;
1379
var scan_end1 = _win[scan + best_len - 1];
1380
var scan_end = _win[scan + best_len];
1381
1382
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1383
* It is easy to get rid of this optimization if necessary.
1384
*/
1385
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1386
1387
/* Do not waste too much time if we already have a good match: */
1388
if (s.prev_length >= s.good_match) {
1389
chain_length >>= 2;
1390
}
1391
/* Do not look for matches beyond the end of the input. This is necessary
1392
* to make deflate deterministic.
1393
*/
1394
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
1395
1396
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1397
1398
do {
1399
// Assert(cur_match < s->strstart, "no future");
1400
match = cur_match;
1401
1402
/* Skip to next match if the match length cannot increase
1403
* or if the match length is less than 2. Note that the checks below
1404
* for insufficient lookahead only occur occasionally for performance
1405
* reasons. Therefore uninitialized memory will be accessed, and
1406
* conditional jumps will be made that depend on those values.
1407
* However the length of the match is limited to the lookahead, so
1408
* the output of deflate is not affected by the uninitialized values.
1409
*/
1410
1411
if (_win[match + best_len] !== scan_end ||
1412
_win[match + best_len - 1] !== scan_end1 ||
1413
_win[match] !== _win[scan] ||
1414
_win[++match] !== _win[scan + 1]) {
1415
continue;
1416
}
1417
1418
/* The check at best_len-1 can be removed because it will be made
1419
* again later. (This heuristic is not always a win.)
1420
* It is not necessary to compare scan[2] and match[2] since they
1421
* are always equal when the other bytes match, given that
1422
* the hash keys are equal and that HASH_BITS >= 8.
1423
*/
1424
scan += 2;
1425
match++;
1426
// Assert(*scan == *match, "match[2]?");
1427
1428
/* We check for insufficient lookahead only every 8th comparison;
1429
* the 256th check will be made at strstart+258.
1430
*/
1431
do {
1432
/*jshint noempty:false*/
1433
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1434
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1435
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1436
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1437
scan < strend);
1438
1439
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1440
1441
len = MAX_MATCH - (strend - scan);
1442
scan = strend - MAX_MATCH;
1443
1444
if (len > best_len) {
1445
s.match_start = cur_match;
1446
best_len = len;
1447
if (len >= nice_match) {
1448
break;
1449
}
1450
scan_end1 = _win[scan + best_len - 1];
1451
scan_end = _win[scan + best_len];
1452
}
1453
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
1454
1455
if (best_len <= s.lookahead) {
1456
return best_len;
1457
}
1458
return s.lookahead;
1459
}
1460
1461
1462
/* ===========================================================================
1463
* Fill the window when the lookahead becomes insufficient.
1464
* Updates strstart and lookahead.
1465
*
1466
* IN assertion: lookahead < MIN_LOOKAHEAD
1467
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1468
* At least one byte has been read, or avail_in == 0; reads are
1469
* performed for at least two bytes (required for the zip translate_eol
1470
* option -- not supported here).
1471
*/
1472
function fill_window(s) {
1473
var _w_size = s.w_size;
1474
var p, n, m, more, str;
1475
1476
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1477
1478
do {
1479
more = s.window_size - s.lookahead - s.strstart;
1480
1481
// JS ints have 32 bit, block below not needed
1482
/* Deal with !@#$% 64K limit: */
1483
//if (sizeof(int) <= 2) {
1484
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1485
// more = wsize;
1486
//
1487
// } else if (more == (unsigned)(-1)) {
1488
// /* Very unlikely, but possible on 16 bit machine if
1489
// * strstart == 0 && lookahead == 1 (input done a byte at time)
1490
// */
1491
// more--;
1492
// }
1493
//}
1494
1495
1496
/* If the window is almost full and there is insufficient lookahead,
1497
* move the upper half to the lower one to make room in the upper half.
1498
*/
1499
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
1500
1501
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
1502
s.match_start -= _w_size;
1503
s.strstart -= _w_size;
1504
/* we now have strstart >= MAX_DIST */
1505
s.block_start -= _w_size;
1506
1507
/* Slide the hash table (could be avoided with 32 bit values
1508
at the expense of memory usage). We slide even when level == 0
1509
to keep the hash table consistent if we switch back to level > 0
1510
later. (Using level 0 permanently is not an optimal usage of
1511
zlib, so we don't care about this pathological case.)
1512
*/
1513
1514
n = s.hash_size;
1515
p = n;
1516
do {
1517
m = s.head[--p];
1518
s.head[p] = (m >= _w_size ? m - _w_size : 0);
1519
} while (--n);
1520
1521
n = _w_size;
1522
p = n;
1523
do {
1524
m = s.prev[--p];
1525
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
1526
/* If n is not on any hash chain, prev[n] is garbage but
1527
* its value will never be used.
1528
*/
1529
} while (--n);
1530
1531
more += _w_size;
1532
}
1533
if (s.strm.avail_in === 0) {
1534
break;
1535
}
1536
1537
/* If there was no sliding:
1538
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1539
* more == window_size - lookahead - strstart
1540
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1541
* => more >= window_size - 2*WSIZE + 2
1542
* In the BIG_MEM or MMAP case (not yet supported),
1543
* window_size == input_size + MIN_LOOKAHEAD &&
1544
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1545
* Otherwise, window_size == 2*WSIZE so more >= 2.
1546
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1547
*/
1548
//Assert(more >= 2, "more < 2");
1549
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
1550
s.lookahead += n;
1551
1552
/* Initialize the hash value now that we have some input: */
1553
if (s.lookahead + s.insert >= MIN_MATCH) {
1554
str = s.strstart - s.insert;
1555
s.ins_h = s.window[str];
1556
1557
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
1558
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
1559
//#if MIN_MATCH != 3
1560
// Call update_hash() MIN_MATCH-3 more times
1561
//#endif
1562
while (s.insert) {
1563
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
1564
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
1565
1566
s.prev[str & s.w_mask] = s.head[s.ins_h];
1567
s.head[s.ins_h] = str;
1568
str++;
1569
s.insert--;
1570
if (s.lookahead + s.insert < MIN_MATCH) {
1571
break;
1572
}
1573
}
1574
}
1575
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1576
* but this is not important since only literal bytes will be emitted.
1577
*/
1578
1579
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
1580
1581
/* If the WIN_INIT bytes after the end of the current data have never been
1582
* written, then zero those bytes in order to avoid memory check reports of
1583
* the use of uninitialized (or uninitialised as Julian writes) bytes by
1584
* the longest match routines. Update the high water mark for the next
1585
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
1586
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1587
*/
1588
// if (s.high_water < s.window_size) {
1589
// var curr = s.strstart + s.lookahead;
1590
// var init = 0;
1591
//
1592
// if (s.high_water < curr) {
1593
// /* Previous high water mark below current data -- zero WIN_INIT
1594
// * bytes or up to end of window, whichever is less.
1595
// */
1596
// init = s.window_size - curr;
1597
// if (init > WIN_INIT)
1598
// init = WIN_INIT;
1599
// zmemzero(s->window + curr, (unsigned)init);
1600
// s->high_water = curr + init;
1601
// }
1602
// else if (s->high_water < (ulg)curr + WIN_INIT) {
1603
// /* High water mark at or above current data, but below current data
1604
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1605
// * to end of window, whichever is less.
1606
// */
1607
// init = (ulg)curr + WIN_INIT - s->high_water;
1608
// if (init > s->window_size - s->high_water)
1609
// init = s->window_size - s->high_water;
1610
// zmemzero(s->window + s->high_water, (unsigned)init);
1611
// s->high_water += init;
1612
// }
1613
// }
1614
//
1615
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1616
// "not enough room for search");
1617
}
1618
1619
/* ===========================================================================
1620
* Copy without compression as much as possible from the input stream, return
1621
* the current block state.
1622
* This function does not insert new strings in the dictionary since
1623
* uncompressible data is probably not useful. This function is used
1624
* only for the level=0 compression option.
1625
* NOTE: this function should be optimized to avoid extra copying from
1626
* window to pending_buf.
1627
*/
1628
function deflate_stored(s, flush) {
1629
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1630
* to pending_buf_size, and each stored block has a 5 byte header:
1631
*/
1632
var max_block_size = 0xffff;
1633
1634
if (max_block_size > s.pending_buf_size - 5) {
1635
max_block_size = s.pending_buf_size - 5;
1636
}
1637
1638
/* Copy as much as possible from input to output: */
1639
for (;;) {
1640
/* Fill the window as much as possible: */
1641
if (s.lookahead <= 1) {
1642
1643
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1644
// s->block_start >= (long)s->w_size, "slide too late");
1645
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
1646
// s.block_start >= s.w_size)) {
1647
// throw new Error("slide too late");
1648
// }
1649
1650
fill_window(s);
1651
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
1652
return BS_NEED_MORE;
1653
}
1654
1655
if (s.lookahead === 0) {
1656
break;
1657
}
1658
/* flush the current block */
1659
}
1660
//Assert(s->block_start >= 0L, "block gone");
1661
// if (s.block_start < 0) throw new Error("block gone");
1662
1663
s.strstart += s.lookahead;
1664
s.lookahead = 0;
1665
1666
/* Emit a stored block if pending_buf will be full: */
1667
var max_start = s.block_start + max_block_size;
1668
1669
if (s.strstart === 0 || s.strstart >= max_start) {
1670
/* strstart == 0 is possible when wraparound on 16-bit machine */
1671
s.lookahead = s.strstart - max_start;
1672
s.strstart = max_start;
1673
/*** FLUSH_BLOCK(s, 0); ***/
1674
flush_block_only(s, false);
1675
if (s.strm.avail_out === 0) {
1676
return BS_NEED_MORE;
1677
}
1678
/***/
1679
1680
1681
}
1682
/* Flush if we may have to slide, otherwise block_start may become
1683
* negative and the data will be gone:
1684
*/
1685
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
1686
/*** FLUSH_BLOCK(s, 0); ***/
1687
flush_block_only(s, false);
1688
if (s.strm.avail_out === 0) {
1689
return BS_NEED_MORE;
1690
}
1691
/***/
1692
}
1693
}
1694
1695
s.insert = 0;
1696
1697
if (flush === Z_FINISH) {
1698
/*** FLUSH_BLOCK(s, 1); ***/
1699
flush_block_only(s, true);
1700
if (s.strm.avail_out === 0) {
1701
return BS_FINISH_STARTED;
1702
}
1703
/***/
1704
return BS_FINISH_DONE;
1705
}
1706
1707
if (s.strstart > s.block_start) {
1708
/*** FLUSH_BLOCK(s, 0); ***/
1709
flush_block_only(s, false);
1710
if (s.strm.avail_out === 0) {
1711
return BS_NEED_MORE;
1712
}
1713
/***/
1714
}
1715
1716
return BS_NEED_MORE;
1717
}
1718
1719
/* ===========================================================================
1720
* Compress as much as possible from the input stream, return the current
1721
* block state.
1722
* This function does not perform lazy evaluation of matches and inserts
1723
* new strings in the dictionary only for unmatched strings or for short
1724
* matches. It is used only for the fast compression options.
1725
*/
1726
function deflate_fast(s, flush) {
1727
var hash_head; /* head of the hash chain */
1728
var bflush; /* set if current block must be flushed */
1729
1730
for (;;) {
1731
/* Make sure that we always have enough lookahead, except
1732
* at the end of the input file. We need MAX_MATCH bytes
1733
* for the next match, plus MIN_MATCH bytes to insert the
1734
* string following the next match.
1735
*/
1736
if (s.lookahead < MIN_LOOKAHEAD) {
1737
fill_window(s);
1738
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
1739
return BS_NEED_MORE;
1740
}
1741
if (s.lookahead === 0) {
1742
break; /* flush the current block */
1743
}
1744
}
1745
1746
/* Insert the string window[strstart .. strstart+2] in the
1747
* dictionary, and set hash_head to the head of the hash chain:
1748
*/
1749
hash_head = 0/*NIL*/;
1750
if (s.lookahead >= MIN_MATCH) {
1751
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
1752
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1753
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1754
s.head[s.ins_h] = s.strstart;
1755
/***/
1756
}
1757
1758
/* Find the longest match, discarding those <= prev_length.
1759
* At this point we have always match_length < MIN_MATCH
1760
*/
1761
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
1762
/* To simplify the code, we prevent matches with the string
1763
* of window index 0 (in particular we have to avoid a match
1764
* of the string with itself at the start of the input file).
1765
*/
1766
s.match_length = longest_match(s, hash_head);
1767
/* longest_match() sets match_start */
1768
}
1769
if (s.match_length >= MIN_MATCH) {
1770
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
1771
1772
/*** _tr_tally_dist(s, s.strstart - s.match_start,
1773
s.match_length - MIN_MATCH, bflush); ***/
1774
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
1775
1776
s.lookahead -= s.match_length;
1777
1778
/* Insert new strings in the hash table only if the match length
1779
* is not too large. This saves time but degrades compression.
1780
*/
1781
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
1782
s.match_length--; /* string at strstart already in table */
1783
do {
1784
s.strstart++;
1785
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
1786
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1787
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1788
s.head[s.ins_h] = s.strstart;
1789
/***/
1790
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
1791
* always MIN_MATCH bytes ahead.
1792
*/
1793
} while (--s.match_length !== 0);
1794
s.strstart++;
1795
} else
1796
{
1797
s.strstart += s.match_length;
1798
s.match_length = 0;
1799
s.ins_h = s.window[s.strstart];
1800
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
1801
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
1802
1803
//#if MIN_MATCH != 3
1804
// Call UPDATE_HASH() MIN_MATCH-3 more times
1805
//#endif
1806
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1807
* matter since it will be recomputed at next deflate call.
1808
*/
1809
}
1810
} else {
1811
/* No match, output a literal byte */
1812
//Tracevv((stderr,"%c", s.window[s.strstart]));
1813
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
1814
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
1815
1816
s.lookahead--;
1817
s.strstart++;
1818
}
1819
if (bflush) {
1820
/*** FLUSH_BLOCK(s, 0); ***/
1821
flush_block_only(s, false);
1822
if (s.strm.avail_out === 0) {
1823
return BS_NEED_MORE;
1824
}
1825
/***/
1826
}
1827
}
1828
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
1829
if (flush === Z_FINISH) {
1830
/*** FLUSH_BLOCK(s, 1); ***/
1831
flush_block_only(s, true);
1832
if (s.strm.avail_out === 0) {
1833
return BS_FINISH_STARTED;
1834
}
1835
/***/
1836
return BS_FINISH_DONE;
1837
}
1838
if (s.last_lit) {
1839
/*** FLUSH_BLOCK(s, 0); ***/
1840
flush_block_only(s, false);
1841
if (s.strm.avail_out === 0) {
1842
return BS_NEED_MORE;
1843
}
1844
/***/
1845
}
1846
return BS_BLOCK_DONE;
1847
}
1848
1849
/* ===========================================================================
1850
* Same as above, but achieves better compression. We use a lazy
1851
* evaluation for matches: a match is finally adopted only if there is
1852
* no better match at the next window position.
1853
*/
1854
function deflate_slow(s, flush) {
1855
var hash_head; /* head of hash chain */
1856
var bflush; /* set if current block must be flushed */
1857
1858
var max_insert;
1859
1860
/* Process the input block. */
1861
for (;;) {
1862
/* Make sure that we always have enough lookahead, except
1863
* at the end of the input file. We need MAX_MATCH bytes
1864
* for the next match, plus MIN_MATCH bytes to insert the
1865
* string following the next match.
1866
*/
1867
if (s.lookahead < MIN_LOOKAHEAD) {
1868
fill_window(s);
1869
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
1870
return BS_NEED_MORE;
1871
}
1872
if (s.lookahead === 0) { break; } /* flush the current block */
1873
}
1874
1875
/* Insert the string window[strstart .. strstart+2] in the
1876
* dictionary, and set hash_head to the head of the hash chain:
1877
*/
1878
hash_head = 0/*NIL*/;
1879
if (s.lookahead >= MIN_MATCH) {
1880
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
1881
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1882
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1883
s.head[s.ins_h] = s.strstart;
1884
/***/
1885
}
1886
1887
/* Find the longest match, discarding those <= prev_length.
1888
*/
1889
s.prev_length = s.match_length;
1890
s.prev_match = s.match_start;
1891
s.match_length = MIN_MATCH-1;
1892
1893
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
1894
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
1895
/* To simplify the code, we prevent matches with the string
1896
* of window index 0 (in particular we have to avoid a match
1897
* of the string with itself at the start of the input file).
1898
*/
1899
s.match_length = longest_match(s, hash_head);
1900
/* longest_match() sets match_start */
1901
1902
if (s.match_length <= 5 &&
1903
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
1904
1905
/* If prev_match is also MIN_MATCH, match_start is garbage
1906
* but we will ignore the current match anyway.
1907
*/
1908
s.match_length = MIN_MATCH-1;
1909
}
1910
}
1911
/* If there was a match at the previous step and the current
1912
* match is not better, output the previous match:
1913
*/
1914
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
1915
max_insert = s.strstart + s.lookahead - MIN_MATCH;
1916
/* Do not insert strings in hash table beyond this. */
1917
1918
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
1919
1920
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
1921
s.prev_length - MIN_MATCH, bflush);***/
1922
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
1923
/* Insert in hash table all strings up to the end of the match.
1924
* strstart-1 and strstart are already inserted. If there is not
1925
* enough lookahead, the last two strings are not inserted in
1926
* the hash table.
1927
*/
1928
s.lookahead -= s.prev_length-1;
1929
s.prev_length -= 2;
1930
do {
1931
if (++s.strstart <= max_insert) {
1932
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
1933
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1934
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1935
s.head[s.ins_h] = s.strstart;
1936
/***/
1937
}
1938
} while (--s.prev_length !== 0);
1939
s.match_available = 0;
1940
s.match_length = MIN_MATCH-1;
1941
s.strstart++;
1942
1943
if (bflush) {
1944
/*** FLUSH_BLOCK(s, 0); ***/
1945
flush_block_only(s, false);
1946
if (s.strm.avail_out === 0) {
1947
return BS_NEED_MORE;
1948
}
1949
/***/
1950
}
1951
1952
} else if (s.match_available) {
1953
/* If there was no match at the previous position, output a
1954
* single literal. If there was a match but the current match
1955
* is longer, truncate the previous match to a single literal.
1956
*/
1957
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
1958
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
1959
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
1960
1961
if (bflush) {
1962
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
1963
flush_block_only(s, false);
1964
/***/
1965
}
1966
s.strstart++;
1967
s.lookahead--;
1968
if (s.strm.avail_out === 0) {
1969
return BS_NEED_MORE;
1970
}
1971
} else {
1972
/* There is no previous match to compare with, wait for
1973
* the next step to decide.
1974
*/
1975
s.match_available = 1;
1976
s.strstart++;
1977
s.lookahead--;
1978
}
1979
}
1980
//Assert (flush != Z_NO_FLUSH, "no flush?");
1981
if (s.match_available) {
1982
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
1983
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
1984
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
1985
1986
s.match_available = 0;
1987
}
1988
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
1989
if (flush === Z_FINISH) {
1990
/*** FLUSH_BLOCK(s, 1); ***/
1991
flush_block_only(s, true);
1992
if (s.strm.avail_out === 0) {
1993
return BS_FINISH_STARTED;
1994
}
1995
/***/
1996
return BS_FINISH_DONE;
1997
}
1998
if (s.last_lit) {
1999
/*** FLUSH_BLOCK(s, 0); ***/
2000
flush_block_only(s, false);
2001
if (s.strm.avail_out === 0) {
2002
return BS_NEED_MORE;
2003
}
2004
/***/
2005
}
2006
2007
return BS_BLOCK_DONE;
2008
}
2009
2010
2011
/* ===========================================================================
2012
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
2013
* one. Do not maintain a hash table. (It will be regenerated if this run of
2014
* deflate switches away from Z_RLE.)
2015
*/
2016
function deflate_rle(s, flush) {
2017
var bflush; /* set if current block must be flushed */
2018
var prev; /* byte at distance one to match */
2019
var scan, strend; /* scan goes up to strend for length of run */
2020
2021
var _win = s.window;
2022
2023
for (;;) {
2024
/* Make sure that we always have enough lookahead, except
2025
* at the end of the input file. We need MAX_MATCH bytes
2026
* for the longest run, plus one for the unrolled loop.
2027
*/
2028
if (s.lookahead <= MAX_MATCH) {
2029
fill_window(s);
2030
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
2031
return BS_NEED_MORE;
2032
}
2033
if (s.lookahead === 0) { break; } /* flush the current block */
2034
}
2035
2036
/* See how many times the previous byte repeats */
2037
s.match_length = 0;
2038
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
2039
scan = s.strstart - 1;
2040
prev = _win[scan];
2041
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
2042
strend = s.strstart + MAX_MATCH;
2043
do {
2044
/*jshint noempty:false*/
2045
} while (prev === _win[++scan] && prev === _win[++scan] &&
2046
prev === _win[++scan] && prev === _win[++scan] &&
2047
prev === _win[++scan] && prev === _win[++scan] &&
2048
prev === _win[++scan] && prev === _win[++scan] &&
2049
scan < strend);
2050
s.match_length = MAX_MATCH - (strend - scan);
2051
if (s.match_length > s.lookahead) {
2052
s.match_length = s.lookahead;
2053
}
2054
}
2055
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2056
}
2057
2058
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
2059
if (s.match_length >= MIN_MATCH) {
2060
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
2061
2062
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
2063
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
2064
2065
s.lookahead -= s.match_length;
2066
s.strstart += s.match_length;
2067
s.match_length = 0;
2068
} else {
2069
/* No match, output a literal byte */
2070
//Tracevv((stderr,"%c", s->window[s->strstart]));
2071
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2072
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2073
2074
s.lookahead--;
2075
s.strstart++;
2076
}
2077
if (bflush) {
2078
/*** FLUSH_BLOCK(s, 0); ***/
2079
flush_block_only(s, false);
2080
if (s.strm.avail_out === 0) {
2081
return BS_NEED_MORE;
2082
}
2083
/***/
2084
}
2085
}
2086
s.insert = 0;
2087
if (flush === Z_FINISH) {
2088
/*** FLUSH_BLOCK(s, 1); ***/
2089
flush_block_only(s, true);
2090
if (s.strm.avail_out === 0) {
2091
return BS_FINISH_STARTED;
2092
}
2093
/***/
2094
return BS_FINISH_DONE;
2095
}
2096
if (s.last_lit) {
2097
/*** FLUSH_BLOCK(s, 0); ***/
2098
flush_block_only(s, false);
2099
if (s.strm.avail_out === 0) {
2100
return BS_NEED_MORE;
2101
}
2102
/***/
2103
}
2104
return BS_BLOCK_DONE;
2105
}
2106
2107
/* ===========================================================================
2108
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
2109
* (It will be regenerated if this run of deflate switches away from Huffman.)
2110
*/
2111
function deflate_huff(s, flush) {
2112
var bflush; /* set if current block must be flushed */
2113
2114
for (;;) {
2115
/* Make sure that we have a literal to write. */
2116
if (s.lookahead === 0) {
2117
fill_window(s);
2118
if (s.lookahead === 0) {
2119
if (flush === Z_NO_FLUSH) {
2120
return BS_NEED_MORE;
2121
}
2122
break; /* flush the current block */
2123
}
2124
}
2125
2126
/* Output a literal byte */
2127
s.match_length = 0;
2128
//Tracevv((stderr,"%c", s->window[s->strstart]));
2129
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2130
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2131
s.lookahead--;
2132
s.strstart++;
2133
if (bflush) {
2134
/*** FLUSH_BLOCK(s, 0); ***/
2135
flush_block_only(s, false);
2136
if (s.strm.avail_out === 0) {
2137
return BS_NEED_MORE;
2138
}
2139
/***/
2140
}
2141
}
2142
s.insert = 0;
2143
if (flush === Z_FINISH) {
2144
/*** FLUSH_BLOCK(s, 1); ***/
2145
flush_block_only(s, true);
2146
if (s.strm.avail_out === 0) {
2147
return BS_FINISH_STARTED;
2148
}
2149
/***/
2150
return BS_FINISH_DONE;
2151
}
2152
if (s.last_lit) {
2153
/*** FLUSH_BLOCK(s, 0); ***/
2154
flush_block_only(s, false);
2155
if (s.strm.avail_out === 0) {
2156
return BS_NEED_MORE;
2157
}
2158
/***/
2159
}
2160
return BS_BLOCK_DONE;
2161
}
2162
2163
/* Values for max_lazy_match, good_match and max_chain_length, depending on
2164
* the desired pack level (0..9). The values given below have been tuned to
2165
* exclude worst case performance for pathological files. Better values may be
2166
* found for specific files.
2167
*/
2168
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
2169
this.good_length = good_length;
2170
this.max_lazy = max_lazy;
2171
this.nice_length = nice_length;
2172
this.max_chain = max_chain;
2173
this.func = func;
2174
};
2175
2176
var configuration_table;
2177
2178
configuration_table = [
2179
/* good lazy nice chain */
2180
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
2181
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
2182
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
2183
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
2184
2185
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
2186
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
2187
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
2188
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
2189
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
2190
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
2191
];
2192
2193
2194
/* ===========================================================================
2195
* Initialize the "longest match" routines for a new zlib stream
2196
*/
2197
function lm_init(s) {
2198
s.window_size = 2 * s.w_size;
2199
2200
/*** CLEAR_HASH(s); ***/
2201
zero(s.head); // Fill with NIL (= 0);
2202
2203
/* Set the default configuration parameters:
2204
*/
2205
s.max_lazy_match = configuration_table[s.level].max_lazy;
2206
s.good_match = configuration_table[s.level].good_length;
2207
s.nice_match = configuration_table[s.level].nice_length;
2208
s.max_chain_length = configuration_table[s.level].max_chain;
2209
2210
s.strstart = 0;
2211
s.block_start = 0;
2212
s.lookahead = 0;
2213
s.insert = 0;
2214
s.match_length = s.prev_length = MIN_MATCH - 1;
2215
s.match_available = 0;
2216
s.ins_h = 0;
2217
}
2218
2219
2220
function DeflateState() {
2221
this.strm = null; /* pointer back to this zlib stream */
2222
this.status = 0; /* as the name implies */
2223
this.pending_buf = null; /* output still pending */
2224
this.pending_buf_size = 0; /* size of pending_buf */
2225
this.pending_out = 0; /* next pending byte to output to the stream */
2226
this.pending = 0; /* nb of bytes in the pending buffer */
2227
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
2228
this.gzhead = null; /* gzip header information to write */
2229
this.gzindex = 0; /* where in extra, name, or comment */
2230
this.method = Z_DEFLATED; /* can only be DEFLATED */
2231
this.last_flush = -1; /* value of flush param for previous deflate call */
2232
2233
this.w_size = 0; /* LZ77 window size (32K by default) */
2234
this.w_bits = 0; /* log2(w_size) (8..16) */
2235
this.w_mask = 0; /* w_size - 1 */
2236
2237
this.window = null;
2238
/* Sliding window. Input bytes are read into the second half of the window,
2239
* and move to the first half later to keep a dictionary of at least wSize
2240
* bytes. With this organization, matches are limited to a distance of
2241
* wSize-MAX_MATCH bytes, but this ensures that IO is always
2242
* performed with a length multiple of the block size.
2243
*/
2244
2245
this.window_size = 0;
2246
/* Actual size of window: 2*wSize, except when the user input buffer
2247
* is directly used as sliding window.
2248
*/
2249
2250
this.prev = null;
2251
/* Link to older string with same hash index. To limit the size of this
2252
* array to 64K, this link is maintained only for the last 32K strings.
2253
* An index in this array is thus a window index modulo 32K.
2254
*/
2255
2256
this.head = null; /* Heads of the hash chains or NIL. */
2257
2258
this.ins_h = 0; /* hash index of string to be inserted */
2259
this.hash_size = 0; /* number of elements in hash table */
2260
this.hash_bits = 0; /* log2(hash_size) */
2261
this.hash_mask = 0; /* hash_size-1 */
2262
2263
this.hash_shift = 0;
2264
/* Number of bits by which ins_h must be shifted at each input
2265
* step. It must be such that after MIN_MATCH steps, the oldest
2266
* byte no longer takes part in the hash key, that is:
2267
* hash_shift * MIN_MATCH >= hash_bits
2268
*/
2269
2270
this.block_start = 0;
2271
/* Window position at the beginning of the current output block. Gets
2272
* negative when the window is moved backwards.
2273
*/
2274
2275
this.match_length = 0; /* length of best match */
2276
this.prev_match = 0; /* previous match */
2277
this.match_available = 0; /* set if previous match exists */
2278
this.strstart = 0; /* start of string to insert */
2279
this.match_start = 0; /* start of matching string */
2280
this.lookahead = 0; /* number of valid bytes ahead in window */
2281
2282
this.prev_length = 0;
2283
/* Length of the best match at previous step. Matches not greater than this
2284
* are discarded. This is used in the lazy match evaluation.
2285
*/
2286
2287
this.max_chain_length = 0;
2288
/* To speed up deflation, hash chains are never searched beyond this
2289
* length. A higher limit improves compression ratio but degrades the
2290
* speed.
2291
*/
2292
2293
this.max_lazy_match = 0;
2294
/* Attempt to find a better match only when the current match is strictly
2295
* smaller than this value. This mechanism is used only for compression
2296
* levels >= 4.
2297
*/
2298
// That's alias to max_lazy_match, don't use directly
2299
//this.max_insert_length = 0;
2300
/* Insert new strings in the hash table only if the match length is not
2301
* greater than this length. This saves time but degrades compression.
2302
* max_insert_length is used only for compression levels <= 3.
2303
*/
2304
2305
this.level = 0; /* compression level (1..9) */
2306
this.strategy = 0; /* favor or force Huffman coding*/
2307
2308
this.good_match = 0;
2309
/* Use a faster search when the previous match is longer than this */
2310
2311
this.nice_match = 0; /* Stop searching when current match exceeds this */
2312
2313
/* used by trees.c: */
2314
2315
/* Didn't use ct_data typedef below to suppress compiler warning */
2316
2317
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
2318
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
2319
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
2320
2321
// Use flat array of DOUBLE size, with interleaved fata,
2322
// because JS does not support effective
2323
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
2324
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
2325
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
2326
zero(this.dyn_ltree);
2327
zero(this.dyn_dtree);
2328
zero(this.bl_tree);
2329
2330
this.l_desc = null; /* desc. for literal tree */
2331
this.d_desc = null; /* desc. for distance tree */
2332
this.bl_desc = null; /* desc. for bit length tree */
2333
2334
//ush bl_count[MAX_BITS+1];
2335
this.bl_count = new utils.Buf16(MAX_BITS+1);
2336
/* number of codes at each bit length for an optimal tree */
2337
2338
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
2339
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
2340
zero(this.heap);
2341
2342
this.heap_len = 0; /* number of elements in the heap */
2343
this.heap_max = 0; /* element of largest frequency */
2344
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2345
* The same heap array is used to build all trees.
2346
*/
2347
2348
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
2349
zero(this.depth);
2350
/* Depth of each subtree used as tie breaker for trees of equal frequency
2351
*/
2352
2353
this.l_buf = 0; /* buffer index for literals or lengths */
2354
2355
this.lit_bufsize = 0;
2356
/* Size of match buffer for literals/lengths. There are 4 reasons for
2357
* limiting lit_bufsize to 64K:
2358
* - frequencies can be kept in 16 bit counters
2359
* - if compression is not successful for the first block, all input
2360
* data is still in the window so we can still emit a stored block even
2361
* when input comes from standard input. (This can also be done for
2362
* all blocks if lit_bufsize is not greater than 32K.)
2363
* - if compression is not successful for a file smaller than 64K, we can
2364
* even emit a stored file instead of a stored block (saving 5 bytes).
2365
* This is applicable only for zip (not gzip or zlib).
2366
* - creating new Huffman trees less frequently may not provide fast
2367
* adaptation to changes in the input data statistics. (Take for
2368
* example a binary file with poorly compressible code followed by
2369
* a highly compressible string table.) Smaller buffer sizes give
2370
* fast adaptation but have of course the overhead of transmitting
2371
* trees more frequently.
2372
* - I can't count above 4
2373
*/
2374
2375
this.last_lit = 0; /* running index in l_buf */
2376
2377
this.d_buf = 0;
2378
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
2379
* the same number of elements. To use different lengths, an extra flag
2380
* array would be necessary.
2381
*/
2382
2383
this.opt_len = 0; /* bit length of current block with optimal trees */
2384
this.static_len = 0; /* bit length of current block with static trees */
2385
this.matches = 0; /* number of string matches in current block */
2386
this.insert = 0; /* bytes at end of window left to insert */
2387
2388
2389
this.bi_buf = 0;
2390
/* Output buffer. bits are inserted starting at the bottom (least
2391
* significant bits).
2392
*/
2393
this.bi_valid = 0;
2394
/* Number of valid bits in bi_buf. All bits above the last valid bit
2395
* are always zero.
2396
*/
2397
2398
// Used for window memory init. We safely ignore it for JS. That makes
2399
// sense only for pointers and memory check tools.
2400
//this.high_water = 0;
2401
/* High water mark offset in window for initialized bytes -- bytes above
2402
* this are set to zero in order to avoid memory check warnings when
2403
* longest match routines access bytes past the input. This is then
2404
* updated to the new high water mark.
2405
*/
2406
}
2407
2408
2409
function deflateResetKeep(strm) {
2410
var s;
2411
2412
if (!strm || !strm.state) {
2413
return err(strm, Z_STREAM_ERROR);
2414
}
2415
2416
strm.total_in = strm.total_out = 0;
2417
strm.data_type = Z_UNKNOWN;
2418
2419
s = strm.state;
2420
s.pending = 0;
2421
s.pending_out = 0;
2422
2423
if (s.wrap < 0) {
2424
s.wrap = -s.wrap;
2425
/* was made negative by deflate(..., Z_FINISH); */
2426
}
2427
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
2428
strm.adler = (s.wrap === 2) ?
2429
0 // crc32(0, Z_NULL, 0)
2430
:
2431
1; // adler32(0, Z_NULL, 0)
2432
s.last_flush = Z_NO_FLUSH;
2433
trees._tr_init(s);
2434
return Z_OK;
2435
}
2436
2437
2438
function deflateReset(strm) {
2439
var ret = deflateResetKeep(strm);
2440
if (ret === Z_OK) {
2441
lm_init(strm.state);
2442
}
2443
return ret;
2444
}
2445
2446
2447
function deflateSetHeader(strm, head) {
2448
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
2449
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
2450
strm.state.gzhead = head;
2451
return Z_OK;
2452
}
2453
2454
2455
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
2456
if (!strm) { // === Z_NULL
2457
return Z_STREAM_ERROR;
2458
}
2459
var wrap = 1;
2460
2461
if (level === Z_DEFAULT_COMPRESSION) {
2462
level = 6;
2463
}
2464
2465
if (windowBits < 0) { /* suppress zlib wrapper */
2466
wrap = 0;
2467
windowBits = -windowBits;
2468
}
2469
2470
else if (windowBits > 15) {
2471
wrap = 2; /* write gzip wrapper instead */
2472
windowBits -= 16;
2473
}
2474
2475
2476
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
2477
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
2478
strategy < 0 || strategy > Z_FIXED) {
2479
return err(strm, Z_STREAM_ERROR);
2480
}
2481
2482
2483
if (windowBits === 8) {
2484
windowBits = 9;
2485
}
2486
/* until 256-byte window bug fixed */
2487
2488
var s = new DeflateState();
2489
2490
strm.state = s;
2491
s.strm = strm;
2492
2493
s.wrap = wrap;
2494
s.gzhead = null;
2495
s.w_bits = windowBits;
2496
s.w_size = 1 << s.w_bits;
2497
s.w_mask = s.w_size - 1;
2498
2499
s.hash_bits = memLevel + 7;
2500
s.hash_size = 1 << s.hash_bits;
2501
s.hash_mask = s.hash_size - 1;
2502
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
2503
2504
s.window = new utils.Buf8(s.w_size * 2);
2505
s.head = new utils.Buf16(s.hash_size);
2506
s.prev = new utils.Buf16(s.w_size);
2507
2508
// Don't need mem init magic for JS.
2509
//s.high_water = 0; /* nothing written to s->window yet */
2510
2511
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
2512
2513
s.pending_buf_size = s.lit_bufsize * 4;
2514
s.pending_buf = new utils.Buf8(s.pending_buf_size);
2515
2516
s.d_buf = s.lit_bufsize >> 1;
2517
s.l_buf = (1 + 2) * s.lit_bufsize;
2518
2519
s.level = level;
2520
s.strategy = strategy;
2521
s.method = method;
2522
2523
return deflateReset(strm);
2524
}
2525
2526
function deflateInit(strm, level) {
2527
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2528
}
2529
2530
2531
function deflate(strm, flush) {
2532
var old_flush, s;
2533
var beg, val; // for gzip header write only
2534
2535
if (!strm || !strm.state ||
2536
flush > Z_BLOCK || flush < 0) {
2537
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
2538
}
2539
2540
s = strm.state;
2541
2542
if (!strm.output ||
2543
(!strm.input && strm.avail_in !== 0) ||
2544
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
2545
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
2546
}
2547
2548
s.strm = strm; /* just in case */
2549
old_flush = s.last_flush;
2550
s.last_flush = flush;
2551
2552
/* Write the header */
2553
if (s.status === INIT_STATE) {
2554
2555
if (s.wrap === 2) { // GZIP header
2556
strm.adler = 0; //crc32(0L, Z_NULL, 0);
2557
put_byte(s, 31);
2558
put_byte(s, 139);
2559
put_byte(s, 8);
2560
if (!s.gzhead) { // s->gzhead == Z_NULL
2561
put_byte(s, 0);
2562
put_byte(s, 0);
2563
put_byte(s, 0);
2564
put_byte(s, 0);
2565
put_byte(s, 0);
2566
put_byte(s, s.level === 9 ? 2 :
2567
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2568
4 : 0));
2569
put_byte(s, OS_CODE);
2570
s.status = BUSY_STATE;
2571
}
2572
else {
2573
put_byte(s, (s.gzhead.text ? 1 : 0) +
2574
(s.gzhead.hcrc ? 2 : 0) +
2575
(!s.gzhead.extra ? 0 : 4) +
2576
(!s.gzhead.name ? 0 : 8) +
2577
(!s.gzhead.comment ? 0 : 16)
2578
);
2579
put_byte(s, s.gzhead.time & 0xff);
2580
put_byte(s, (s.gzhead.time >> 8) & 0xff);
2581
put_byte(s, (s.gzhead.time >> 16) & 0xff);
2582
put_byte(s, (s.gzhead.time >> 24) & 0xff);
2583
put_byte(s, s.level === 9 ? 2 :
2584
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2585
4 : 0));
2586
put_byte(s, s.gzhead.os & 0xff);
2587
if (s.gzhead.extra && s.gzhead.extra.length) {
2588
put_byte(s, s.gzhead.extra.length & 0xff);
2589
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
2590
}
2591
if (s.gzhead.hcrc) {
2592
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
2593
}
2594
s.gzindex = 0;
2595
s.status = EXTRA_STATE;
2596
}
2597
}
2598
else // DEFLATE header
2599
{
2600
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
2601
var level_flags = -1;
2602
2603
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
2604
level_flags = 0;
2605
} else if (s.level < 6) {
2606
level_flags = 1;
2607
} else if (s.level === 6) {
2608
level_flags = 2;
2609
} else {
2610
level_flags = 3;
2611
}
2612
header |= (level_flags << 6);
2613
if (s.strstart !== 0) { header |= PRESET_DICT; }
2614
header += 31 - (header % 31);
2615
2616
s.status = BUSY_STATE;
2617
putShortMSB(s, header);
2618
2619
/* Save the adler32 of the preset dictionary: */
2620
if (s.strstart !== 0) {
2621
putShortMSB(s, strm.adler >>> 16);
2622
putShortMSB(s, strm.adler & 0xffff);
2623
}
2624
strm.adler = 1; // adler32(0L, Z_NULL, 0);
2625
}
2626
}
2627
2628
//#ifdef GZIP
2629
if (s.status === EXTRA_STATE) {
2630
if (s.gzhead.extra/* != Z_NULL*/) {
2631
beg = s.pending; /* start of bytes to update crc */
2632
2633
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
2634
if (s.pending === s.pending_buf_size) {
2635
if (s.gzhead.hcrc && s.pending > beg) {
2636
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2637
}
2638
flush_pending(strm);
2639
beg = s.pending;
2640
if (s.pending === s.pending_buf_size) {
2641
break;
2642
}
2643
}
2644
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
2645
s.gzindex++;
2646
}
2647
if (s.gzhead.hcrc && s.pending > beg) {
2648
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2649
}
2650
if (s.gzindex === s.gzhead.extra.length) {
2651
s.gzindex = 0;
2652
s.status = NAME_STATE;
2653
}
2654
}
2655
else {
2656
s.status = NAME_STATE;
2657
}
2658
}
2659
if (s.status === NAME_STATE) {
2660
if (s.gzhead.name/* != Z_NULL*/) {
2661
beg = s.pending; /* start of bytes to update crc */
2662
//int val;
2663
2664
do {
2665
if (s.pending === s.pending_buf_size) {
2666
if (s.gzhead.hcrc && s.pending > beg) {
2667
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2668
}
2669
flush_pending(strm);
2670
beg = s.pending;
2671
if (s.pending === s.pending_buf_size) {
2672
val = 1;
2673
break;
2674
}
2675
}
2676
// JS specific: little magic to add zero terminator to end of string
2677
if (s.gzindex < s.gzhead.name.length) {
2678
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
2679
} else {
2680
val = 0;
2681
}
2682
put_byte(s, val);
2683
} while (val !== 0);
2684
2685
if (s.gzhead.hcrc && s.pending > beg){
2686
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2687
}
2688
if (val === 0) {
2689
s.gzindex = 0;
2690
s.status = COMMENT_STATE;
2691
}
2692
}
2693
else {
2694
s.status = COMMENT_STATE;
2695
}
2696
}
2697
if (s.status === COMMENT_STATE) {
2698
if (s.gzhead.comment/* != Z_NULL*/) {
2699
beg = s.pending; /* start of bytes to update crc */
2700
//int val;
2701
2702
do {
2703
if (s.pending === s.pending_buf_size) {
2704
if (s.gzhead.hcrc && s.pending > beg) {
2705
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2706
}
2707
flush_pending(strm);
2708
beg = s.pending;
2709
if (s.pending === s.pending_buf_size) {
2710
val = 1;
2711
break;
2712
}
2713
}
2714
// JS specific: little magic to add zero terminator to end of string
2715
if (s.gzindex < s.gzhead.comment.length) {
2716
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
2717
} else {
2718
val = 0;
2719
}
2720
put_byte(s, val);
2721
} while (val !== 0);
2722
2723
if (s.gzhead.hcrc && s.pending > beg) {
2724
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2725
}
2726
if (val === 0) {
2727
s.status = HCRC_STATE;
2728
}
2729
}
2730
else {
2731
s.status = HCRC_STATE;
2732
}
2733
}
2734
if (s.status === HCRC_STATE) {
2735
if (s.gzhead.hcrc) {
2736
if (s.pending + 2 > s.pending_buf_size) {
2737
flush_pending(strm);
2738
}
2739
if (s.pending + 2 <= s.pending_buf_size) {
2740
put_byte(s, strm.adler & 0xff);
2741
put_byte(s, (strm.adler >> 8) & 0xff);
2742
strm.adler = 0; //crc32(0L, Z_NULL, 0);
2743
s.status = BUSY_STATE;
2744
}
2745
}
2746
else {
2747
s.status = BUSY_STATE;
2748
}
2749
}
2750
//#endif
2751
2752
/* Flush as much pending output as possible */
2753
if (s.pending !== 0) {
2754
flush_pending(strm);
2755
if (strm.avail_out === 0) {
2756
/* Since avail_out is 0, deflate will be called again with
2757
* more output space, but possibly with both pending and
2758
* avail_in equal to zero. There won't be anything to do,
2759
* but this is not an error situation so make sure we
2760
* return OK instead of BUF_ERROR at next call of deflate:
2761
*/
2762
s.last_flush = -1;
2763
return Z_OK;
2764
}
2765
2766
/* Make sure there is something to do and avoid duplicate consecutive
2767
* flushes. For repeated and useless calls with Z_FINISH, we keep
2768
* returning Z_STREAM_END instead of Z_BUF_ERROR.
2769
*/
2770
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
2771
flush !== Z_FINISH) {
2772
return err(strm, Z_BUF_ERROR);
2773
}
2774
2775
/* User must not provide more input after the first FINISH: */
2776
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
2777
return err(strm, Z_BUF_ERROR);
2778
}
2779
2780
/* Start a new block or continue the current one.
2781
*/
2782
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
2783
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
2784
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
2785
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
2786
configuration_table[s.level].func(s, flush));
2787
2788
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
2789
s.status = FINISH_STATE;
2790
}
2791
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
2792
if (strm.avail_out === 0) {
2793
s.last_flush = -1;
2794
/* avoid BUF_ERROR next call, see above */
2795
}
2796
return Z_OK;
2797
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
2798
* of deflate should use the same flush parameter to make sure
2799
* that the flush is complete. So we don't have to output an
2800
* empty block here, this will be done at next call. This also
2801
* ensures that for a very small output buffer, we emit at most
2802
* one empty block.
2803
*/
2804
}
2805
if (bstate === BS_BLOCK_DONE) {
2806
if (flush === Z_PARTIAL_FLUSH) {
2807
trees._tr_align(s);
2808
}
2809
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
2810
2811
trees._tr_stored_block(s, 0, 0, false);
2812
/* For a full flush, this empty block will be recognized
2813
* as a special marker by inflate_sync().
2814
*/
2815
if (flush === Z_FULL_FLUSH) {
2816
/*** CLEAR_HASH(s); ***/ /* forget history */
2817
zero(s.head); // Fill with NIL (= 0);
2818
2819
if (s.lookahead === 0) {
2820
s.strstart = 0;
2821
s.block_start = 0;
2822
s.insert = 0;
2823
}
2824
}
2825
}
2826
flush_pending(strm);
2827
if (strm.avail_out === 0) {
2828
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
2829
return Z_OK;
2830
}
2831
}
2832
}
2833
//Assert(strm->avail_out > 0, "bug2");
2834
//if (strm.avail_out <= 0) { throw new Error("bug2");}
2835
2836
if (flush !== Z_FINISH) { return Z_OK; }
2837
if (s.wrap <= 0) { return Z_STREAM_END; }
2838
2839
/* Write the trailer */
2840
if (s.wrap === 2) {
2841
put_byte(s, strm.adler & 0xff);
2842
put_byte(s, (strm.adler >> 8) & 0xff);
2843
put_byte(s, (strm.adler >> 16) & 0xff);
2844
put_byte(s, (strm.adler >> 24) & 0xff);
2845
put_byte(s, strm.total_in & 0xff);
2846
put_byte(s, (strm.total_in >> 8) & 0xff);
2847
put_byte(s, (strm.total_in >> 16) & 0xff);
2848
put_byte(s, (strm.total_in >> 24) & 0xff);
2849
}
2850
else
2851
{
2852
putShortMSB(s, strm.adler >>> 16);
2853
putShortMSB(s, strm.adler & 0xffff);
2854
}
2855
2856
flush_pending(strm);
2857
/* If avail_out is zero, the application will call deflate again
2858
* to flush the rest.
2859
*/
2860
if (s.wrap > 0) { s.wrap = -s.wrap; }
2861
/* write the trailer only once! */
2862
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
2863
}
2864
2865
function deflateEnd(strm) {
2866
var status;
2867
2868
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
2869
return Z_STREAM_ERROR;
2870
}
2871
2872
status = strm.state.status;
2873
if (status !== INIT_STATE &&
2874
status !== EXTRA_STATE &&
2875
status !== NAME_STATE &&
2876
status !== COMMENT_STATE &&
2877
status !== HCRC_STATE &&
2878
status !== BUSY_STATE &&
2879
status !== FINISH_STATE
2880
) {
2881
return err(strm, Z_STREAM_ERROR);
2882
}
2883
2884
strm.state = null;
2885
2886
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
2887
}
2888
2889
/* =========================================================================
2890
* Copy the source state to the destination state
2891
*/
2892
//function deflateCopy(dest, source) {
2893
//
2894
//}
2895
2896
exports.deflateInit = deflateInit;
2897
exports.deflateInit2 = deflateInit2;
2898
exports.deflateReset = deflateReset;
2899
exports.deflateResetKeep = deflateResetKeep;
2900
exports.deflateSetHeader = deflateSetHeader;
2901
exports.deflate = deflate;
2902
exports.deflateEnd = deflateEnd;
2903
exports.deflateInfo = 'pako deflate (from Nodeca project)';
2904
2905
/* Not implemented
2906
exports.deflateBound = deflateBound;
2907
exports.deflateCopy = deflateCopy;
2908
exports.deflateSetDictionary = deflateSetDictionary;
2909
exports.deflateParams = deflateParams;
2910
exports.deflatePending = deflatePending;
2911
exports.deflatePrime = deflatePrime;
2912
exports.deflateTune = deflateTune;
2913
*/
2914
},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(require,module,exports){
2915
'use strict';
2916
2917
2918
function GZheader() {
2919
/* true if compressed data believed to be text */
2920
this.text = 0;
2921
/* modification time */
2922
this.time = 0;
2923
/* extra flags (not used when writing a gzip file) */
2924
this.xflags = 0;
2925
/* operating system */
2926
this.os = 0;
2927
/* pointer to extra field or Z_NULL if none */
2928
this.extra = null;
2929
/* extra field length (valid if extra != Z_NULL) */
2930
this.extra_len = 0; // Actually, we don't need it in JS,
2931
// but leave for few code modifications
2932
2933
//
2934
// Setup limits is not necessary because in js we should not preallocate memory
2935
// for inflate use constant limit in 65536 bytes
2936
//
2937
2938
/* space at extra (only when reading header) */
2939
// this.extra_max = 0;
2940
/* pointer to zero-terminated file name or Z_NULL */
2941
this.name = '';
2942
/* space at name (only when reading header) */
2943
// this.name_max = 0;
2944
/* pointer to zero-terminated comment or Z_NULL */
2945
this.comment = '';
2946
/* space at comment (only when reading header) */
2947
// this.comm_max = 0;
2948
/* true if there was or will be a header crc */
2949
this.hcrc = 0;
2950
/* true when done reading gzip header (not used when writing a gzip file) */
2951
this.done = false;
2952
}
2953
2954
module.exports = GZheader;
2955
},{}],10:[function(require,module,exports){
2956
'use strict';
2957
2958
// See state defs from inflate.js
2959
var BAD = 30; /* got a data error -- remain here until reset */
2960
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
2961
2962
/*
2963
Decode literal, length, and distance codes and write out the resulting
2964
literal and match bytes until either not enough input or output is
2965
available, an end-of-block is encountered, or a data error is encountered.
2966
When large enough input and output buffers are supplied to inflate(), for
2967
example, a 16K input buffer and a 64K output buffer, more than 95% of the
2968
inflate execution time is spent in this routine.
2969
2970
Entry assumptions:
2971
2972
state.mode === LEN
2973
strm.avail_in >= 6
2974
strm.avail_out >= 258
2975
start >= strm.avail_out
2976
state.bits < 8
2977
2978
On return, state.mode is one of:
2979
2980
LEN -- ran out of enough output space or enough available input
2981
TYPE -- reached end of block code, inflate() to interpret next block
2982
BAD -- error in block data
2983
2984
Notes:
2985
2986
- The maximum input bits used by a length/distance pair is 15 bits for the
2987
length code, 5 bits for the length extra, 15 bits for the distance code,
2988
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
2989
Therefore if strm.avail_in >= 6, then there is enough input to avoid
2990
checking for available input while decoding.
2991
2992
- The maximum bytes that a single length/distance pair can output is 258
2993
bytes, which is the maximum length that can be coded. inflate_fast()
2994
requires strm.avail_out >= 258 for each loop to avoid checking for
2995
output space.
2996
*/
2997
module.exports = function inflate_fast(strm, start) {
2998
var state;
2999
var _in; /* local strm.input */
3000
var last; /* have enough input while in < last */
3001
var _out; /* local strm.output */
3002
var beg; /* inflate()'s initial strm.output */
3003
var end; /* while out < end, enough space available */
3004
//#ifdef INFLATE_STRICT
3005
var dmax; /* maximum distance from zlib header */
3006
//#endif
3007
var wsize; /* window size or zero if not using window */
3008
var whave; /* valid bytes in the window */
3009
var wnext; /* window write index */
3010
var window; /* allocated sliding window, if wsize != 0 */
3011
var hold; /* local strm.hold */
3012
var bits; /* local strm.bits */
3013
var lcode; /* local strm.lencode */
3014
var dcode; /* local strm.distcode */
3015
var lmask; /* mask for first level of length codes */
3016
var dmask; /* mask for first level of distance codes */
3017
var here; /* retrieved table entry */
3018
var op; /* code bits, operation, extra bits, or */
3019
/* window position, window bytes to copy */
3020
var len; /* match length, unused bytes */
3021
var dist; /* match distance */
3022
var from; /* where to copy match from */
3023
var from_source;
3024
3025
3026
var input, output; // JS specific, because we have no pointers
3027
3028
/* copy state to local variables */
3029
state = strm.state;
3030
//here = state.here;
3031
_in = strm.next_in;
3032
input = strm.input;
3033
last = _in + (strm.avail_in - 5);
3034
_out = strm.next_out;
3035
output = strm.output;
3036
beg = _out - (start - strm.avail_out);
3037
end = _out + (strm.avail_out - 257);
3038
//#ifdef INFLATE_STRICT
3039
dmax = state.dmax;
3040
//#endif
3041
wsize = state.wsize;
3042
whave = state.whave;
3043
wnext = state.wnext;
3044
window = state.window;
3045
hold = state.hold;
3046
bits = state.bits;
3047
lcode = state.lencode;
3048
dcode = state.distcode;
3049
lmask = (1 << state.lenbits) - 1;
3050
dmask = (1 << state.distbits) - 1;
3051
3052
3053
/* decode literals and length/distances until end-of-block or not enough
3054
input data or output space */
3055
3056
top:
3057
do {
3058
if (bits < 15) {
3059
hold += input[_in++] << bits;
3060
bits += 8;
3061
hold += input[_in++] << bits;
3062
bits += 8;
3063
}
3064
3065
here = lcode[hold & lmask];
3066
3067
dolen:
3068
for (;;) { // Goto emulation
3069
op = here >>> 24/*here.bits*/;
3070
hold >>>= op;
3071
bits -= op;
3072
op = (here >>> 16) & 0xff/*here.op*/;
3073
if (op === 0) { /* literal */
3074
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
3075
// "inflate: literal '%c'\n" :
3076
// "inflate: literal 0x%02x\n", here.val));
3077
output[_out++] = here & 0xffff/*here.val*/;
3078
}
3079
else if (op & 16) { /* length base */
3080
len = here & 0xffff/*here.val*/;
3081
op &= 15; /* number of extra bits */
3082
if (op) {
3083
if (bits < op) {
3084
hold += input[_in++] << bits;
3085
bits += 8;
3086
}
3087
len += hold & ((1 << op) - 1);
3088
hold >>>= op;
3089
bits -= op;
3090
}
3091
//Tracevv((stderr, "inflate: length %u\n", len));
3092
if (bits < 15) {
3093
hold += input[_in++] << bits;
3094
bits += 8;
3095
hold += input[_in++] << bits;
3096
bits += 8;
3097
}
3098
here = dcode[hold & dmask];
3099
3100
dodist:
3101
for (;;) { // goto emulation
3102
op = here >>> 24/*here.bits*/;
3103
hold >>>= op;
3104
bits -= op;
3105
op = (here >>> 16) & 0xff/*here.op*/;
3106
3107
if (op & 16) { /* distance base */
3108
dist = here & 0xffff/*here.val*/;
3109
op &= 15; /* number of extra bits */
3110
if (bits < op) {
3111
hold += input[_in++] << bits;
3112
bits += 8;
3113
if (bits < op) {
3114
hold += input[_in++] << bits;
3115
bits += 8;
3116
}
3117
}
3118
dist += hold & ((1 << op) - 1);
3119
//#ifdef INFLATE_STRICT
3120
if (dist > dmax) {
3121
strm.msg = 'invalid distance too far back';
3122
state.mode = BAD;
3123
break top;
3124
}
3125
//#endif
3126
hold >>>= op;
3127
bits -= op;
3128
//Tracevv((stderr, "inflate: distance %u\n", dist));
3129
op = _out - beg; /* max distance in output */
3130
if (dist > op) { /* see if copy from window */
3131
op = dist - op; /* distance back in window */
3132
if (op > whave) {
3133
if (state.sane) {
3134
strm.msg = 'invalid distance too far back';
3135
state.mode = BAD;
3136
break top;
3137
}
3138
3139
// (!) This block is disabled in zlib defailts,
3140
// don't enable it for binary compatibility
3141
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
3142
// if (len <= op - whave) {
3143
// do {
3144
// output[_out++] = 0;
3145
// } while (--len);
3146
// continue top;
3147
// }
3148
// len -= op - whave;
3149
// do {
3150
// output[_out++] = 0;
3151
// } while (--op > whave);
3152
// if (op === 0) {
3153
// from = _out - dist;
3154
// do {
3155
// output[_out++] = output[from++];
3156
// } while (--len);
3157
// continue top;
3158
// }
3159
//#endif
3160
}
3161
from = 0; // window index
3162
from_source = window;
3163
if (wnext === 0) { /* very common case */
3164
from += wsize - op;
3165
if (op < len) { /* some from window */
3166
len -= op;
3167
do {
3168
output[_out++] = window[from++];
3169
} while (--op);
3170
from = _out - dist; /* rest from output */
3171
from_source = output;
3172
}
3173
}
3174
else if (wnext < op) { /* wrap around window */
3175
from += wsize + wnext - op;
3176
op -= wnext;
3177
if (op < len) { /* some from end of window */
3178
len -= op;
3179
do {
3180
output[_out++] = window[from++];
3181
} while (--op);
3182
from = 0;
3183
if (wnext < len) { /* some from start of window */
3184
op = wnext;
3185
len -= op;
3186
do {
3187
output[_out++] = window[from++];
3188
} while (--op);
3189
from = _out - dist; /* rest from output */
3190
from_source = output;
3191
}
3192
}
3193
}
3194
else { /* contiguous in window */
3195
from += wnext - op;
3196
if (op < len) { /* some from window */
3197
len -= op;
3198
do {
3199
output[_out++] = window[from++];
3200
} while (--op);
3201
from = _out - dist; /* rest from output */
3202
from_source = output;
3203
}
3204
}
3205
while (len > 2) {
3206
output[_out++] = from_source[from++];
3207
output[_out++] = from_source[from++];
3208
output[_out++] = from_source[from++];
3209
len -= 3;
3210
}
3211
if (len) {
3212
output[_out++] = from_source[from++];
3213
if (len > 1) {
3214
output[_out++] = from_source[from++];
3215
}
3216
}
3217
}
3218
else {
3219
from = _out - dist; /* copy direct from output */
3220
do { /* minimum length is three */
3221
output[_out++] = output[from++];
3222
output[_out++] = output[from++];
3223
output[_out++] = output[from++];
3224
len -= 3;
3225
} while (len > 2);
3226
if (len) {
3227
output[_out++] = output[from++];
3228
if (len > 1) {
3229
output[_out++] = output[from++];
3230
}
3231
}
3232
}
3233
}
3234
else if ((op & 64) === 0) { /* 2nd level distance code */
3235
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3236
continue dodist;
3237
}
3238
else {
3239
strm.msg = 'invalid distance code';
3240
state.mode = BAD;
3241
break top;
3242
}
3243
3244
break; // need to emulate goto via "continue"
3245
}
3246
}
3247
else if ((op & 64) === 0) { /* 2nd level length code */
3248
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3249
continue dolen;
3250
}
3251
else if (op & 32) { /* end-of-block */
3252
//Tracevv((stderr, "inflate: end of block\n"));
3253
state.mode = TYPE;
3254
break top;
3255
}
3256
else {
3257
strm.msg = 'invalid literal/length code';
3258
state.mode = BAD;
3259
break top;
3260
}
3261
3262
break; // need to emulate goto via "continue"
3263
}
3264
} while (_in < last && _out < end);
3265
3266
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
3267
len = bits >> 3;
3268
_in -= len;
3269
bits -= len << 3;
3270
hold &= (1 << bits) - 1;
3271
3272
/* update state and return */
3273
strm.next_in = _in;
3274
strm.next_out = _out;
3275
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
3276
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
3277
state.hold = hold;
3278
state.bits = bits;
3279
return;
3280
};
3281
3282
},{}],11:[function(require,module,exports){
3283
'use strict';
3284
3285
3286
var utils = require('../utils/common');
3287
var adler32 = require('./adler32');
3288
var crc32 = require('./crc32');
3289
var inflate_fast = require('./inffast');
3290
var inflate_table = require('./inftrees');
3291
3292
var CODES = 0;
3293
var LENS = 1;
3294
var DISTS = 2;
3295
3296
/* Public constants ==========================================================*/
3297
/* ===========================================================================*/
3298
3299
3300
/* Allowed flush values; see deflate() and inflate() below for details */
3301
//var Z_NO_FLUSH = 0;
3302
//var Z_PARTIAL_FLUSH = 1;
3303
//var Z_SYNC_FLUSH = 2;
3304
//var Z_FULL_FLUSH = 3;
3305
var Z_FINISH = 4;
3306
var Z_BLOCK = 5;
3307
var Z_TREES = 6;
3308
3309
3310
/* Return codes for the compression/decompression functions. Negative values
3311
* are errors, positive values are used for special but normal events.
3312
*/
3313
var Z_OK = 0;
3314
var Z_STREAM_END = 1;
3315
var Z_NEED_DICT = 2;
3316
//var Z_ERRNO = -1;
3317
var Z_STREAM_ERROR = -2;
3318
var Z_DATA_ERROR = -3;
3319
var Z_MEM_ERROR = -4;
3320
var Z_BUF_ERROR = -5;
3321
//var Z_VERSION_ERROR = -6;
3322
3323
/* The deflate compression method */
3324
var Z_DEFLATED = 8;
3325
3326
3327
/* STATES ====================================================================*/
3328
/* ===========================================================================*/
3329
3330
3331
var HEAD = 1; /* i: waiting for magic header */
3332
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
3333
var TIME = 3; /* i: waiting for modification time (gzip) */
3334
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
3335
var EXLEN = 5; /* i: waiting for extra length (gzip) */
3336
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
3337
var NAME = 7; /* i: waiting for end of file name (gzip) */
3338
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
3339
var HCRC = 9; /* i: waiting for header crc (gzip) */
3340
var DICTID = 10; /* i: waiting for dictionary check value */
3341
var DICT = 11; /* waiting for inflateSetDictionary() call */
3342
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
3343
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
3344
var STORED = 14; /* i: waiting for stored size (length and complement) */
3345
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
3346
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
3347
var TABLE = 17; /* i: waiting for dynamic block table lengths */
3348
var LENLENS = 18; /* i: waiting for code length code lengths */
3349
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
3350
var LEN_ = 20; /* i: same as LEN below, but only first time in */
3351
var LEN = 21; /* i: waiting for length/lit/eob code */
3352
var LENEXT = 22; /* i: waiting for length extra bits */
3353
var DIST = 23; /* i: waiting for distance code */
3354
var DISTEXT = 24; /* i: waiting for distance extra bits */
3355
var MATCH = 25; /* o: waiting for output space to copy string */
3356
var LIT = 26; /* o: waiting for output space to write literal */
3357
var CHECK = 27; /* i: waiting for 32-bit check value */
3358
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
3359
var DONE = 29; /* finished check, done -- remain here until reset */
3360
var BAD = 30; /* got a data error -- remain here until reset */
3361
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
3362
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
3363
3364
/* ===========================================================================*/
3365
3366
3367
3368
var ENOUGH_LENS = 852;
3369
var ENOUGH_DISTS = 592;
3370
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
3371
3372
var MAX_WBITS = 15;
3373
/* 32K LZ77 window */
3374
var DEF_WBITS = MAX_WBITS;
3375
3376
3377
function ZSWAP32(q) {
3378
return (((q >>> 24) & 0xff) +
3379
((q >>> 8) & 0xff00) +
3380
((q & 0xff00) << 8) +
3381
((q & 0xff) << 24));
3382
}
3383
3384
3385
function InflateState() {
3386
this.mode = 0; /* current inflate mode */
3387
this.last = false; /* true if processing last block */
3388
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
3389
this.havedict = false; /* true if dictionary provided */
3390
this.flags = 0; /* gzip header method and flags (0 if zlib) */
3391
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
3392
this.check = 0; /* protected copy of check value */
3393
this.total = 0; /* protected copy of output count */
3394
// TODO: may be {}
3395
this.head = null; /* where to save gzip header information */
3396
3397
/* sliding window */
3398
this.wbits = 0; /* log base 2 of requested window size */
3399
this.wsize = 0; /* window size or zero if not using window */
3400
this.whave = 0; /* valid bytes in the window */
3401
this.wnext = 0; /* window write index */
3402
this.window = null; /* allocated sliding window, if needed */
3403
3404
/* bit accumulator */
3405
this.hold = 0; /* input bit accumulator */
3406
this.bits = 0; /* number of bits in "in" */
3407
3408
/* for string and stored block copying */
3409
this.length = 0; /* literal or length of data to copy */
3410
this.offset = 0; /* distance back to copy string from */
3411
3412
/* for table and code decoding */
3413
this.extra = 0; /* extra bits needed */
3414
3415
/* fixed and dynamic code tables */
3416
this.lencode = null; /* starting table for length/literal codes */
3417
this.distcode = null; /* starting table for distance codes */
3418
this.lenbits = 0; /* index bits for lencode */
3419
this.distbits = 0; /* index bits for distcode */
3420
3421
/* dynamic table building */
3422
this.ncode = 0; /* number of code length code lengths */
3423
this.nlen = 0; /* number of length code lengths */
3424
this.ndist = 0; /* number of distance code lengths */
3425
this.have = 0; /* number of code lengths in lens[] */
3426
this.next = null; /* next available space in codes[] */
3427
3428
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
3429
this.work = new utils.Buf16(288); /* work area for code table building */
3430
3431
/*
3432
because we don't have pointers in js, we use lencode and distcode directly
3433
as buffers so we don't need codes
3434
*/
3435
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
3436
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
3437
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
3438
this.sane = 0; /* if false, allow invalid distance too far */
3439
this.back = 0; /* bits back of last unprocessed length/lit */
3440
this.was = 0; /* initial length of match */
3441
}
3442
3443
function inflateResetKeep(strm) {
3444
var state;
3445
3446
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3447
state = strm.state;
3448
strm.total_in = strm.total_out = state.total = 0;
3449
strm.msg = ''; /*Z_NULL*/
3450
if (state.wrap) { /* to support ill-conceived Java test suite */
3451
strm.adler = state.wrap & 1;
3452
}
3453
state.mode = HEAD;
3454
state.last = 0;
3455
state.havedict = 0;
3456
state.dmax = 32768;
3457
state.head = null/*Z_NULL*/;
3458
state.hold = 0;
3459
state.bits = 0;
3460
//state.lencode = state.distcode = state.next = state.codes;
3461
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
3462
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
3463
3464
state.sane = 1;
3465
state.back = -1;
3466
//Tracev((stderr, "inflate: reset\n"));
3467
return Z_OK;
3468
}
3469
3470
function inflateReset(strm) {
3471
var state;
3472
3473
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3474
state = strm.state;
3475
state.wsize = 0;
3476
state.whave = 0;
3477
state.wnext = 0;
3478
return inflateResetKeep(strm);
3479
3480
}
3481
3482
function inflateReset2(strm, windowBits) {
3483
var wrap;
3484
var state;
3485
3486
/* get the state */
3487
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3488
state = strm.state;
3489
3490
/* extract wrap request from windowBits parameter */
3491
if (windowBits < 0) {
3492
wrap = 0;
3493
windowBits = -windowBits;
3494
}
3495
else {
3496
wrap = (windowBits >> 4) + 1;
3497
if (windowBits < 48) {
3498
windowBits &= 15;
3499
}
3500
}
3501
3502
/* set number of window bits, free window if different */
3503
if (windowBits && (windowBits < 8 || windowBits > 15)) {
3504
return Z_STREAM_ERROR;
3505
}
3506
if (state.window !== null && state.wbits !== windowBits) {
3507
state.window = null;
3508
}
3509
3510
/* update state and reset the rest of it */
3511
state.wrap = wrap;
3512
state.wbits = windowBits;
3513
return inflateReset(strm);
3514
}
3515
3516
function inflateInit2(strm, windowBits) {
3517
var ret;
3518
var state;
3519
3520
if (!strm) { return Z_STREAM_ERROR; }
3521
//strm.msg = Z_NULL; /* in case we return an error */
3522
3523
state = new InflateState();
3524
3525
//if (state === Z_NULL) return Z_MEM_ERROR;
3526
//Tracev((stderr, "inflate: allocated\n"));
3527
strm.state = state;
3528
state.window = null/*Z_NULL*/;
3529
ret = inflateReset2(strm, windowBits);
3530
if (ret !== Z_OK) {
3531
strm.state = null/*Z_NULL*/;
3532
}
3533
return ret;
3534
}
3535
3536
function inflateInit(strm) {
3537
return inflateInit2(strm, DEF_WBITS);
3538
}
3539
3540
3541
/*
3542
Return state with length and distance decoding tables and index sizes set to
3543
fixed code decoding. Normally this returns fixed tables from inffixed.h.
3544
If BUILDFIXED is defined, then instead this routine builds the tables the
3545
first time it's called, and returns those tables the first time and
3546
thereafter. This reduces the size of the code by about 2K bytes, in
3547
exchange for a little execution time. However, BUILDFIXED should not be
3548
used for threaded applications, since the rewriting of the tables and virgin
3549
may not be thread-safe.
3550
*/
3551
var virgin = true;
3552
3553
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
3554
3555
function fixedtables(state) {
3556
/* build fixed huffman tables if first call (may not be thread safe) */
3557
if (virgin) {
3558
var sym;
3559
3560
lenfix = new utils.Buf32(512);
3561
distfix = new utils.Buf32(32);
3562
3563
/* literal/length table */
3564
sym = 0;
3565
while (sym < 144) { state.lens[sym++] = 8; }
3566
while (sym < 256) { state.lens[sym++] = 9; }
3567
while (sym < 280) { state.lens[sym++] = 7; }
3568
while (sym < 288) { state.lens[sym++] = 8; }
3569
3570
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
3571
3572
/* distance table */
3573
sym = 0;
3574
while (sym < 32) { state.lens[sym++] = 5; }
3575
3576
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
3577
3578
/* do this just once */
3579
virgin = false;
3580
}
3581
3582
state.lencode = lenfix;
3583
state.lenbits = 9;
3584
state.distcode = distfix;
3585
state.distbits = 5;
3586
}
3587
3588
3589
/*
3590
Update the window with the last wsize (normally 32K) bytes written before
3591
returning. If window does not exist yet, create it. This is only called
3592
when a window is already in use, or when output has been written during this
3593
inflate call, but the end of the deflate stream has not been reached yet.
3594
It is also called to create a window for dictionary data when a dictionary
3595
is loaded.
3596
3597
Providing output buffers larger than 32K to inflate() should provide a speed
3598
advantage, since only the last 32K of output is copied to the sliding window
3599
upon return from inflate(), and since all distances after the first 32K of
3600
output will fall in the output data, making match copies simpler and faster.
3601
The advantage may be dependent on the size of the processor's data caches.
3602
*/
3603
function updatewindow(strm, src, end, copy) {
3604
var dist;
3605
var state = strm.state;
3606
3607
/* if it hasn't been done already, allocate space for the window */
3608
if (state.window === null) {
3609
state.wsize = 1 << state.wbits;
3610
state.wnext = 0;
3611
state.whave = 0;
3612
3613
state.window = new utils.Buf8(state.wsize);
3614
}
3615
3616
/* copy state->wsize or less output bytes into the circular window */
3617
if (copy >= state.wsize) {
3618
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
3619
state.wnext = 0;
3620
state.whave = state.wsize;
3621
}
3622
else {
3623
dist = state.wsize - state.wnext;
3624
if (dist > copy) {
3625
dist = copy;
3626
}
3627
//zmemcpy(state->window + state->wnext, end - copy, dist);
3628
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
3629
copy -= dist;
3630
if (copy) {
3631
//zmemcpy(state->window, end - copy, copy);
3632
utils.arraySet(state.window,src, end - copy, copy, 0);
3633
state.wnext = copy;
3634
state.whave = state.wsize;
3635
}
3636
else {
3637
state.wnext += dist;
3638
if (state.wnext === state.wsize) { state.wnext = 0; }
3639
if (state.whave < state.wsize) { state.whave += dist; }
3640
}
3641
}
3642
return 0;
3643
}
3644
3645
function inflate(strm, flush) {
3646
var state;
3647
var input, output; // input/output buffers
3648
var next; /* next input INDEX */
3649
var put; /* next output INDEX */
3650
var have, left; /* available input and output */
3651
var hold; /* bit buffer */
3652
var bits; /* bits in bit buffer */
3653
var _in, _out; /* save starting available input and output */
3654
var copy; /* number of stored or match bytes to copy */
3655
var from; /* where to copy match bytes from */
3656
var from_source;
3657
var here = 0; /* current decoding table entry */
3658
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
3659
//var last; /* parent table entry */
3660
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
3661
var len; /* length to copy for repeats, bits to drop */
3662
var ret; /* return code */
3663
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
3664
var opts;
3665
3666
var n; // temporary var for NEED_BITS
3667
3668
var order = /* permutation of code lengths */
3669
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
3670
3671
3672
if (!strm || !strm.state || !strm.output ||
3673
(!strm.input && strm.avail_in !== 0)) {
3674
return Z_STREAM_ERROR;
3675
}
3676
3677
state = strm.state;
3678
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
3679
3680
3681
//--- LOAD() ---
3682
put = strm.next_out;
3683
output = strm.output;
3684
left = strm.avail_out;
3685
next = strm.next_in;
3686
input = strm.input;
3687
have = strm.avail_in;
3688
hold = state.hold;
3689
bits = state.bits;
3690
//---
3691
3692
_in = have;
3693
_out = left;
3694
ret = Z_OK;
3695
3696
inf_leave: // goto emulation
3697
for (;;) {
3698
switch (state.mode) {
3699
case HEAD:
3700
if (state.wrap === 0) {
3701
state.mode = TYPEDO;
3702
break;
3703
}
3704
//=== NEEDBITS(16);
3705
while (bits < 16) {
3706
if (have === 0) { break inf_leave; }
3707
have--;
3708
hold += input[next++] << bits;
3709
bits += 8;
3710
}
3711
//===//
3712
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
3713
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
3714
//=== CRC2(state.check, hold);
3715
hbuf[0] = hold & 0xff;
3716
hbuf[1] = (hold >>> 8) & 0xff;
3717
state.check = crc32(state.check, hbuf, 2, 0);
3718
//===//
3719
3720
//=== INITBITS();
3721
hold = 0;
3722
bits = 0;
3723
//===//
3724
state.mode = FLAGS;
3725
break;
3726
}
3727
state.flags = 0; /* expect zlib header */
3728
if (state.head) {
3729
state.head.done = false;
3730
}
3731
if (!(state.wrap & 1) || /* check if zlib header allowed */
3732
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
3733
strm.msg = 'incorrect header check';
3734
state.mode = BAD;
3735
break;
3736
}
3737
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
3738
strm.msg = 'unknown compression method';
3739
state.mode = BAD;
3740
break;
3741
}
3742
//--- DROPBITS(4) ---//
3743
hold >>>= 4;
3744
bits -= 4;
3745
//---//
3746
len = (hold & 0x0f)/*BITS(4)*/ + 8;
3747
if (state.wbits === 0) {
3748
state.wbits = len;
3749
}
3750
else if (len > state.wbits) {
3751
strm.msg = 'invalid window size';
3752
state.mode = BAD;
3753
break;
3754
}
3755
state.dmax = 1 << len;
3756
//Tracev((stderr, "inflate: zlib header ok\n"));
3757
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
3758
state.mode = hold & 0x200 ? DICTID : TYPE;
3759
//=== INITBITS();
3760
hold = 0;
3761
bits = 0;
3762
//===//
3763
break;
3764
case FLAGS:
3765
//=== NEEDBITS(16); */
3766
while (bits < 16) {
3767
if (have === 0) { break inf_leave; }
3768
have--;
3769
hold += input[next++] << bits;
3770
bits += 8;
3771
}
3772
//===//
3773
state.flags = hold;
3774
if ((state.flags & 0xff) !== Z_DEFLATED) {
3775
strm.msg = 'unknown compression method';
3776
state.mode = BAD;
3777
break;
3778
}
3779
if (state.flags & 0xe000) {
3780
strm.msg = 'unknown header flags set';
3781
state.mode = BAD;
3782
break;
3783
}
3784
if (state.head) {
3785
state.head.text = ((hold >> 8) & 1);
3786
}
3787
if (state.flags & 0x0200) {
3788
//=== CRC2(state.check, hold);
3789
hbuf[0] = hold & 0xff;
3790
hbuf[1] = (hold >>> 8) & 0xff;
3791
state.check = crc32(state.check, hbuf, 2, 0);
3792
//===//
3793
}
3794
//=== INITBITS();
3795
hold = 0;
3796
bits = 0;
3797
//===//
3798
state.mode = TIME;
3799
/* falls through */
3800
case TIME:
3801
//=== NEEDBITS(32); */
3802
while (bits < 32) {
3803
if (have === 0) { break inf_leave; }
3804
have--;
3805
hold += input[next++] << bits;
3806
bits += 8;
3807
}
3808
//===//
3809
if (state.head) {
3810
state.head.time = hold;
3811
}
3812
if (state.flags & 0x0200) {
3813
//=== CRC4(state.check, hold)
3814
hbuf[0] = hold & 0xff;
3815
hbuf[1] = (hold >>> 8) & 0xff;
3816
hbuf[2] = (hold >>> 16) & 0xff;
3817
hbuf[3] = (hold >>> 24) & 0xff;
3818
state.check = crc32(state.check, hbuf, 4, 0);
3819
//===
3820
}
3821
//=== INITBITS();
3822
hold = 0;
3823
bits = 0;
3824
//===//
3825
state.mode = OS;
3826
/* falls through */
3827
case OS:
3828
//=== NEEDBITS(16); */
3829
while (bits < 16) {
3830
if (have === 0) { break inf_leave; }
3831
have--;
3832
hold += input[next++] << bits;
3833
bits += 8;
3834
}
3835
//===//
3836
if (state.head) {
3837
state.head.xflags = (hold & 0xff);
3838
state.head.os = (hold >> 8);
3839
}
3840
if (state.flags & 0x0200) {
3841
//=== CRC2(state.check, hold);
3842
hbuf[0] = hold & 0xff;
3843
hbuf[1] = (hold >>> 8) & 0xff;
3844
state.check = crc32(state.check, hbuf, 2, 0);
3845
//===//
3846
}
3847
//=== INITBITS();
3848
hold = 0;
3849
bits = 0;
3850
//===//
3851
state.mode = EXLEN;
3852
/* falls through */
3853
case EXLEN:
3854
if (state.flags & 0x0400) {
3855
//=== NEEDBITS(16); */
3856
while (bits < 16) {
3857
if (have === 0) { break inf_leave; }
3858
have--;
3859
hold += input[next++] << bits;
3860
bits += 8;
3861
}
3862
//===//
3863
state.length = hold;
3864
if (state.head) {
3865
state.head.extra_len = hold;
3866
}
3867
if (state.flags & 0x0200) {
3868
//=== CRC2(state.check, hold);
3869
hbuf[0] = hold & 0xff;
3870
hbuf[1] = (hold >>> 8) & 0xff;
3871
state.check = crc32(state.check, hbuf, 2, 0);
3872
//===//
3873
}
3874
//=== INITBITS();
3875
hold = 0;
3876
bits = 0;
3877
//===//
3878
}
3879
else if (state.head) {
3880
state.head.extra = null/*Z_NULL*/;
3881
}
3882
state.mode = EXTRA;
3883
/* falls through */
3884
case EXTRA:
3885
if (state.flags & 0x0400) {
3886
copy = state.length;
3887
if (copy > have) { copy = have; }
3888
if (copy) {
3889
if (state.head) {
3890
len = state.head.extra_len - state.length;
3891
if (!state.head.extra) {
3892
// Use untyped array for more conveniend processing later
3893
state.head.extra = new Array(state.head.extra_len);
3894
}
3895
utils.arraySet(
3896
state.head.extra,
3897
input,
3898
next,
3899
// extra field is limited to 65536 bytes
3900
// - no need for additional size check
3901
copy,
3902
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
3903
len
3904
);
3905
//zmemcpy(state.head.extra + len, next,
3906
// len + copy > state.head.extra_max ?
3907
// state.head.extra_max - len : copy);
3908
}
3909
if (state.flags & 0x0200) {
3910
state.check = crc32(state.check, input, copy, next);
3911
}
3912
have -= copy;
3913
next += copy;
3914
state.length -= copy;
3915
}
3916
if (state.length) { break inf_leave; }
3917
}
3918
state.length = 0;
3919
state.mode = NAME;
3920
/* falls through */
3921
case NAME:
3922
if (state.flags & 0x0800) {
3923
if (have === 0) { break inf_leave; }
3924
copy = 0;
3925
do {
3926
// TODO: 2 or 1 bytes?
3927
len = input[next + copy++];
3928
/* use constant limit because in js we should not preallocate memory */
3929
if (state.head && len &&
3930
(state.length < 65536 /*state.head.name_max*/)) {
3931
state.head.name += String.fromCharCode(len);
3932
}
3933
} while (len && copy < have);
3934
3935
if (state.flags & 0x0200) {
3936
state.check = crc32(state.check, input, copy, next);
3937
}
3938
have -= copy;
3939
next += copy;
3940
if (len) { break inf_leave; }
3941
}
3942
else if (state.head) {
3943
state.head.name = null;
3944
}
3945
state.length = 0;
3946
state.mode = COMMENT;
3947
/* falls through */
3948
case COMMENT:
3949
if (state.flags & 0x1000) {
3950
if (have === 0) { break inf_leave; }
3951
copy = 0;
3952
do {
3953
len = input[next + copy++];
3954
/* use constant limit because in js we should not preallocate memory */
3955
if (state.head && len &&
3956
(state.length < 65536 /*state.head.comm_max*/)) {
3957
state.head.comment += String.fromCharCode(len);
3958
}
3959
} while (len && copy < have);
3960
if (state.flags & 0x0200) {
3961
state.check = crc32(state.check, input, copy, next);
3962
}
3963
have -= copy;
3964
next += copy;
3965
if (len) { break inf_leave; }
3966
}
3967
else if (state.head) {
3968
state.head.comment = null;
3969
}
3970
state.mode = HCRC;
3971
/* falls through */
3972
case HCRC:
3973
if (state.flags & 0x0200) {
3974
//=== NEEDBITS(16); */
3975
while (bits < 16) {
3976
if (have === 0) { break inf_leave; }
3977
have--;
3978
hold += input[next++] << bits;
3979
bits += 8;
3980
}
3981
//===//
3982
if (hold !== (state.check & 0xffff)) {
3983
strm.msg = 'header crc mismatch';
3984
state.mode = BAD;
3985
break;
3986
}
3987
//=== INITBITS();
3988
hold = 0;
3989
bits = 0;
3990
//===//
3991
}
3992
if (state.head) {
3993
state.head.hcrc = ((state.flags >> 9) & 1);
3994
state.head.done = true;
3995
}
3996
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
3997
state.mode = TYPE;
3998
break;
3999
case DICTID:
4000
//=== NEEDBITS(32); */
4001
while (bits < 32) {
4002
if (have === 0) { break inf_leave; }
4003
have--;
4004
hold += input[next++] << bits;
4005
bits += 8;
4006
}
4007
//===//
4008
strm.adler = state.check = ZSWAP32(hold);
4009
//=== INITBITS();
4010
hold = 0;
4011
bits = 0;
4012
//===//
4013
state.mode = DICT;
4014
/* falls through */
4015
case DICT:
4016
if (state.havedict === 0) {
4017
//--- RESTORE() ---
4018
strm.next_out = put;
4019
strm.avail_out = left;
4020
strm.next_in = next;
4021
strm.avail_in = have;
4022
state.hold = hold;
4023
state.bits = bits;
4024
//---
4025
return Z_NEED_DICT;
4026
}
4027
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
4028
state.mode = TYPE;
4029
/* falls through */
4030
case TYPE:
4031
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
4032
/* falls through */
4033
case TYPEDO:
4034
if (state.last) {
4035
//--- BYTEBITS() ---//
4036
hold >>>= bits & 7;
4037
bits -= bits & 7;
4038
//---//
4039
state.mode = CHECK;
4040
break;
4041
}
4042
//=== NEEDBITS(3); */
4043
while (bits < 3) {
4044
if (have === 0) { break inf_leave; }
4045
have--;
4046
hold += input[next++] << bits;
4047
bits += 8;
4048
}
4049
//===//
4050
state.last = (hold & 0x01)/*BITS(1)*/;
4051
//--- DROPBITS(1) ---//
4052
hold >>>= 1;
4053
bits -= 1;
4054
//---//
4055
4056
switch ((hold & 0x03)/*BITS(2)*/) {
4057
case 0: /* stored block */
4058
//Tracev((stderr, "inflate: stored block%s\n",
4059
// state.last ? " (last)" : ""));
4060
state.mode = STORED;
4061
break;
4062
case 1: /* fixed block */
4063
fixedtables(state);
4064
//Tracev((stderr, "inflate: fixed codes block%s\n",
4065
// state.last ? " (last)" : ""));
4066
state.mode = LEN_; /* decode codes */
4067
if (flush === Z_TREES) {
4068
//--- DROPBITS(2) ---//
4069
hold >>>= 2;
4070
bits -= 2;
4071
//---//
4072
break inf_leave;
4073
}
4074
break;
4075
case 2: /* dynamic block */
4076
//Tracev((stderr, "inflate: dynamic codes block%s\n",
4077
// state.last ? " (last)" : ""));
4078
state.mode = TABLE;
4079
break;
4080
case 3:
4081
strm.msg = 'invalid block type';
4082
state.mode = BAD;
4083
}
4084
//--- DROPBITS(2) ---//
4085
hold >>>= 2;
4086
bits -= 2;
4087
//---//
4088
break;
4089
case STORED:
4090
//--- BYTEBITS() ---// /* go to byte boundary */
4091
hold >>>= bits & 7;
4092
bits -= bits & 7;
4093
//---//
4094
//=== NEEDBITS(32); */
4095
while (bits < 32) {
4096
if (have === 0) { break inf_leave; }
4097
have--;
4098
hold += input[next++] << bits;
4099
bits += 8;
4100
}
4101
//===//
4102
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
4103
strm.msg = 'invalid stored block lengths';
4104
state.mode = BAD;
4105
break;
4106
}
4107
state.length = hold & 0xffff;
4108
//Tracev((stderr, "inflate: stored length %u\n",
4109
// state.length));
4110
//=== INITBITS();
4111
hold = 0;
4112
bits = 0;
4113
//===//
4114
state.mode = COPY_;
4115
if (flush === Z_TREES) { break inf_leave; }
4116
/* falls through */
4117
case COPY_:
4118
state.mode = COPY;
4119
/* falls through */
4120
case COPY:
4121
copy = state.length;
4122
if (copy) {
4123
if (copy > have) { copy = have; }
4124
if (copy > left) { copy = left; }
4125
if (copy === 0) { break inf_leave; }
4126
//--- zmemcpy(put, next, copy); ---
4127
utils.arraySet(output, input, next, copy, put);
4128
//---//
4129
have -= copy;
4130
next += copy;
4131
left -= copy;
4132
put += copy;
4133
state.length -= copy;
4134
break;
4135
}
4136
//Tracev((stderr, "inflate: stored end\n"));
4137
state.mode = TYPE;
4138
break;
4139
case TABLE:
4140
//=== NEEDBITS(14); */
4141
while (bits < 14) {
4142
if (have === 0) { break inf_leave; }
4143
have--;
4144
hold += input[next++] << bits;
4145
bits += 8;
4146
}
4147
//===//
4148
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
4149
//--- DROPBITS(5) ---//
4150
hold >>>= 5;
4151
bits -= 5;
4152
//---//
4153
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
4154
//--- DROPBITS(5) ---//
4155
hold >>>= 5;
4156
bits -= 5;
4157
//---//
4158
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
4159
//--- DROPBITS(4) ---//
4160
hold >>>= 4;
4161
bits -= 4;
4162
//---//
4163
//#ifndef PKZIP_BUG_WORKAROUND
4164
if (state.nlen > 286 || state.ndist > 30) {
4165
strm.msg = 'too many length or distance symbols';
4166
state.mode = BAD;
4167
break;
4168
}
4169
//#endif
4170
//Tracev((stderr, "inflate: table sizes ok\n"));
4171
state.have = 0;
4172
state.mode = LENLENS;
4173
/* falls through */
4174
case LENLENS:
4175
while (state.have < state.ncode) {
4176
//=== NEEDBITS(3);
4177
while (bits < 3) {
4178
if (have === 0) { break inf_leave; }
4179
have--;
4180
hold += input[next++] << bits;
4181
bits += 8;
4182
}
4183
//===//
4184
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
4185
//--- DROPBITS(3) ---//
4186
hold >>>= 3;
4187
bits -= 3;
4188
//---//
4189
}
4190
while (state.have < 19) {
4191
state.lens[order[state.have++]] = 0;
4192
}
4193
// We have separate tables & no pointers. 2 commented lines below not needed.
4194
//state.next = state.codes;
4195
//state.lencode = state.next;
4196
// Switch to use dynamic table
4197
state.lencode = state.lendyn;
4198
state.lenbits = 7;
4199
4200
opts = {bits: state.lenbits};
4201
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
4202
state.lenbits = opts.bits;
4203
4204
if (ret) {
4205
strm.msg = 'invalid code lengths set';
4206
state.mode = BAD;
4207
break;
4208
}
4209
//Tracev((stderr, "inflate: code lengths ok\n"));
4210
state.have = 0;
4211
state.mode = CODELENS;
4212
/* falls through */
4213
case CODELENS:
4214
while (state.have < state.nlen + state.ndist) {
4215
for (;;) {
4216
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
4217
here_bits = here >>> 24;
4218
here_op = (here >>> 16) & 0xff;
4219
here_val = here & 0xffff;
4220
4221
if ((here_bits) <= bits) { break; }
4222
//--- PULLBYTE() ---//
4223
if (have === 0) { break inf_leave; }
4224
have--;
4225
hold += input[next++] << bits;
4226
bits += 8;
4227
//---//
4228
}
4229
if (here_val < 16) {
4230
//--- DROPBITS(here.bits) ---//
4231
hold >>>= here_bits;
4232
bits -= here_bits;
4233
//---//
4234
state.lens[state.have++] = here_val;
4235
}
4236
else {
4237
if (here_val === 16) {
4238
//=== NEEDBITS(here.bits + 2);
4239
n = here_bits + 2;
4240
while (bits < n) {
4241
if (have === 0) { break inf_leave; }
4242
have--;
4243
hold += input[next++] << bits;
4244
bits += 8;
4245
}
4246
//===//
4247
//--- DROPBITS(here.bits) ---//
4248
hold >>>= here_bits;
4249
bits -= here_bits;
4250
//---//
4251
if (state.have === 0) {
4252
strm.msg = 'invalid bit length repeat';
4253
state.mode = BAD;
4254
break;
4255
}
4256
len = state.lens[state.have - 1];
4257
copy = 3 + (hold & 0x03);//BITS(2);
4258
//--- DROPBITS(2) ---//
4259
hold >>>= 2;
4260
bits -= 2;
4261
//---//
4262
}
4263
else if (here_val === 17) {
4264
//=== NEEDBITS(here.bits + 3);
4265
n = here_bits + 3;
4266
while (bits < n) {
4267
if (have === 0) { break inf_leave; }
4268
have--;
4269
hold += input[next++] << bits;
4270
bits += 8;
4271
}
4272
//===//
4273
//--- DROPBITS(here.bits) ---//
4274
hold >>>= here_bits;
4275
bits -= here_bits;
4276
//---//
4277
len = 0;
4278
copy = 3 + (hold & 0x07);//BITS(3);
4279
//--- DROPBITS(3) ---//
4280
hold >>>= 3;
4281
bits -= 3;
4282
//---//
4283
}
4284
else {
4285
//=== NEEDBITS(here.bits + 7);
4286
n = here_bits + 7;
4287
while (bits < n) {
4288
if (have === 0) { break inf_leave; }
4289
have--;
4290
hold += input[next++] << bits;
4291
bits += 8;
4292
}
4293
//===//
4294
//--- DROPBITS(here.bits) ---//
4295
hold >>>= here_bits;
4296
bits -= here_bits;
4297
//---//
4298
len = 0;
4299
copy = 11 + (hold & 0x7f);//BITS(7);
4300
//--- DROPBITS(7) ---//
4301
hold >>>= 7;
4302
bits -= 7;
4303
//---//
4304
}
4305
if (state.have + copy > state.nlen + state.ndist) {
4306
strm.msg = 'invalid bit length repeat';
4307
state.mode = BAD;
4308
break;
4309
}
4310
while (copy--) {
4311
state.lens[state.have++] = len;
4312
}
4313
}
4314
}
4315
4316
/* handle error breaks in while */
4317
if (state.mode === BAD) { break; }
4318
4319
/* check for end-of-block code (better have one) */
4320
if (state.lens[256] === 0) {
4321
strm.msg = 'invalid code -- missing end-of-block';
4322
state.mode = BAD;
4323
break;
4324
}
4325
4326
/* build code tables -- note: do not change the lenbits or distbits
4327
values here (9 and 6) without reading the comments in inftrees.h
4328
concerning the ENOUGH constants, which depend on those values */
4329
state.lenbits = 9;
4330
4331
opts = {bits: state.lenbits};
4332
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
4333
// We have separate tables & no pointers. 2 commented lines below not needed.
4334
// state.next_index = opts.table_index;
4335
state.lenbits = opts.bits;
4336
// state.lencode = state.next;
4337
4338
if (ret) {
4339
strm.msg = 'invalid literal/lengths set';
4340
state.mode = BAD;
4341
break;
4342
}
4343
4344
state.distbits = 6;
4345
//state.distcode.copy(state.codes);
4346
// Switch to use dynamic table
4347
state.distcode = state.distdyn;
4348
opts = {bits: state.distbits};
4349
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
4350
// We have separate tables & no pointers. 2 commented lines below not needed.
4351
// state.next_index = opts.table_index;
4352
state.distbits = opts.bits;
4353
// state.distcode = state.next;
4354
4355
if (ret) {
4356
strm.msg = 'invalid distances set';
4357
state.mode = BAD;
4358
break;
4359
}
4360
//Tracev((stderr, 'inflate: codes ok\n'));
4361
state.mode = LEN_;
4362
if (flush === Z_TREES) { break inf_leave; }
4363
/* falls through */
4364
case LEN_:
4365
state.mode = LEN;
4366
/* falls through */
4367
case LEN:
4368
if (have >= 6 && left >= 258) {
4369
//--- RESTORE() ---
4370
strm.next_out = put;
4371
strm.avail_out = left;
4372
strm.next_in = next;
4373
strm.avail_in = have;
4374
state.hold = hold;
4375
state.bits = bits;
4376
//---
4377
inflate_fast(strm, _out);
4378
//--- LOAD() ---
4379
put = strm.next_out;
4380
output = strm.output;
4381
left = strm.avail_out;
4382
next = strm.next_in;
4383
input = strm.input;
4384
have = strm.avail_in;
4385
hold = state.hold;
4386
bits = state.bits;
4387
//---
4388
4389
if (state.mode === TYPE) {
4390
state.back = -1;
4391
}
4392
break;
4393
}
4394
state.back = 0;
4395
for (;;) {
4396
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
4397
here_bits = here >>> 24;
4398
here_op = (here >>> 16) & 0xff;
4399
here_val = here & 0xffff;
4400
4401
if (here_bits <= bits) { break; }
4402
//--- PULLBYTE() ---//
4403
if (have === 0) { break inf_leave; }
4404
have--;
4405
hold += input[next++] << bits;
4406
bits += 8;
4407
//---//
4408
}
4409
if (here_op && (here_op & 0xf0) === 0) {
4410
last_bits = here_bits;
4411
last_op = here_op;
4412
last_val = here_val;
4413
for (;;) {
4414
here = state.lencode[last_val +
4415
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4416
here_bits = here >>> 24;
4417
here_op = (here >>> 16) & 0xff;
4418
here_val = here & 0xffff;
4419
4420
if ((last_bits + here_bits) <= bits) { break; }
4421
//--- PULLBYTE() ---//
4422
if (have === 0) { break inf_leave; }
4423
have--;
4424
hold += input[next++] << bits;
4425
bits += 8;
4426
//---//
4427
}
4428
//--- DROPBITS(last.bits) ---//
4429
hold >>>= last_bits;
4430
bits -= last_bits;
4431
//---//
4432
state.back += last_bits;
4433
}
4434
//--- DROPBITS(here.bits) ---//
4435
hold >>>= here_bits;
4436
bits -= here_bits;
4437
//---//
4438
state.back += here_bits;
4439
state.length = here_val;
4440
if (here_op === 0) {
4441
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
4442
// "inflate: literal '%c'\n" :
4443
// "inflate: literal 0x%02x\n", here.val));
4444
state.mode = LIT;
4445
break;
4446
}
4447
if (here_op & 32) {
4448
//Tracevv((stderr, "inflate: end of block\n"));
4449
state.back = -1;
4450
state.mode = TYPE;
4451
break;
4452
}
4453
if (here_op & 64) {
4454
strm.msg = 'invalid literal/length code';
4455
state.mode = BAD;
4456
break;
4457
}
4458
state.extra = here_op & 15;
4459
state.mode = LENEXT;
4460
/* falls through */
4461
case LENEXT:
4462
if (state.extra) {
4463
//=== NEEDBITS(state.extra);
4464
n = state.extra;
4465
while (bits < n) {
4466
if (have === 0) { break inf_leave; }
4467
have--;
4468
hold += input[next++] << bits;
4469
bits += 8;
4470
}
4471
//===//
4472
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
4473
//--- DROPBITS(state.extra) ---//
4474
hold >>>= state.extra;
4475
bits -= state.extra;
4476
//---//
4477
state.back += state.extra;
4478
}
4479
//Tracevv((stderr, "inflate: length %u\n", state.length));
4480
state.was = state.length;
4481
state.mode = DIST;
4482
/* falls through */
4483
case DIST:
4484
for (;;) {
4485
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
4486
here_bits = here >>> 24;
4487
here_op = (here >>> 16) & 0xff;
4488
here_val = here & 0xffff;
4489
4490
if ((here_bits) <= bits) { break; }
4491
//--- PULLBYTE() ---//
4492
if (have === 0) { break inf_leave; }
4493
have--;
4494
hold += input[next++] << bits;
4495
bits += 8;
4496
//---//
4497
}
4498
if ((here_op & 0xf0) === 0) {
4499
last_bits = here_bits;
4500
last_op = here_op;
4501
last_val = here_val;
4502
for (;;) {
4503
here = state.distcode[last_val +
4504
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4505
here_bits = here >>> 24;
4506
here_op = (here >>> 16) & 0xff;
4507
here_val = here & 0xffff;
4508
4509
if ((last_bits + here_bits) <= bits) { break; }
4510
//--- PULLBYTE() ---//
4511
if (have === 0) { break inf_leave; }
4512
have--;
4513
hold += input[next++] << bits;
4514
bits += 8;
4515
//---//
4516
}
4517
//--- DROPBITS(last.bits) ---//
4518
hold >>>= last_bits;
4519
bits -= last_bits;
4520
//---//
4521
state.back += last_bits;
4522
}
4523
//--- DROPBITS(here.bits) ---//
4524
hold >>>= here_bits;
4525
bits -= here_bits;
4526
//---//
4527
state.back += here_bits;
4528
if (here_op & 64) {
4529
strm.msg = 'invalid distance code';
4530
state.mode = BAD;
4531
break;
4532
}
4533
state.offset = here_val;
4534
state.extra = (here_op) & 15;
4535
state.mode = DISTEXT;
4536
/* falls through */
4537
case DISTEXT:
4538
if (state.extra) {
4539
//=== NEEDBITS(state.extra);
4540
n = state.extra;
4541
while (bits < n) {
4542
if (have === 0) { break inf_leave; }
4543
have--;
4544
hold += input[next++] << bits;
4545
bits += 8;
4546
}
4547
//===//
4548
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
4549
//--- DROPBITS(state.extra) ---//
4550
hold >>>= state.extra;
4551
bits -= state.extra;
4552
//---//
4553
state.back += state.extra;
4554
}
4555
//#ifdef INFLATE_STRICT
4556
if (state.offset > state.dmax) {
4557
strm.msg = 'invalid distance too far back';
4558
state.mode = BAD;
4559
break;
4560
}
4561
//#endif
4562
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
4563
state.mode = MATCH;
4564
/* falls through */
4565
case MATCH:
4566
if (left === 0) { break inf_leave; }
4567
copy = _out - left;
4568
if (state.offset > copy) { /* copy from window */
4569
copy = state.offset - copy;
4570
if (copy > state.whave) {
4571
if (state.sane) {
4572
strm.msg = 'invalid distance too far back';
4573
state.mode = BAD;
4574
break;
4575
}
4576
// (!) This block is disabled in zlib defailts,
4577
// don't enable it for binary compatibility
4578
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
4579
// Trace((stderr, "inflate.c too far\n"));
4580
// copy -= state.whave;
4581
// if (copy > state.length) { copy = state.length; }
4582
// if (copy > left) { copy = left; }
4583
// left -= copy;
4584
// state.length -= copy;
4585
// do {
4586
// output[put++] = 0;
4587
// } while (--copy);
4588
// if (state.length === 0) { state.mode = LEN; }
4589
// break;
4590
//#endif
4591
}
4592
if (copy > state.wnext) {
4593
copy -= state.wnext;
4594
from = state.wsize - copy;
4595
}
4596
else {
4597
from = state.wnext - copy;
4598
}
4599
if (copy > state.length) { copy = state.length; }
4600
from_source = state.window;
4601
}
4602
else { /* copy from output */
4603
from_source = output;
4604
from = put - state.offset;
4605
copy = state.length;
4606
}
4607
if (copy > left) { copy = left; }
4608
left -= copy;
4609
state.length -= copy;
4610
do {
4611
output[put++] = from_source[from++];
4612
} while (--copy);
4613
if (state.length === 0) { state.mode = LEN; }
4614
break;
4615
case LIT:
4616
if (left === 0) { break inf_leave; }
4617
output[put++] = state.length;
4618
left--;
4619
state.mode = LEN;
4620
break;
4621
case CHECK:
4622
if (state.wrap) {
4623
//=== NEEDBITS(32);
4624
while (bits < 32) {
4625
if (have === 0) { break inf_leave; }
4626
have--;
4627
// Use '|' insdead of '+' to make sure that result is signed
4628
hold |= input[next++] << bits;
4629
bits += 8;
4630
}
4631
//===//
4632
_out -= left;
4633
strm.total_out += _out;
4634
state.total += _out;
4635
if (_out) {
4636
strm.adler = state.check =
4637
/*UPDATE(state.check, put - _out, _out);*/
4638
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
4639
4640
}
4641
_out = left;
4642
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
4643
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
4644
strm.msg = 'incorrect data check';
4645
state.mode = BAD;
4646
break;
4647
}
4648
//=== INITBITS();
4649
hold = 0;
4650
bits = 0;
4651
//===//
4652
//Tracev((stderr, "inflate: check matches trailer\n"));
4653
}
4654
state.mode = LENGTH;
4655
/* falls through */
4656
case LENGTH:
4657
if (state.wrap && state.flags) {
4658
//=== NEEDBITS(32);
4659
while (bits < 32) {
4660
if (have === 0) { break inf_leave; }
4661
have--;
4662
hold += input[next++] << bits;
4663
bits += 8;
4664
}
4665
//===//
4666
if (hold !== (state.total & 0xffffffff)) {
4667
strm.msg = 'incorrect length check';
4668
state.mode = BAD;
4669
break;
4670
}
4671
//=== INITBITS();
4672
hold = 0;
4673
bits = 0;
4674
//===//
4675
//Tracev((stderr, "inflate: length matches trailer\n"));
4676
}
4677
state.mode = DONE;
4678
/* falls through */
4679
case DONE:
4680
ret = Z_STREAM_END;
4681
break inf_leave;
4682
case BAD:
4683
ret = Z_DATA_ERROR;
4684
break inf_leave;
4685
case MEM:
4686
return Z_MEM_ERROR;
4687
case SYNC:
4688
/* falls through */
4689
default:
4690
return Z_STREAM_ERROR;
4691
}
4692
}
4693
4694
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
4695
4696
/*
4697
Return from inflate(), updating the total counts and the check value.
4698
If there was no progress during the inflate() call, return a buffer
4699
error. Call updatewindow() to create and/or update the window state.
4700
Note: a memory error from inflate() is non-recoverable.
4701
*/
4702
4703
//--- RESTORE() ---
4704
strm.next_out = put;
4705
strm.avail_out = left;
4706
strm.next_in = next;
4707
strm.avail_in = have;
4708
state.hold = hold;
4709
state.bits = bits;
4710
//---
4711
4712
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
4713
(state.mode < CHECK || flush !== Z_FINISH))) {
4714
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
4715
state.mode = MEM;
4716
return Z_MEM_ERROR;
4717
}
4718
}
4719
_in -= strm.avail_in;
4720
_out -= strm.avail_out;
4721
strm.total_in += _in;
4722
strm.total_out += _out;
4723
state.total += _out;
4724
if (state.wrap && _out) {
4725
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
4726
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
4727
}
4728
strm.data_type = state.bits + (state.last ? 64 : 0) +
4729
(state.mode === TYPE ? 128 : 0) +
4730
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
4731
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
4732
ret = Z_BUF_ERROR;
4733
}
4734
return ret;
4735
}
4736
4737
function inflateEnd(strm) {
4738
4739
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
4740
return Z_STREAM_ERROR;
4741
}
4742
4743
var state = strm.state;
4744
if (state.window) {
4745
state.window = null;
4746
}
4747
strm.state = null;
4748
return Z_OK;
4749
}
4750
4751
function inflateGetHeader(strm, head) {
4752
var state;
4753
4754
/* check state */
4755
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
4756
state = strm.state;
4757
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
4758
4759
/* save header structure */
4760
state.head = head;
4761
head.done = false;
4762
return Z_OK;
4763
}
4764
4765
4766
exports.inflateReset = inflateReset;
4767
exports.inflateReset2 = inflateReset2;
4768
exports.inflateResetKeep = inflateResetKeep;
4769
exports.inflateInit = inflateInit;
4770
exports.inflateInit2 = inflateInit2;
4771
exports.inflate = inflate;
4772
exports.inflateEnd = inflateEnd;
4773
exports.inflateGetHeader = inflateGetHeader;
4774
exports.inflateInfo = 'pako inflate (from Nodeca project)';
4775
4776
/* Not implemented
4777
exports.inflateCopy = inflateCopy;
4778
exports.inflateGetDictionary = inflateGetDictionary;
4779
exports.inflateMark = inflateMark;
4780
exports.inflatePrime = inflatePrime;
4781
exports.inflateSetDictionary = inflateSetDictionary;
4782
exports.inflateSync = inflateSync;
4783
exports.inflateSyncPoint = inflateSyncPoint;
4784
exports.inflateUndermine = inflateUndermine;
4785
*/
4786
},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(require,module,exports){
4787
'use strict';
4788
4789
4790
var utils = require('../utils/common');
4791
4792
var MAXBITS = 15;
4793
var ENOUGH_LENS = 852;
4794
var ENOUGH_DISTS = 592;
4795
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
4796
4797
var CODES = 0;
4798
var LENS = 1;
4799
var DISTS = 2;
4800
4801
var lbase = [ /* Length codes 257..285 base */
4802
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
4803
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
4804
];
4805
4806
var lext = [ /* Length codes 257..285 extra */
4807
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
4808
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
4809
];
4810
4811
var dbase = [ /* Distance codes 0..29 base */
4812
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
4813
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
4814
8193, 12289, 16385, 24577, 0, 0
4815
];
4816
4817
var dext = [ /* Distance codes 0..29 extra */
4818
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
4819
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
4820
28, 28, 29, 29, 64, 64
4821
];
4822
4823
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
4824
{
4825
var bits = opts.bits;
4826
//here = opts.here; /* table entry for duplication */
4827
4828
var len = 0; /* a code's length in bits */
4829
var sym = 0; /* index of code symbols */
4830
var min = 0, max = 0; /* minimum and maximum code lengths */
4831
var root = 0; /* number of index bits for root table */
4832
var curr = 0; /* number of index bits for current table */
4833
var drop = 0; /* code bits to drop for sub-table */
4834
var left = 0; /* number of prefix codes available */
4835
var used = 0; /* code entries in table used */
4836
var huff = 0; /* Huffman code */
4837
var incr; /* for incrementing code, index */
4838
var fill; /* index for replicating entries */
4839
var low; /* low bits for current root entry */
4840
var mask; /* mask for low root bits */
4841
var next; /* next available space in table */
4842
var base = null; /* base value table to use */
4843
var base_index = 0;
4844
// var shoextra; /* extra bits table to use */
4845
var end; /* use base and extra for symbol > end */
4846
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
4847
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
4848
var extra = null;
4849
var extra_index = 0;
4850
4851
var here_bits, here_op, here_val;
4852
4853
/*
4854
Process a set of code lengths to create a canonical Huffman code. The
4855
code lengths are lens[0..codes-1]. Each length corresponds to the
4856
symbols 0..codes-1. The Huffman code is generated by first sorting the
4857
symbols by length from short to long, and retaining the symbol order
4858
for codes with equal lengths. Then the code starts with all zero bits
4859
for the first code of the shortest length, and the codes are integer
4860
increments for the same length, and zeros are appended as the length
4861
increases. For the deflate format, these bits are stored backwards
4862
from their more natural integer increment ordering, and so when the
4863
decoding tables are built in the large loop below, the integer codes
4864
are incremented backwards.
4865
4866
This routine assumes, but does not check, that all of the entries in
4867
lens[] are in the range 0..MAXBITS. The caller must assure this.
4868
1..MAXBITS is interpreted as that code length. zero means that that
4869
symbol does not occur in this code.
4870
4871
The codes are sorted by computing a count of codes for each length,
4872
creating from that a table of starting indices for each length in the
4873
sorted table, and then entering the symbols in order in the sorted
4874
table. The sorted table is work[], with that space being provided by
4875
the caller.
4876
4877
The length counts are used for other purposes as well, i.e. finding
4878
the minimum and maximum length codes, determining if there are any
4879
codes at all, checking for a valid set of lengths, and looking ahead
4880
at length counts to determine sub-table sizes when building the
4881
decoding tables.
4882
*/
4883
4884
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
4885
for (len = 0; len <= MAXBITS; len++) {
4886
count[len] = 0;
4887
}
4888
for (sym = 0; sym < codes; sym++) {
4889
count[lens[lens_index + sym]]++;
4890
}
4891
4892
/* bound code lengths, force root to be within code lengths */
4893
root = bits;
4894
for (max = MAXBITS; max >= 1; max--) {
4895
if (count[max] !== 0) { break; }
4896
}
4897
if (root > max) {
4898
root = max;
4899
}
4900
if (max === 0) { /* no symbols to code at all */
4901
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
4902
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
4903
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
4904
table[table_index++] = (1 << 24) | (64 << 16) | 0;
4905
4906
4907
//table.op[opts.table_index] = 64;
4908
//table.bits[opts.table_index] = 1;
4909
//table.val[opts.table_index++] = 0;
4910
table[table_index++] = (1 << 24) | (64 << 16) | 0;
4911
4912
opts.bits = 1;
4913
return 0; /* no symbols, but wait for decoding to report error */
4914
}
4915
for (min = 1; min < max; min++) {
4916
if (count[min] !== 0) { break; }
4917
}
4918
if (root < min) {
4919
root = min;
4920
}
4921
4922
/* check for an over-subscribed or incomplete set of lengths */
4923
left = 1;
4924
for (len = 1; len <= MAXBITS; len++) {
4925
left <<= 1;
4926
left -= count[len];
4927
if (left < 0) {
4928
return -1;
4929
} /* over-subscribed */
4930
}
4931
if (left > 0 && (type === CODES || max !== 1)) {
4932
return -1; /* incomplete set */
4933
}
4934
4935
/* generate offsets into symbol table for each length for sorting */
4936
offs[1] = 0;
4937
for (len = 1; len < MAXBITS; len++) {
4938
offs[len + 1] = offs[len] + count[len];
4939
}
4940
4941
/* sort symbols by length, by symbol order within each length */
4942
for (sym = 0; sym < codes; sym++) {
4943
if (lens[lens_index + sym] !== 0) {
4944
work[offs[lens[lens_index + sym]]++] = sym;
4945
}
4946
}
4947
4948
/*
4949
Create and fill in decoding tables. In this loop, the table being
4950
filled is at next and has curr index bits. The code being used is huff
4951
with length len. That code is converted to an index by dropping drop
4952
bits off of the bottom. For codes where len is less than drop + curr,
4953
those top drop + curr - len bits are incremented through all values to
4954
fill the table with replicated entries.
4955
4956
root is the number of index bits for the root table. When len exceeds
4957
root, sub-tables are created pointed to by the root entry with an index
4958
of the low root bits of huff. This is saved in low to check for when a
4959
new sub-table should be started. drop is zero when the root table is
4960
being filled, and drop is root when sub-tables are being filled.
4961
4962
When a new sub-table is needed, it is necessary to look ahead in the
4963
code lengths to determine what size sub-table is needed. The length
4964
counts are used for this, and so count[] is decremented as codes are
4965
entered in the tables.
4966
4967
used keeps track of how many table entries have been allocated from the
4968
provided *table space. It is checked for LENS and DIST tables against
4969
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
4970
the initial root table size constants. See the comments in inftrees.h
4971
for more information.
4972
4973
sym increments through all symbols, and the loop terminates when
4974
all codes of length max, i.e. all codes, have been processed. This
4975
routine permits incomplete codes, so another loop after this one fills
4976
in the rest of the decoding tables with invalid code markers.
4977
*/
4978
4979
/* set up for code type */
4980
// poor man optimization - use if-else instead of switch,
4981
// to avoid deopts in old v8
4982
if (type === CODES) {
4983
base = extra = work; /* dummy value--not used */
4984
end = 19;
4985
} else if (type === LENS) {
4986
base = lbase;
4987
base_index -= 257;
4988
extra = lext;
4989
extra_index -= 257;
4990
end = 256;
4991
} else { /* DISTS */
4992
base = dbase;
4993
extra = dext;
4994
end = -1;
4995
}
4996
4997
/* initialize opts for loop */
4998
huff = 0; /* starting code */
4999
sym = 0; /* starting code symbol */
5000
len = min; /* starting code length */
5001
next = table_index; /* current table to fill in */
5002
curr = root; /* current table index bits */
5003
drop = 0; /* current bits to drop from code for index */
5004
low = -1; /* trigger new sub-table when len > root */
5005
used = 1 << root; /* use root table entries */
5006
mask = used - 1; /* mask for comparing low */
5007
5008
/* check available table space */
5009
if ((type === LENS && used > ENOUGH_LENS) ||
5010
(type === DISTS && used > ENOUGH_DISTS)) {
5011
return 1;
5012
}
5013
5014
var i=0;
5015
/* process all codes and make table entries */
5016
for (;;) {
5017
i++;
5018
/* create table entry */
5019
here_bits = len - drop;
5020
if (work[sym] < end) {
5021
here_op = 0;
5022
here_val = work[sym];
5023
}
5024
else if (work[sym] > end) {
5025
here_op = extra[extra_index + work[sym]];
5026
here_val = base[base_index + work[sym]];
5027
}
5028
else {
5029
here_op = 32 + 64; /* end of block */
5030
here_val = 0;
5031
}
5032
5033
/* replicate for those indices with low len bits equal to huff */
5034
incr = 1 << (len - drop);
5035
fill = 1 << curr;
5036
min = fill; /* save offset to next table */
5037
do {
5038
fill -= incr;
5039
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
5040
} while (fill !== 0);
5041
5042
/* backwards increment the len-bit code huff */
5043
incr = 1 << (len - 1);
5044
while (huff & incr) {
5045
incr >>= 1;
5046
}
5047
if (incr !== 0) {
5048
huff &= incr - 1;
5049
huff += incr;
5050
} else {
5051
huff = 0;
5052
}
5053
5054
/* go to next symbol, update count, len */
5055
sym++;
5056
if (--count[len] === 0) {
5057
if (len === max) { break; }
5058
len = lens[lens_index + work[sym]];
5059
}
5060
5061
/* create new sub-table if needed */
5062
if (len > root && (huff & mask) !== low) {
5063
/* if first time, transition to sub-tables */
5064
if (drop === 0) {
5065
drop = root;
5066
}
5067
5068
/* increment past last table */
5069
next += min; /* here min is 1 << curr */
5070
5071
/* determine length of next table */
5072
curr = len - drop;
5073
left = 1 << curr;
5074
while (curr + drop < max) {
5075
left -= count[curr + drop];
5076
if (left <= 0) { break; }
5077
curr++;
5078
left <<= 1;
5079
}
5080
5081
/* check for enough space */
5082
used += 1 << curr;
5083
if ((type === LENS && used > ENOUGH_LENS) ||
5084
(type === DISTS && used > ENOUGH_DISTS)) {
5085
return 1;
5086
}
5087
5088
/* point entry in root table to sub-table */
5089
low = huff & mask;
5090
/*table.op[low] = curr;
5091
table.bits[low] = root;
5092
table.val[low] = next - opts.table_index;*/
5093
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
5094
}
5095
}
5096
5097
/* fill in remaining table entry if code is incomplete (guaranteed to have
5098
at most one remaining entry, since if the code is incomplete, the
5099
maximum code length that was allowed to get this far is one bit) */
5100
if (huff !== 0) {
5101
//table.op[next + huff] = 64; /* invalid code marker */
5102
//table.bits[next + huff] = len - drop;
5103
//table.val[next + huff] = 0;
5104
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
5105
}
5106
5107
/* set return parameters */
5108
//opts.table_index += used;
5109
opts.bits = root;
5110
return 0;
5111
};
5112
5113
},{"../utils/common":3}],13:[function(require,module,exports){
5114
'use strict';
5115
5116
module.exports = {
5117
'2': 'need dictionary', /* Z_NEED_DICT 2 */
5118
'1': 'stream end', /* Z_STREAM_END 1 */
5119
'0': '', /* Z_OK 0 */
5120
'-1': 'file error', /* Z_ERRNO (-1) */
5121
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
5122
'-3': 'data error', /* Z_DATA_ERROR (-3) */
5123
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
5124
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
5125
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
5126
};
5127
},{}],14:[function(require,module,exports){
5128
'use strict';
5129
5130
5131
var utils = require('../utils/common');
5132
5133
/* Public constants ==========================================================*/
5134
/* ===========================================================================*/
5135
5136
5137
//var Z_FILTERED = 1;
5138
//var Z_HUFFMAN_ONLY = 2;
5139
//var Z_RLE = 3;
5140
var Z_FIXED = 4;
5141
//var Z_DEFAULT_STRATEGY = 0;
5142
5143
/* Possible values of the data_type field (though see inflate()) */
5144
var Z_BINARY = 0;
5145
var Z_TEXT = 1;
5146
//var Z_ASCII = 1; // = Z_TEXT
5147
var Z_UNKNOWN = 2;
5148
5149
/*============================================================================*/
5150
5151
5152
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
5153
5154
// From zutil.h
5155
5156
var STORED_BLOCK = 0;
5157
var STATIC_TREES = 1;
5158
var DYN_TREES = 2;
5159
/* The three kinds of block type */
5160
5161
var MIN_MATCH = 3;
5162
var MAX_MATCH = 258;
5163
/* The minimum and maximum match lengths */
5164
5165
// From deflate.h
5166
/* ===========================================================================
5167
* Internal compression state.
5168
*/
5169
5170
var LENGTH_CODES = 29;
5171
/* number of length codes, not counting the special END_BLOCK code */
5172
5173
var LITERALS = 256;
5174
/* number of literal bytes 0..255 */
5175
5176
var L_CODES = LITERALS + 1 + LENGTH_CODES;
5177
/* number of Literal or Length codes, including the END_BLOCK code */
5178
5179
var D_CODES = 30;
5180
/* number of distance codes */
5181
5182
var BL_CODES = 19;
5183
/* number of codes used to transfer the bit lengths */
5184
5185
var HEAP_SIZE = 2*L_CODES + 1;
5186
/* maximum heap size */
5187
5188
var MAX_BITS = 15;
5189
/* All codes must not exceed MAX_BITS bits */
5190
5191
var Buf_size = 16;
5192
/* size of bit buffer in bi_buf */
5193
5194
5195
/* ===========================================================================
5196
* Constants
5197
*/
5198
5199
var MAX_BL_BITS = 7;
5200
/* Bit length codes must not exceed MAX_BL_BITS bits */
5201
5202
var END_BLOCK = 256;
5203
/* end of block literal code */
5204
5205
var REP_3_6 = 16;
5206
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
5207
5208
var REPZ_3_10 = 17;
5209
/* repeat a zero length 3-10 times (3 bits of repeat count) */
5210
5211
var REPZ_11_138 = 18;
5212
/* repeat a zero length 11-138 times (7 bits of repeat count) */
5213
5214
var extra_lbits = /* extra bits for each length code */
5215
[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];
5216
5217
var extra_dbits = /* extra bits for each distance code */
5218
[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];
5219
5220
var extra_blbits = /* extra bits for each bit length code */
5221
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
5222
5223
var bl_order =
5224
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
5225
/* The lengths of the bit length codes are sent in order of decreasing
5226
* probability, to avoid transmitting the lengths for unused bit length codes.
5227
*/
5228
5229
/* ===========================================================================
5230
* Local data. These are initialized only once.
5231
*/
5232
5233
// We pre-fill arrays with 0 to avoid uninitialized gaps
5234
5235
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
5236
5237
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
5238
var static_ltree = new Array((L_CODES+2) * 2);
5239
zero(static_ltree);
5240
/* The static literal tree. Since the bit lengths are imposed, there is no
5241
* need for the L_CODES extra codes used during heap construction. However
5242
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
5243
* below).
5244
*/
5245
5246
var static_dtree = new Array(D_CODES * 2);
5247
zero(static_dtree);
5248
/* The static distance tree. (Actually a trivial tree since all codes use
5249
* 5 bits.)
5250
*/
5251
5252
var _dist_code = new Array(DIST_CODE_LEN);
5253
zero(_dist_code);
5254
/* Distance codes. The first 256 values correspond to the distances
5255
* 3 .. 258, the last 256 values correspond to the top 8 bits of
5256
* the 15 bit distances.
5257
*/
5258
5259
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
5260
zero(_length_code);
5261
/* length code for each normalized match length (0 == MIN_MATCH) */
5262
5263
var base_length = new Array(LENGTH_CODES);
5264
zero(base_length);
5265
/* First normalized length for each code (0 = MIN_MATCH) */
5266
5267
var base_dist = new Array(D_CODES);
5268
zero(base_dist);
5269
/* First normalized distance for each code (0 = distance of 1) */
5270
5271
5272
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
5273
5274
this.static_tree = static_tree; /* static tree or NULL */
5275
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
5276
this.extra_base = extra_base; /* base index for extra_bits */
5277
this.elems = elems; /* max number of elements in the tree */
5278
this.max_length = max_length; /* max bit length for the codes */
5279
5280
// show if `static_tree` has data or dummy - needed for monomorphic objects
5281
this.has_stree = static_tree && static_tree.length;
5282
};
5283
5284
5285
var static_l_desc;
5286
var static_d_desc;
5287
var static_bl_desc;
5288
5289
5290
var TreeDesc = function(dyn_tree, stat_desc) {
5291
this.dyn_tree = dyn_tree; /* the dynamic tree */
5292
this.max_code = 0; /* largest code with non zero frequency */
5293
this.stat_desc = stat_desc; /* the corresponding static tree */
5294
};
5295
5296
5297
5298
function d_code(dist) {
5299
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
5300
}
5301
5302
5303
/* ===========================================================================
5304
* Output a short LSB first on the stream.
5305
* IN assertion: there is enough room in pendingBuf.
5306
*/
5307
function put_short (s, w) {
5308
// put_byte(s, (uch)((w) & 0xff));
5309
// put_byte(s, (uch)((ush)(w) >> 8));
5310
s.pending_buf[s.pending++] = (w) & 0xff;
5311
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
5312
}
5313
5314
5315
/* ===========================================================================
5316
* Send a value on a given number of bits.
5317
* IN assertion: length <= 16 and value fits in length bits.
5318
*/
5319
function send_bits(s, value, length) {
5320
if (s.bi_valid > (Buf_size - length)) {
5321
s.bi_buf |= (value << s.bi_valid) & 0xffff;
5322
put_short(s, s.bi_buf);
5323
s.bi_buf = value >> (Buf_size - s.bi_valid);
5324
s.bi_valid += length - Buf_size;
5325
} else {
5326
s.bi_buf |= (value << s.bi_valid) & 0xffff;
5327
s.bi_valid += length;
5328
}
5329
}
5330
5331
5332
function send_code(s, c, tree) {
5333
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
5334
}
5335
5336
5337
/* ===========================================================================
5338
* Reverse the first len bits of a code, using straightforward code (a faster
5339
* method would use a table)
5340
* IN assertion: 1 <= len <= 15
5341
*/
5342
function bi_reverse(code, len) {
5343
var res = 0;
5344
do {
5345
res |= code & 1;
5346
code >>>= 1;
5347
res <<= 1;
5348
} while (--len > 0);
5349
return res >>> 1;
5350
}
5351
5352
5353
/* ===========================================================================
5354
* Flush the bit buffer, keeping at most 7 bits in it.
5355
*/
5356
function bi_flush(s) {
5357
if (s.bi_valid === 16) {
5358
put_short(s, s.bi_buf);
5359
s.bi_buf = 0;
5360
s.bi_valid = 0;
5361
5362
} else if (s.bi_valid >= 8) {
5363
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
5364
s.bi_buf >>= 8;
5365
s.bi_valid -= 8;
5366
}
5367
}
5368
5369
5370
/* ===========================================================================
5371
* Compute the optimal bit lengths for a tree and update the total bit length
5372
* for the current block.
5373
* IN assertion: the fields freq and dad are set, heap[heap_max] and
5374
* above are the tree nodes sorted by increasing frequency.
5375
* OUT assertions: the field len is set to the optimal bit length, the
5376
* array bl_count contains the frequencies for each bit length.
5377
* The length opt_len is updated; static_len is also updated if stree is
5378
* not null.
5379
*/
5380
function gen_bitlen(s, desc)
5381
// deflate_state *s;
5382
// tree_desc *desc; /* the tree descriptor */
5383
{
5384
var tree = desc.dyn_tree;
5385
var max_code = desc.max_code;
5386
var stree = desc.stat_desc.static_tree;
5387
var has_stree = desc.stat_desc.has_stree;
5388
var extra = desc.stat_desc.extra_bits;
5389
var base = desc.stat_desc.extra_base;
5390
var max_length = desc.stat_desc.max_length;
5391
var h; /* heap index */
5392
var n, m; /* iterate over the tree elements */
5393
var bits; /* bit length */
5394
var xbits; /* extra bits */
5395
var f; /* frequency */
5396
var overflow = 0; /* number of elements with bit length too large */
5397
5398
for (bits = 0; bits <= MAX_BITS; bits++) {
5399
s.bl_count[bits] = 0;
5400
}
5401
5402
/* In a first pass, compute the optimal bit lengths (which may
5403
* overflow in the case of the bit length tree).
5404
*/
5405
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
5406
5407
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
5408
n = s.heap[h];
5409
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
5410
if (bits > max_length) {
5411
bits = max_length;
5412
overflow++;
5413
}
5414
tree[n*2 + 1]/*.Len*/ = bits;
5415
/* We overwrite tree[n].Dad which is no longer needed */
5416
5417
if (n > max_code) { continue; } /* not a leaf node */
5418
5419
s.bl_count[bits]++;
5420
xbits = 0;
5421
if (n >= base) {
5422
xbits = extra[n-base];
5423
}
5424
f = tree[n * 2]/*.Freq*/;
5425
s.opt_len += f * (bits + xbits);
5426
if (has_stree) {
5427
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
5428
}
5429
}
5430
if (overflow === 0) { return; }
5431
5432
// Trace((stderr,"\nbit length overflow\n"));
5433
/* This happens for example on obj2 and pic of the Calgary corpus */
5434
5435
/* Find the first bit length which could increase: */
5436
do {
5437
bits = max_length-1;
5438
while (s.bl_count[bits] === 0) { bits--; }
5439
s.bl_count[bits]--; /* move one leaf down the tree */
5440
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
5441
s.bl_count[max_length]--;
5442
/* The brother of the overflow item also moves one step up,
5443
* but this does not affect bl_count[max_length]
5444
*/
5445
overflow -= 2;
5446
} while (overflow > 0);
5447
5448
/* Now recompute all bit lengths, scanning in increasing frequency.
5449
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
5450
* lengths instead of fixing only the wrong ones. This idea is taken
5451
* from 'ar' written by Haruhiko Okumura.)
5452
*/
5453
for (bits = max_length; bits !== 0; bits--) {
5454
n = s.bl_count[bits];
5455
while (n !== 0) {
5456
m = s.heap[--h];
5457
if (m > max_code) { continue; }
5458
if (tree[m*2 + 1]/*.Len*/ !== bits) {
5459
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
5460
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
5461
tree[m*2 + 1]/*.Len*/ = bits;
5462
}
5463
n--;
5464
}
5465
}
5466
}
5467
5468
5469
/* ===========================================================================
5470
* Generate the codes for a given tree and bit counts (which need not be
5471
* optimal).
5472
* IN assertion: the array bl_count contains the bit length statistics for
5473
* the given tree and the field len is set for all tree elements.
5474
* OUT assertion: the field code is set for all tree elements of non
5475
* zero code length.
5476
*/
5477
function gen_codes(tree, max_code, bl_count)
5478
// ct_data *tree; /* the tree to decorate */
5479
// int max_code; /* largest code with non zero frequency */
5480
// ushf *bl_count; /* number of codes at each bit length */
5481
{
5482
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
5483
var code = 0; /* running code value */
5484
var bits; /* bit index */
5485
var n; /* code index */
5486
5487
/* The distribution counts are first used to generate the code values
5488
* without bit reversal.
5489
*/
5490
for (bits = 1; bits <= MAX_BITS; bits++) {
5491
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
5492
}
5493
/* Check that the bit counts in bl_count are consistent. The last code
5494
* must be all ones.
5495
*/
5496
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
5497
// "inconsistent bit counts");
5498
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
5499
5500
for (n = 0; n <= max_code; n++) {
5501
var len = tree[n*2 + 1]/*.Len*/;
5502
if (len === 0) { continue; }
5503
/* Now reverse the bits */
5504
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
5505
5506
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
5507
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
5508
}
5509
}
5510
5511
5512
/* ===========================================================================
5513
* Initialize the various 'constant' tables.
5514
*/
5515
function tr_static_init() {
5516
var n; /* iterates over tree elements */
5517
var bits; /* bit counter */
5518
var length; /* length value */
5519
var code; /* code value */
5520
var dist; /* distance index */
5521
var bl_count = new Array(MAX_BITS+1);
5522
/* number of codes at each bit length for an optimal tree */
5523
5524
// do check in _tr_init()
5525
//if (static_init_done) return;
5526
5527
/* For some embedded targets, global variables are not initialized: */
5528
/*#ifdef NO_INIT_GLOBAL_POINTERS
5529
static_l_desc.static_tree = static_ltree;
5530
static_l_desc.extra_bits = extra_lbits;
5531
static_d_desc.static_tree = static_dtree;
5532
static_d_desc.extra_bits = extra_dbits;
5533
static_bl_desc.extra_bits = extra_blbits;
5534
#endif*/
5535
5536
/* Initialize the mapping length (0..255) -> length code (0..28) */
5537
length = 0;
5538
for (code = 0; code < LENGTH_CODES-1; code++) {
5539
base_length[code] = length;
5540
for (n = 0; n < (1<<extra_lbits[code]); n++) {
5541
_length_code[length++] = code;
5542
}
5543
}
5544
//Assert (length == 256, "tr_static_init: length != 256");
5545
/* Note that the length 255 (match length 258) can be represented
5546
* in two different ways: code 284 + 5 bits or code 285, so we
5547
* overwrite length_code[255] to use the best encoding:
5548
*/
5549
_length_code[length-1] = code;
5550
5551
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
5552
dist = 0;
5553
for (code = 0 ; code < 16; code++) {
5554
base_dist[code] = dist;
5555
for (n = 0; n < (1<<extra_dbits[code]); n++) {
5556
_dist_code[dist++] = code;
5557
}
5558
}
5559
//Assert (dist == 256, "tr_static_init: dist != 256");
5560
dist >>= 7; /* from now on, all distances are divided by 128 */
5561
for ( ; code < D_CODES; code++) {
5562
base_dist[code] = dist << 7;
5563
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
5564
_dist_code[256 + dist++] = code;
5565
}
5566
}
5567
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
5568
5569
/* Construct the codes of the static literal tree */
5570
for (bits = 0; bits <= MAX_BITS; bits++) {
5571
bl_count[bits] = 0;
5572
}
5573
5574
n = 0;
5575
while (n <= 143) {
5576
static_ltree[n*2 + 1]/*.Len*/ = 8;
5577
n++;
5578
bl_count[8]++;
5579
}
5580
while (n <= 255) {
5581
static_ltree[n*2 + 1]/*.Len*/ = 9;
5582
n++;
5583
bl_count[9]++;
5584
}
5585
while (n <= 279) {
5586
static_ltree[n*2 + 1]/*.Len*/ = 7;
5587
n++;
5588
bl_count[7]++;
5589
}
5590
while (n <= 287) {
5591
static_ltree[n*2 + 1]/*.Len*/ = 8;
5592
n++;
5593
bl_count[8]++;
5594
}
5595
/* Codes 286 and 287 do not exist, but we must include them in the
5596
* tree construction to get a canonical Huffman tree (longest code
5597
* all ones)
5598
*/
5599
gen_codes(static_ltree, L_CODES+1, bl_count);
5600
5601
/* The static distance tree is trivial: */
5602
for (n = 0; n < D_CODES; n++) {
5603
static_dtree[n*2 + 1]/*.Len*/ = 5;
5604
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
5605
}
5606
5607
// Now data ready and we can init static trees
5608
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
5609
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
5610
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
5611
5612
//static_init_done = true;
5613
}
5614
5615
5616
/* ===========================================================================
5617
* Initialize a new block.
5618
*/
5619
function init_block(s) {
5620
var n; /* iterates over tree elements */
5621
5622
/* Initialize the trees. */
5623
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
5624
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
5625
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
5626
5627
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
5628
s.opt_len = s.static_len = 0;
5629
s.last_lit = s.matches = 0;
5630
}
5631
5632
5633
/* ===========================================================================
5634
* Flush the bit buffer and align the output on a byte boundary
5635
*/
5636
function bi_windup(s)
5637
{
5638
if (s.bi_valid > 8) {
5639
put_short(s, s.bi_buf);
5640
} else if (s.bi_valid > 0) {
5641
//put_byte(s, (Byte)s->bi_buf);
5642
s.pending_buf[s.pending++] = s.bi_buf;
5643
}
5644
s.bi_buf = 0;
5645
s.bi_valid = 0;
5646
}
5647
5648
/* ===========================================================================
5649
* Copy a stored block, storing first the length and its
5650
* one's complement if requested.
5651
*/
5652
function copy_block(s, buf, len, header)
5653
//DeflateState *s;
5654
//charf *buf; /* the input data */
5655
//unsigned len; /* its length */
5656
//int header; /* true if block header must be written */
5657
{
5658
bi_windup(s); /* align on byte boundary */
5659
5660
if (header) {
5661
put_short(s, len);
5662
put_short(s, ~len);
5663
}
5664
// while (len--) {
5665
// put_byte(s, *buf++);
5666
// }
5667
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
5668
s.pending += len;
5669
}
5670
5671
/* ===========================================================================
5672
* Compares to subtrees, using the tree depth as tie breaker when
5673
* the subtrees have equal frequency. This minimizes the worst case length.
5674
*/
5675
function smaller(tree, n, m, depth) {
5676
var _n2 = n*2;
5677
var _m2 = m*2;
5678
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
5679
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
5680
}
5681
5682
/* ===========================================================================
5683
* Restore the heap property by moving down the tree starting at node k,
5684
* exchanging a node with the smallest of its two sons if necessary, stopping
5685
* when the heap property is re-established (each father smaller than its
5686
* two sons).
5687
*/
5688
function pqdownheap(s, tree, k)
5689
// deflate_state *s;
5690
// ct_data *tree; /* the tree to restore */
5691
// int k; /* node to move down */
5692
{
5693
var v = s.heap[k];
5694
var j = k << 1; /* left son of k */
5695
while (j <= s.heap_len) {
5696
/* Set j to the smallest of the two sons: */
5697
if (j < s.heap_len &&
5698
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
5699
j++;
5700
}
5701
/* Exit if v is smaller than both sons */
5702
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
5703
5704
/* Exchange v with the smallest son */
5705
s.heap[k] = s.heap[j];
5706
k = j;
5707
5708
/* And continue down the tree, setting j to the left son of k */
5709
j <<= 1;
5710
}
5711
s.heap[k] = v;
5712
}
5713
5714
5715
// inlined manually
5716
// var SMALLEST = 1;
5717
5718
/* ===========================================================================
5719
* Send the block data compressed using the given Huffman trees
5720
*/
5721
function compress_block(s, ltree, dtree)
5722
// deflate_state *s;
5723
// const ct_data *ltree; /* literal tree */
5724
// const ct_data *dtree; /* distance tree */
5725
{
5726
var dist; /* distance of matched string */
5727
var lc; /* match length or unmatched char (if dist == 0) */
5728
var lx = 0; /* running index in l_buf */
5729
var code; /* the code to send */
5730
var extra; /* number of extra bits to send */
5731
5732
if (s.last_lit !== 0) {
5733
do {
5734
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
5735
lc = s.pending_buf[s.l_buf + lx];
5736
lx++;
5737
5738
if (dist === 0) {
5739
send_code(s, lc, ltree); /* send a literal byte */
5740
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
5741
} else {
5742
/* Here, lc is the match length - MIN_MATCH */
5743
code = _length_code[lc];
5744
send_code(s, code+LITERALS+1, ltree); /* send the length code */
5745
extra = extra_lbits[code];
5746
if (extra !== 0) {
5747
lc -= base_length[code];
5748
send_bits(s, lc, extra); /* send the extra length bits */
5749
}
5750
dist--; /* dist is now the match distance - 1 */
5751
code = d_code(dist);
5752
//Assert (code < D_CODES, "bad d_code");
5753
5754
send_code(s, code, dtree); /* send the distance code */
5755
extra = extra_dbits[code];
5756
if (extra !== 0) {
5757
dist -= base_dist[code];
5758
send_bits(s, dist, extra); /* send the extra distance bits */
5759
}
5760
} /* literal or match pair ? */
5761
5762
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
5763
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
5764
// "pendingBuf overflow");
5765
5766
} while (lx < s.last_lit);
5767
}
5768
5769
send_code(s, END_BLOCK, ltree);
5770
}
5771
5772
5773
/* ===========================================================================
5774
* Construct one Huffman tree and assigns the code bit strings and lengths.
5775
* Update the total bit length for the current block.
5776
* IN assertion: the field freq is set for all tree elements.
5777
* OUT assertions: the fields len and code are set to the optimal bit length
5778
* and corresponding code. The length opt_len is updated; static_len is
5779
* also updated if stree is not null. The field max_code is set.
5780
*/
5781
function build_tree(s, desc)
5782
// deflate_state *s;
5783
// tree_desc *desc; /* the tree descriptor */
5784
{
5785
var tree = desc.dyn_tree;
5786
var stree = desc.stat_desc.static_tree;
5787
var has_stree = desc.stat_desc.has_stree;
5788
var elems = desc.stat_desc.elems;
5789
var n, m; /* iterate over heap elements */
5790
var max_code = -1; /* largest code with non zero frequency */
5791
var node; /* new node being created */
5792
5793
/* Construct the initial heap, with least frequent element in
5794
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
5795
* heap[0] is not used.
5796
*/
5797
s.heap_len = 0;
5798
s.heap_max = HEAP_SIZE;
5799
5800
for (n = 0; n < elems; n++) {
5801
if (tree[n * 2]/*.Freq*/ !== 0) {
5802
s.heap[++s.heap_len] = max_code = n;
5803
s.depth[n] = 0;
5804
5805
} else {
5806
tree[n*2 + 1]/*.Len*/ = 0;
5807
}
5808
}
5809
5810
/* The pkzip format requires that at least one distance code exists,
5811
* and that at least one bit should be sent even if there is only one
5812
* possible code. So to avoid special checks later on we force at least
5813
* two codes of non zero frequency.
5814
*/
5815
while (s.heap_len < 2) {
5816
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
5817
tree[node * 2]/*.Freq*/ = 1;
5818
s.depth[node] = 0;
5819
s.opt_len--;
5820
5821
if (has_stree) {
5822
s.static_len -= stree[node*2 + 1]/*.Len*/;
5823
}
5824
/* node is 0 or 1 so it does not have extra bits */
5825
}
5826
desc.max_code = max_code;
5827
5828
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
5829
* establish sub-heaps of increasing lengths:
5830
*/
5831
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
5832
5833
/* Construct the Huffman tree by repeatedly combining the least two
5834
* frequent nodes.
5835
*/
5836
node = elems; /* next internal node of the tree */
5837
do {
5838
//pqremove(s, tree, n); /* n = node of least frequency */
5839
/*** pqremove ***/
5840
n = s.heap[1/*SMALLEST*/];
5841
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
5842
pqdownheap(s, tree, 1/*SMALLEST*/);
5843
/***/
5844
5845
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
5846
5847
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
5848
s.heap[--s.heap_max] = m;
5849
5850
/* Create a new node father of n and m */
5851
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
5852
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
5853
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
5854
5855
/* and insert the new node in the heap */
5856
s.heap[1/*SMALLEST*/] = node++;
5857
pqdownheap(s, tree, 1/*SMALLEST*/);
5858
5859
} while (s.heap_len >= 2);
5860
5861
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
5862
5863
/* At this point, the fields freq and dad are set. We can now
5864
* generate the bit lengths.
5865
*/
5866
gen_bitlen(s, desc);
5867
5868
/* The field len is now set, we can generate the bit codes */
5869
gen_codes(tree, max_code, s.bl_count);
5870
}
5871
5872
5873
/* ===========================================================================
5874
* Scan a literal or distance tree to determine the frequencies of the codes
5875
* in the bit length tree.
5876
*/
5877
function scan_tree(s, tree, max_code)
5878
// deflate_state *s;
5879
// ct_data *tree; /* the tree to be scanned */
5880
// int max_code; /* and its largest code of non zero frequency */
5881
{
5882
var n; /* iterates over all tree elements */
5883
var prevlen = -1; /* last emitted length */
5884
var curlen; /* length of current code */
5885
5886
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
5887
5888
var count = 0; /* repeat count of the current code */
5889
var max_count = 7; /* max repeat count */
5890
var min_count = 4; /* min repeat count */
5891
5892
if (nextlen === 0) {
5893
max_count = 138;
5894
min_count = 3;
5895
}
5896
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
5897
5898
for (n = 0; n <= max_code; n++) {
5899
curlen = nextlen;
5900
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
5901
5902
if (++count < max_count && curlen === nextlen) {
5903
continue;
5904
5905
} else if (count < min_count) {
5906
s.bl_tree[curlen * 2]/*.Freq*/ += count;
5907
5908
} else if (curlen !== 0) {
5909
5910
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
5911
s.bl_tree[REP_3_6*2]/*.Freq*/++;
5912
5913
} else if (count <= 10) {
5914
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
5915
5916
} else {
5917
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
5918
}
5919
5920
count = 0;
5921
prevlen = curlen;
5922
5923
if (nextlen === 0) {
5924
max_count = 138;
5925
min_count = 3;
5926
5927
} else if (curlen === nextlen) {
5928
max_count = 6;
5929
min_count = 3;
5930
5931
} else {
5932
max_count = 7;
5933
min_count = 4;
5934
}
5935
}
5936
}
5937
5938
5939
/* ===========================================================================
5940
* Send a literal or distance tree in compressed form, using the codes in
5941
* bl_tree.
5942
*/
5943
function send_tree(s, tree, max_code)
5944
// deflate_state *s;
5945
// ct_data *tree; /* the tree to be scanned */
5946
// int max_code; /* and its largest code of non zero frequency */
5947
{
5948
var n; /* iterates over all tree elements */
5949
var prevlen = -1; /* last emitted length */
5950
var curlen; /* length of current code */
5951
5952
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
5953
5954
var count = 0; /* repeat count of the current code */
5955
var max_count = 7; /* max repeat count */
5956
var min_count = 4; /* min repeat count */
5957
5958
/* tree[max_code+1].Len = -1; */ /* guard already set */
5959
if (nextlen === 0) {
5960
max_count = 138;
5961
min_count = 3;
5962
}
5963
5964
for (n = 0; n <= max_code; n++) {
5965
curlen = nextlen;
5966
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
5967
5968
if (++count < max_count && curlen === nextlen) {
5969
continue;
5970
5971
} else if (count < min_count) {
5972
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
5973
5974
} else if (curlen !== 0) {
5975
if (curlen !== prevlen) {
5976
send_code(s, curlen, s.bl_tree);
5977
count--;
5978
}
5979
//Assert(count >= 3 && count <= 6, " 3_6?");
5980
send_code(s, REP_3_6, s.bl_tree);
5981
send_bits(s, count-3, 2);
5982
5983
} else if (count <= 10) {
5984
send_code(s, REPZ_3_10, s.bl_tree);
5985
send_bits(s, count-3, 3);
5986
5987
} else {
5988
send_code(s, REPZ_11_138, s.bl_tree);
5989
send_bits(s, count-11, 7);
5990
}
5991
5992
count = 0;
5993
prevlen = curlen;
5994
if (nextlen === 0) {
5995
max_count = 138;
5996
min_count = 3;
5997
5998
} else if (curlen === nextlen) {
5999
max_count = 6;
6000
min_count = 3;
6001
6002
} else {
6003
max_count = 7;
6004
min_count = 4;
6005
}
6006
}
6007
}
6008
6009
6010
/* ===========================================================================
6011
* Construct the Huffman tree for the bit lengths and return the index in
6012
* bl_order of the last bit length code to send.
6013
*/
6014
function build_bl_tree(s) {
6015
var max_blindex; /* index of last bit length code of non zero freq */
6016
6017
/* Determine the bit length frequencies for literal and distance trees */
6018
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
6019
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
6020
6021
/* Build the bit length tree: */
6022
build_tree(s, s.bl_desc);
6023
/* opt_len now includes the length of the tree representations, except
6024
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
6025
*/
6026
6027
/* Determine the number of bit length codes to send. The pkzip format
6028
* requires that at least 4 bit length codes be sent. (appnote.txt says
6029
* 3 but the actual value used is 4.)
6030
*/
6031
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
6032
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
6033
break;
6034
}
6035
}
6036
/* Update opt_len to include the bit length tree and counts */
6037
s.opt_len += 3*(max_blindex+1) + 5+5+4;
6038
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
6039
// s->opt_len, s->static_len));
6040
6041
return max_blindex;
6042
}
6043
6044
6045
/* ===========================================================================
6046
* Send the header for a block using dynamic Huffman trees: the counts, the
6047
* lengths of the bit length codes, the literal tree and the distance tree.
6048
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
6049
*/
6050
function send_all_trees(s, lcodes, dcodes, blcodes)
6051
// deflate_state *s;
6052
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
6053
{
6054
var rank; /* index in bl_order */
6055
6056
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
6057
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
6058
// "too many codes");
6059
//Tracev((stderr, "\nbl counts: "));
6060
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
6061
send_bits(s, dcodes-1, 5);
6062
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
6063
for (rank = 0; rank < blcodes; rank++) {
6064
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
6065
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
6066
}
6067
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
6068
6069
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
6070
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
6071
6072
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
6073
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
6074
}
6075
6076
6077
/* ===========================================================================
6078
* Check if the data type is TEXT or BINARY, using the following algorithm:
6079
* - TEXT if the two conditions below are satisfied:
6080
* a) There are no non-portable control characters belonging to the
6081
* "black list" (0..6, 14..25, 28..31).
6082
* b) There is at least one printable character belonging to the
6083
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
6084
* - BINARY otherwise.
6085
* - The following partially-portable control characters form a
6086
* "gray list" that is ignored in this detection algorithm:
6087
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
6088
* IN assertion: the fields Freq of dyn_ltree are set.
6089
*/
6090
function detect_data_type(s) {
6091
/* black_mask is the bit mask of black-listed bytes
6092
* set bits 0..6, 14..25, and 28..31
6093
* 0xf3ffc07f = binary 11110011111111111100000001111111
6094
*/
6095
var black_mask = 0xf3ffc07f;
6096
var n;
6097
6098
/* Check for non-textual ("black-listed") bytes. */
6099
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
6100
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
6101
return Z_BINARY;
6102
}
6103
}
6104
6105
/* Check for textual ("white-listed") bytes. */
6106
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
6107
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
6108
return Z_TEXT;
6109
}
6110
for (n = 32; n < LITERALS; n++) {
6111
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
6112
return Z_TEXT;
6113
}
6114
}
6115
6116
/* There are no "black-listed" or "white-listed" bytes:
6117
* this stream either is empty or has tolerated ("gray-listed") bytes only.
6118
*/
6119
return Z_BINARY;
6120
}
6121
6122
6123
var static_init_done = false;
6124
6125
/* ===========================================================================
6126
* Initialize the tree data structures for a new zlib stream.
6127
*/
6128
function _tr_init(s)
6129
{
6130
6131
if (!static_init_done) {
6132
tr_static_init();
6133
static_init_done = true;
6134
}
6135
6136
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
6137
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
6138
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
6139
6140
s.bi_buf = 0;
6141
s.bi_valid = 0;
6142
6143
/* Initialize the first block of the first file: */
6144
init_block(s);
6145
}
6146
6147
6148
/* ===========================================================================
6149
* Send a stored block
6150
*/
6151
function _tr_stored_block(s, buf, stored_len, last)
6152
//DeflateState *s;
6153
//charf *buf; /* input block */
6154
//ulg stored_len; /* length of input block */
6155
//int last; /* one if this is the last block for a file */
6156
{
6157
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
6158
copy_block(s, buf, stored_len, true); /* with header */
6159
}
6160
6161
6162
/* ===========================================================================
6163
* Send one empty static block to give enough lookahead for inflate.
6164
* This takes 10 bits, of which 7 may remain in the bit buffer.
6165
*/
6166
function _tr_align(s) {
6167
send_bits(s, STATIC_TREES<<1, 3);
6168
send_code(s, END_BLOCK, static_ltree);
6169
bi_flush(s);
6170
}
6171
6172
6173
/* ===========================================================================
6174
* Determine the best encoding for the current block: dynamic trees, static
6175
* trees or store, and output the encoded block to the zip file.
6176
*/
6177
function _tr_flush_block(s, buf, stored_len, last)
6178
//DeflateState *s;
6179
//charf *buf; /* input block, or NULL if too old */
6180
//ulg stored_len; /* length of input block */
6181
//int last; /* one if this is the last block for a file */
6182
{
6183
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
6184
var max_blindex = 0; /* index of last bit length code of non zero freq */
6185
6186
/* Build the Huffman trees unless a stored block is forced */
6187
if (s.level > 0) {
6188
6189
/* Check if the file is binary or text */
6190
if (s.strm.data_type === Z_UNKNOWN) {
6191
s.strm.data_type = detect_data_type(s);
6192
}
6193
6194
/* Construct the literal and distance trees */
6195
build_tree(s, s.l_desc);
6196
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
6197
// s->static_len));
6198
6199
build_tree(s, s.d_desc);
6200
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
6201
// s->static_len));
6202
/* At this point, opt_len and static_len are the total bit lengths of
6203
* the compressed block data, excluding the tree representations.
6204
*/
6205
6206
/* Build the bit length tree for the above two trees, and get the index
6207
* in bl_order of the last bit length code to send.
6208
*/
6209
max_blindex = build_bl_tree(s);
6210
6211
/* Determine the best encoding. Compute the block lengths in bytes. */
6212
opt_lenb = (s.opt_len+3+7) >>> 3;
6213
static_lenb = (s.static_len+3+7) >>> 3;
6214
6215
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
6216
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
6217
// s->last_lit));
6218
6219
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
6220
6221
} else {
6222
// Assert(buf != (char*)0, "lost buf");
6223
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
6224
}
6225
6226
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
6227
/* 4: two words for the lengths */
6228
6229
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
6230
* Otherwise we can't have processed more than WSIZE input bytes since
6231
* the last block flush, because compression would have been
6232
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
6233
* transform a block into a stored block.
6234
*/
6235
_tr_stored_block(s, buf, stored_len, last);
6236
6237
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
6238
6239
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
6240
compress_block(s, static_ltree, static_dtree);
6241
6242
} else {
6243
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
6244
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
6245
compress_block(s, s.dyn_ltree, s.dyn_dtree);
6246
}
6247
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
6248
/* The above check is made mod 2^32, for files larger than 512 MB
6249
* and uLong implemented on 32 bits.
6250
*/
6251
init_block(s);
6252
6253
if (last) {
6254
bi_windup(s);
6255
}
6256
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
6257
// s->compressed_len-7*last));
6258
}
6259
6260
/* ===========================================================================
6261
* Save the match info and tally the frequency counts. Return true if
6262
* the current block must be flushed.
6263
*/
6264
function _tr_tally(s, dist, lc)
6265
// deflate_state *s;
6266
// unsigned dist; /* distance of matched string */
6267
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
6268
{
6269
//var out_length, in_length, dcode;
6270
6271
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
6272
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
6273
6274
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
6275
s.last_lit++;
6276
6277
if (dist === 0) {
6278
/* lc is the unmatched char */
6279
s.dyn_ltree[lc*2]/*.Freq*/++;
6280
} else {
6281
s.matches++;
6282
/* Here, lc is the match length - MIN_MATCH */
6283
dist--; /* dist = match distance - 1 */
6284
//Assert((ush)dist < (ush)MAX_DIST(s) &&
6285
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
6286
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
6287
6288
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
6289
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
6290
}
6291
6292
// (!) This block is disabled in zlib defailts,
6293
// don't enable it for binary compatibility
6294
6295
//#ifdef TRUNCATE_BLOCK
6296
// /* Try to guess if it is profitable to stop the current block here */
6297
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
6298
// /* Compute an upper bound for the compressed length */
6299
// out_length = s.last_lit*8;
6300
// in_length = s.strstart - s.block_start;
6301
//
6302
// for (dcode = 0; dcode < D_CODES; dcode++) {
6303
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
6304
// }
6305
// out_length >>>= 3;
6306
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
6307
// // s->last_lit, in_length, out_length,
6308
// // 100L - out_length*100L/in_length));
6309
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
6310
// return true;
6311
// }
6312
// }
6313
//#endif
6314
6315
return (s.last_lit === s.lit_bufsize-1);
6316
/* We avoid equality with lit_bufsize because of wraparound at 64K
6317
* on 16 bit machines and because stored blocks are restricted to
6318
* 64K-1 bytes.
6319
*/
6320
}
6321
6322
exports._tr_init = _tr_init;
6323
exports._tr_stored_block = _tr_stored_block;
6324
exports._tr_flush_block = _tr_flush_block;
6325
exports._tr_tally = _tr_tally;
6326
exports._tr_align = _tr_align;
6327
},{"../utils/common":3}],15:[function(require,module,exports){
6328
'use strict';
6329
6330
6331
function ZStream() {
6332
/* next input byte */
6333
this.input = null; // JS specific, because we have no pointers
6334
this.next_in = 0;
6335
/* number of bytes available at input */
6336
this.avail_in = 0;
6337
/* total number of input bytes read so far */
6338
this.total_in = 0;
6339
/* next output byte should be put there */
6340
this.output = null; // JS specific, because we have no pointers
6341
this.next_out = 0;
6342
/* remaining free space at output */
6343
this.avail_out = 0;
6344
/* total number of bytes output so far */
6345
this.total_out = 0;
6346
/* last error message, NULL if no error */
6347
this.msg = ''/*Z_NULL*/;
6348
/* not visible by applications */
6349
this.state = null;
6350
/* best guess about the data type: binary or text */
6351
this.data_type = 2/*Z_UNKNOWN*/;
6352
/* adler32 value of the uncompressed data */
6353
this.adler = 0;
6354
}
6355
6356
module.exports = ZStream;
6357
},{}],"/":[function(require,module,exports){
6358
// Top level file is just a mixin of submodules & constants
6359
'use strict';
6360
6361
var assign = require('./lib/utils/common').assign;
6362
6363
var deflate = require('./lib/deflate');
6364
var inflate = require('./lib/inflate');
6365
var constants = require('./lib/zlib/constants');
6366
6367
var pako = {};
6368
6369
assign(pako, deflate, inflate, constants);
6370
6371
module.exports = pako;
6372
},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")
6373
});
6374