Projekt

Obecné

Profil

Stáhnout (216 KB) Statistiky
| Větev: | Revize:
1
/* pako 1.0.11 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(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
'use strict';
3

    
4

    
5
var zlib_deflate = require('./zlib/deflate');
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
var Z_SYNC_FLUSH    = 2;
22

    
23
var Z_DEFAULT_COMPRESSION = -1;
24

    
25
var Z_DEFAULT_STRATEGY    = 0;
26

    
27
var Z_DEFLATED  = 8;
28

    
29
/* ===========================================================================*/
30

    
31

    
32
/**
33
 * class Deflate
34
 *
35
 * Generic JS-style wrapper for zlib calls. If you don't need
36
 * streaming behaviour - use more simple functions: [[deflate]],
37
 * [[deflateRaw]] and [[gzip]].
38
 **/
39

    
40
/* internal
41
 * Deflate.chunks -> Array
42
 *
43
 * Chunks of output data, if [[Deflate#onData]] not overridden.
44
 **/
45

    
46
/**
47
 * Deflate.result -> Uint8Array|Array
48
 *
49
 * Compressed result, generated by default [[Deflate#onData]]
50
 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
51
 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
52
 * push a chunk with explicit flush (call [[Deflate#push]] with
53
 * `Z_SYNC_FLUSH` param).
54
 **/
55

    
56
/**
57
 * Deflate.err -> Number
58
 *
59
 * Error code after deflate finished. 0 (Z_OK) on success.
60
 * You will not need it in real life, because deflate errors
61
 * are possible only on wrong options or bad `onData` / `onEnd`
62
 * custom handlers.
63
 **/
64

    
65
/**
66
 * Deflate.msg -> String
67
 *
68
 * Error message, if [[Deflate.err]] != 0
69
 **/
70

    
71

    
72
/**
73
 * new Deflate(options)
74
 * - options (Object): zlib deflate options.
75
 *
76
 * Creates new deflator instance with specified params. Throws exception
77
 * on bad params. Supported options:
78
 *
79
 * - `level`
80
 * - `windowBits`
81
 * - `memLevel`
82
 * - `strategy`
83
 * - `dictionary`
84
 *
85
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
86
 * for more information on these.
87
 *
88
 * Additional options, for internal needs:
89
 *
90
 * - `chunkSize` - size of generated data chunks (16K by default)
91
 * - `raw` (Boolean) - do raw deflate
92
 * - `gzip` (Boolean) - create gzip wrapper
93
 * - `to` (String) - if equal to 'string', then result will be "binary string"
94
 *    (each char code [0..255])
95
 * - `header` (Object) - custom header for gzip
96
 *   - `text` (Boolean) - true if compressed data believed to be text
97
 *   - `time` (Number) - modification time, unix timestamp
98
 *   - `os` (Number) - operation system code
99
 *   - `extra` (Array) - array of bytes with extra data (max 65536)
100
 *   - `name` (String) - file name (binary string)
101
 *   - `comment` (String) - comment (binary string)
102
 *   - `hcrc` (Boolean) - true if header crc should be added
103
 *
104
 * ##### Example:
105
 *
106
 * ```javascript
107
 * var pako = require('pako')
108
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
109
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
110
 *
111
 * var deflate = new pako.Deflate({ level: 3});
112
 *
113
 * deflate.push(chunk1, false);
114
 * deflate.push(chunk2, true);  // true -> last chunk
115
 *
116
 * if (deflate.err) { throw new Error(deflate.err); }
117
 *
118
 * console.log(deflate.result);
119
 * ```
120
 **/
121
function Deflate(options) {
122
  if (!(this instanceof Deflate)) return new Deflate(options);
123

    
124
  this.options = utils.assign({
125
    level: Z_DEFAULT_COMPRESSION,
126
    method: Z_DEFLATED,
127
    chunkSize: 16384,
128
    windowBits: 15,
129
    memLevel: 8,
130
    strategy: Z_DEFAULT_STRATEGY,
131
    to: ''
132
  }, options || {});
133

    
134
  var opt = this.options;
135

    
136
  if (opt.raw && (opt.windowBits > 0)) {
137
    opt.windowBits = -opt.windowBits;
138
  }
139

    
140
  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
141
    opt.windowBits += 16;
142
  }
143

    
144
  this.err    = 0;      // error code, if happens (0 = Z_OK)
145
  this.msg    = '';     // error message
146
  this.ended  = false;  // used to avoid multiple onEnd() calls
147
  this.chunks = [];     // chunks of compressed data
148

    
149
  this.strm = new ZStream();
150
  this.strm.avail_out = 0;
151

    
152
  var status = zlib_deflate.deflateInit2(
153
    this.strm,
154
    opt.level,
155
    opt.method,
156
    opt.windowBits,
157
    opt.memLevel,
158
    opt.strategy
159
  );
160

    
161
  if (status !== Z_OK) {
162
    throw new Error(msg[status]);
163
  }
164

    
165
  if (opt.header) {
166
    zlib_deflate.deflateSetHeader(this.strm, opt.header);
167
  }
168

    
169
  if (opt.dictionary) {
170
    var dict;
171
    // Convert data if needed
172
    if (typeof opt.dictionary === 'string') {
173
      // If we need to compress text, change encoding to utf8.
174
      dict = strings.string2buf(opt.dictionary);
175
    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
176
      dict = new Uint8Array(opt.dictionary);
177
    } else {
178
      dict = opt.dictionary;
179
    }
180

    
181
    status = zlib_deflate.deflateSetDictionary(this.strm, dict);
182

    
183
    if (status !== Z_OK) {
184
      throw new Error(msg[status]);
185
    }
186

    
187
    this._dict_set = true;
188
  }
189
}
190

    
191
/**
192
 * Deflate#push(data[, mode]) -> Boolean
193
 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
194
 *   converted to utf8 byte sequence.
195
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
196
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
197
 *
198
 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
199
 * new compressed chunks. Returns `true` on success. The last data block must have
200
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
201
 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
202
 * can use mode Z_SYNC_FLUSH, keeping the compression context.
203
 *
204
 * On fail call [[Deflate#onEnd]] with error code and return false.
205
 *
206
 * We strongly recommend to use `Uint8Array` on input for best speed (output
207
 * array format is detected automatically). Also, don't skip last param and always
208
 * use the same type in your code (boolean or number). That will improve JS speed.
209
 *
210
 * For regular `Array`-s make sure all elements are [0..255].
211
 *
212
 * ##### Example
213
 *
214
 * ```javascript
215
 * push(chunk, false); // push one of data chunks
216
 * ...
217
 * push(chunk, true);  // push last chunk
218
 * ```
219
 **/
220
Deflate.prototype.push = function (data, mode) {
221
  var strm = this.strm;
222
  var chunkSize = this.options.chunkSize;
223
  var status, _mode;
224

    
225
  if (this.ended) { return false; }
226

    
227
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
228

    
229
  // Convert data if needed
230
  if (typeof data === 'string') {
231
    // If we need to compress text, change encoding to utf8.
232
    strm.input = strings.string2buf(data);
233
  } else if (toString.call(data) === '[object ArrayBuffer]') {
234
    strm.input = new Uint8Array(data);
235
  } else {
236
    strm.input = data;
237
  }
238

    
239
  strm.next_in = 0;
240
  strm.avail_in = strm.input.length;
241

    
242
  do {
243
    if (strm.avail_out === 0) {
244
      strm.output = new utils.Buf8(chunkSize);
245
      strm.next_out = 0;
246
      strm.avail_out = chunkSize;
247
    }
248
    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
249

    
250
    if (status !== Z_STREAM_END && status !== Z_OK) {
251
      this.onEnd(status);
252
      this.ended = true;
253
      return false;
254
    }
255
    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
256
      if (this.options.to === 'string') {
257
        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
258
      } else {
259
        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
260
      }
261
    }
262
  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
263

    
264
  // Finalize on the last chunk.
265
  if (_mode === Z_FINISH) {
266
    status = zlib_deflate.deflateEnd(this.strm);
267
    this.onEnd(status);
268
    this.ended = true;
269
    return status === Z_OK;
270
  }
271

    
272
  // callback interim results if Z_SYNC_FLUSH.
273
  if (_mode === Z_SYNC_FLUSH) {
274
    this.onEnd(Z_OK);
275
    strm.avail_out = 0;
276
    return true;
277
  }
278

    
279
  return true;
280
};
281

    
282

    
283
/**
284
 * Deflate#onData(chunk) -> Void
285
 * - chunk (Uint8Array|Array|String): output data. Type of array depends
286
 *   on js engine support. When string output requested, each chunk
287
 *   will be string.
288
 *
289
 * By default, stores data blocks in `chunks[]` property and glue
290
 * those in `onEnd`. Override this handler, if you need another behaviour.
291
 **/
292
Deflate.prototype.onData = function (chunk) {
293
  this.chunks.push(chunk);
294
};
295

    
296

    
297
/**
298
 * Deflate#onEnd(status) -> Void
299
 * - status (Number): deflate status. 0 (Z_OK) on success,
300
 *   other if not.
301
 *
302
 * Called once after you tell deflate that the input stream is
303
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
304
 * or if an error happened. By default - join collected chunks,
305
 * free memory and fill `results` / `err` properties.
306
 **/
307
Deflate.prototype.onEnd = function (status) {
308
  // On success - join
309
  if (status === Z_OK) {
310
    if (this.options.to === 'string') {
311
      this.result = this.chunks.join('');
312
    } else {
313
      this.result = utils.flattenChunks(this.chunks);
314
    }
315
  }
316
  this.chunks = [];
317
  this.err = status;
318
  this.msg = this.strm.msg;
319
};
320

    
321

    
322
/**
323
 * deflate(data[, options]) -> Uint8Array|Array|String
324
 * - data (Uint8Array|Array|String): input data to compress.
325
 * - options (Object): zlib deflate options.
326
 *
327
 * Compress `data` with deflate algorithm and `options`.
328
 *
329
 * Supported options are:
330
 *
331
 * - level
332
 * - windowBits
333
 * - memLevel
334
 * - strategy
335
 * - dictionary
336
 *
337
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
338
 * for more information on these.
339
 *
340
 * Sugar (options):
341
 *
342
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
343
 *   negative windowBits implicitly.
344
 * - `to` (String) - if equal to 'string', then result will be "binary string"
345
 *    (each char code [0..255])
346
 *
347
 * ##### Example:
348
 *
349
 * ```javascript
350
 * var pako = require('pako')
351
 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
352
 *
353
 * console.log(pako.deflate(data));
354
 * ```
355
 **/
356
function deflate(input, options) {
357
  var deflator = new Deflate(options);
358

    
359
  deflator.push(input, true);
360

    
361
  // That will never happens, if you don't cheat with options :)
362
  if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
363

    
364
  return deflator.result;
365
}
366

    
367

    
368
/**
369
 * deflateRaw(data[, options]) -> Uint8Array|Array|String
370
 * - data (Uint8Array|Array|String): input data to compress.
371
 * - options (Object): zlib deflate options.
372
 *
373
 * The same as [[deflate]], but creates raw data, without wrapper
374
 * (header and adler32 crc).
375
 **/
376
function deflateRaw(input, options) {
377
  options = options || {};
378
  options.raw = true;
379
  return deflate(input, options);
380
}
381

    
382

    
383
/**
384
 * gzip(data[, options]) -> Uint8Array|Array|String
385
 * - data (Uint8Array|Array|String): input data to compress.
386
 * - options (Object): zlib deflate options.
387
 *
388
 * The same as [[deflate]], but create gzip wrapper instead of
389
 * deflate one.
390
 **/
391
function gzip(input, options) {
392
  options = options || {};
393
  options.gzip = true;
394
  return deflate(input, options);
395
}
396

    
397

    
398
exports.Deflate = Deflate;
399
exports.deflate = deflate;
400
exports.deflateRaw = deflateRaw;
401
exports.gzip = gzip;
402

    
403
},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(require,module,exports){
404
'use strict';
405

    
406

    
407
var zlib_inflate = require('./zlib/inflate');
408
var utils        = require('./utils/common');
409
var strings      = require('./utils/strings');
410
var c            = require('./zlib/constants');
411
var msg          = require('./zlib/messages');
412
var ZStream      = require('./zlib/zstream');
413
var GZheader     = require('./zlib/gzheader');
414

    
415
var toString = Object.prototype.toString;
416

    
417
/**
418
 * class Inflate
419
 *
420
 * Generic JS-style wrapper for zlib calls. If you don't need
421
 * streaming behaviour - use more simple functions: [[inflate]]
422
 * and [[inflateRaw]].
423
 **/
424

    
425
/* internal
426
 * inflate.chunks -> Array
427
 *
428
 * Chunks of output data, if [[Inflate#onData]] not overridden.
429
 **/
430

    
431
/**
432
 * Inflate.result -> Uint8Array|Array|String
433
 *
434
 * Uncompressed result, generated by default [[Inflate#onData]]
435
 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
436
 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
437
 * push a chunk with explicit flush (call [[Inflate#push]] with
438
 * `Z_SYNC_FLUSH` param).
439
 **/
440

    
441
/**
442
 * Inflate.err -> Number
443
 *
444
 * Error code after inflate finished. 0 (Z_OK) on success.
445
 * Should be checked if broken data possible.
446
 **/
447

    
448
/**
449
 * Inflate.msg -> String
450
 *
451
 * Error message, if [[Inflate.err]] != 0
452
 **/
453

    
454

    
455
/**
456
 * new Inflate(options)
457
 * - options (Object): zlib inflate options.
458
 *
459
 * Creates new inflator instance with specified params. Throws exception
460
 * on bad params. Supported options:
461
 *
462
 * - `windowBits`
463
 * - `dictionary`
464
 *
465
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
466
 * for more information on these.
467
 *
468
 * Additional options, for internal needs:
469
 *
470
 * - `chunkSize` - size of generated data chunks (16K by default)
471
 * - `raw` (Boolean) - do raw inflate
472
 * - `to` (String) - if equal to 'string', then result will be converted
473
 *   from utf8 to utf16 (javascript) string. When string output requested,
474
 *   chunk length can differ from `chunkSize`, depending on content.
475
 *
476
 * By default, when no options set, autodetect deflate/gzip data format via
477
 * wrapper header.
478
 *
479
 * ##### Example:
480
 *
481
 * ```javascript
482
 * var pako = require('pako')
483
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
484
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
485
 *
486
 * var inflate = new pako.Inflate({ level: 3});
487
 *
488
 * inflate.push(chunk1, false);
489
 * inflate.push(chunk2, true);  // true -> last chunk
490
 *
491
 * if (inflate.err) { throw new Error(inflate.err); }
492
 *
493
 * console.log(inflate.result);
494
 * ```
495
 **/
496
function Inflate(options) {
497
  if (!(this instanceof Inflate)) return new Inflate(options);
498

    
499
  this.options = utils.assign({
500
    chunkSize: 16384,
501
    windowBits: 0,
502
    to: ''
503
  }, options || {});
504

    
505
  var opt = this.options;
506

    
507
  // Force window size for `raw` data, if not set directly,
508
  // because we have no header for autodetect.
509
  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
510
    opt.windowBits = -opt.windowBits;
511
    if (opt.windowBits === 0) { opt.windowBits = -15; }
512
  }
513

    
514
  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
515
  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
516
      !(options && options.windowBits)) {
517
    opt.windowBits += 32;
518
  }
519

    
520
  // Gzip header has no info about windows size, we can do autodetect only
521
  // for deflate. So, if window size not set, force it to max when gzip possible
522
  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
523
    // bit 3 (16) -> gzipped data
524
    // bit 4 (32) -> autodetect gzip/deflate
525
    if ((opt.windowBits & 15) === 0) {
526
      opt.windowBits |= 15;
527
    }
528
  }
529

    
530
  this.err    = 0;      // error code, if happens (0 = Z_OK)
531
  this.msg    = '';     // error message
532
  this.ended  = false;  // used to avoid multiple onEnd() calls
533
  this.chunks = [];     // chunks of compressed data
534

    
535
  this.strm   = new ZStream();
536
  this.strm.avail_out = 0;
537

    
538
  var status  = zlib_inflate.inflateInit2(
539
    this.strm,
540
    opt.windowBits
541
  );
542

    
543
  if (status !== c.Z_OK) {
544
    throw new Error(msg[status]);
545
  }
546

    
547
  this.header = new GZheader();
548

    
549
  zlib_inflate.inflateGetHeader(this.strm, this.header);
550

    
551
  // Setup dictionary
552
  if (opt.dictionary) {
553
    // Convert data if needed
554
    if (typeof opt.dictionary === 'string') {
555
      opt.dictionary = strings.string2buf(opt.dictionary);
556
    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
557
      opt.dictionary = new Uint8Array(opt.dictionary);
558
    }
559
    if (opt.raw) { //In raw mode we need to set the dictionary early
560
      status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
561
      if (status !== c.Z_OK) {
562
        throw new Error(msg[status]);
563
      }
564
    }
565
  }
566
}
567

    
568
/**
569
 * Inflate#push(data[, mode]) -> Boolean
570
 * - data (Uint8Array|Array|ArrayBuffer|String): input data
571
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
572
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
573
 *
574
 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
575
 * new output chunks. Returns `true` on success. The last data block must have
576
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
577
 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
578
 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
579
 *
580
 * On fail call [[Inflate#onEnd]] with error code and return false.
581
 *
582
 * We strongly recommend to use `Uint8Array` on input for best speed (output
583
 * format is detected automatically). Also, don't skip last param and always
584
 * use the same type in your code (boolean or number). That will improve JS speed.
585
 *
586
 * For regular `Array`-s make sure all elements are [0..255].
587
 *
588
 * ##### Example
589
 *
590
 * ```javascript
591
 * push(chunk, false); // push one of data chunks
592
 * ...
593
 * push(chunk, true);  // push last chunk
594
 * ```
595
 **/
596
Inflate.prototype.push = function (data, mode) {
597
  var strm = this.strm;
598
  var chunkSize = this.options.chunkSize;
599
  var dictionary = this.options.dictionary;
600
  var status, _mode;
601
  var next_out_utf8, tail, utf8str;
602

    
603
  // Flag to properly process Z_BUF_ERROR on testing inflate call
604
  // when we check that all output data was flushed.
605
  var allowBufError = false;
606

    
607
  if (this.ended) { return false; }
608
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
609

    
610
  // Convert data if needed
611
  if (typeof data === 'string') {
612
    // Only binary strings can be decompressed on practice
613
    strm.input = strings.binstring2buf(data);
614
  } else if (toString.call(data) === '[object ArrayBuffer]') {
615
    strm.input = new Uint8Array(data);
616
  } else {
617
    strm.input = data;
618
  }
619

    
620
  strm.next_in = 0;
621
  strm.avail_in = strm.input.length;
622

    
623
  do {
624
    if (strm.avail_out === 0) {
625
      strm.output = new utils.Buf8(chunkSize);
626
      strm.next_out = 0;
627
      strm.avail_out = chunkSize;
628
    }
629

    
630
    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
631

    
632
    if (status === c.Z_NEED_DICT && dictionary) {
633
      status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
634
    }
635

    
636
    if (status === c.Z_BUF_ERROR && allowBufError === true) {
637
      status = c.Z_OK;
638
      allowBufError = false;
639
    }
640

    
641
    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
642
      this.onEnd(status);
643
      this.ended = true;
644
      return false;
645
    }
646

    
647
    if (strm.next_out) {
648
      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
649

    
650
        if (this.options.to === 'string') {
651

    
652
          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
653

    
654
          tail = strm.next_out - next_out_utf8;
655
          utf8str = strings.buf2string(strm.output, next_out_utf8);
656

    
657
          // move tail
658
          strm.next_out = tail;
659
          strm.avail_out = chunkSize - tail;
660
          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
661

    
662
          this.onData(utf8str);
663

    
664
        } else {
665
          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
666
        }
667
      }
668
    }
669

    
670
    // When no more input data, we should check that internal inflate buffers
671
    // are flushed. The only way to do it when avail_out = 0 - run one more
672
    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
673
    // Here we set flag to process this error properly.
674
    //
675
    // NOTE. Deflate does not return error in this case and does not needs such
676
    // logic.
677
    if (strm.avail_in === 0 && strm.avail_out === 0) {
678
      allowBufError = true;
679
    }
680

    
681
  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
682

    
683
  if (status === c.Z_STREAM_END) {
684
    _mode = c.Z_FINISH;
685
  }
686

    
687
  // Finalize on the last chunk.
688
  if (_mode === c.Z_FINISH) {
689
    status = zlib_inflate.inflateEnd(this.strm);
690
    this.onEnd(status);
691
    this.ended = true;
692
    return status === c.Z_OK;
693
  }
694

    
695
  // callback interim results if Z_SYNC_FLUSH.
696
  if (_mode === c.Z_SYNC_FLUSH) {
697
    this.onEnd(c.Z_OK);
698
    strm.avail_out = 0;
699
    return true;
700
  }
701

    
702
  return true;
703
};
704

    
705

    
706
/**
707
 * Inflate#onData(chunk) -> Void
708
 * - chunk (Uint8Array|Array|String): output data. Type of array depends
709
 *   on js engine support. When string output requested, each chunk
710
 *   will be string.
711
 *
712
 * By default, stores data blocks in `chunks[]` property and glue
713
 * those in `onEnd`. Override this handler, if you need another behaviour.
714
 **/
715
Inflate.prototype.onData = function (chunk) {
716
  this.chunks.push(chunk);
717
};
718

    
719

    
720
/**
721
 * Inflate#onEnd(status) -> Void
722
 * - status (Number): inflate status. 0 (Z_OK) on success,
723
 *   other if not.
724
 *
725
 * Called either after you tell inflate that the input stream is
726
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
727
 * or if an error happened. By default - join collected chunks,
728
 * free memory and fill `results` / `err` properties.
729
 **/
730
Inflate.prototype.onEnd = function (status) {
731
  // On success - join
732
  if (status === c.Z_OK) {
733
    if (this.options.to === 'string') {
734
      // Glue & convert here, until we teach pako to send
735
      // utf8 aligned strings to onData
736
      this.result = this.chunks.join('');
737
    } else {
738
      this.result = utils.flattenChunks(this.chunks);
739
    }
740
  }
741
  this.chunks = [];
742
  this.err = status;
743
  this.msg = this.strm.msg;
744
};
745

    
746

    
747
/**
748
 * inflate(data[, options]) -> Uint8Array|Array|String
749
 * - data (Uint8Array|Array|String): input data to decompress.
750
 * - options (Object): zlib inflate options.
751
 *
752
 * Decompress `data` with inflate/ungzip and `options`. Autodetect
753
 * format via wrapper header by default. That's why we don't provide
754
 * separate `ungzip` method.
755
 *
756
 * Supported options are:
757
 *
758
 * - windowBits
759
 *
760
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
761
 * for more information.
762
 *
763
 * Sugar (options):
764
 *
765
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
766
 *   negative windowBits implicitly.
767
 * - `to` (String) - if equal to 'string', then result will be converted
768
 *   from utf8 to utf16 (javascript) string. When string output requested,
769
 *   chunk length can differ from `chunkSize`, depending on content.
770
 *
771
 *
772
 * ##### Example:
773
 *
774
 * ```javascript
775
 * var pako = require('pako')
776
 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
777
 *   , output;
778
 *
779
 * try {
780
 *   output = pako.inflate(input);
781
 * } catch (err)
782
 *   console.log(err);
783
 * }
784
 * ```
785
 **/
786
function inflate(input, options) {
787
  var inflator = new Inflate(options);
788

    
789
  inflator.push(input, true);
790

    
791
  // That will never happens, if you don't cheat with options :)
792
  if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
793

    
794
  return inflator.result;
795
}
796

    
797

    
798
/**
799
 * inflateRaw(data[, options]) -> Uint8Array|Array|String
800
 * - data (Uint8Array|Array|String): input data to decompress.
801
 * - options (Object): zlib inflate options.
802
 *
803
 * The same as [[inflate]], but creates raw data, without wrapper
804
 * (header and adler32 crc).
805
 **/
806
function inflateRaw(input, options) {
807
  options = options || {};
808
  options.raw = true;
809
  return inflate(input, options);
810
}
811

    
812

    
813
/**
814
 * ungzip(data[, options]) -> Uint8Array|Array|String
815
 * - data (Uint8Array|Array|String): input data to decompress.
816
 * - options (Object): zlib inflate options.
817
 *
818
 * Just shortcut to [[inflate]], because it autodetects format
819
 * by header.content. Done for convenience.
820
 **/
821

    
822

    
823
exports.Inflate = Inflate;
824
exports.inflate = inflate;
825
exports.inflateRaw = inflateRaw;
826
exports.ungzip  = inflate;
827

    
828
},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(require,module,exports){
829
'use strict';
830

    
831

    
832
var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
833
                (typeof Uint16Array !== 'undefined') &&
834
                (typeof Int32Array !== 'undefined');
835

    
836
function _has(obj, key) {
837
  return Object.prototype.hasOwnProperty.call(obj, key);
838
}
839

    
840
exports.assign = function (obj /*from1, from2, from3, ...*/) {
841
  var sources = Array.prototype.slice.call(arguments, 1);
842
  while (sources.length) {
843
    var source = sources.shift();
844
    if (!source) { continue; }
845

    
846
    if (typeof source !== 'object') {
847
      throw new TypeError(source + 'must be non-object');
848
    }
849

    
850
    for (var p in source) {
851
      if (_has(source, p)) {
852
        obj[p] = source[p];
853
      }
854
    }
855
  }
856

    
857
  return obj;
858
};
859

    
860

    
861
// reduce buffer size, avoiding mem copy
862
exports.shrinkBuf = function (buf, size) {
863
  if (buf.length === size) { return buf; }
864
  if (buf.subarray) { return buf.subarray(0, size); }
865
  buf.length = size;
866
  return buf;
867
};
868

    
869

    
870
var fnTyped = {
871
  arraySet: function (dest, src, src_offs, len, dest_offs) {
872
    if (src.subarray && dest.subarray) {
873
      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
874
      return;
875
    }
876
    // Fallback to ordinary array
877
    for (var i = 0; i < len; i++) {
878
      dest[dest_offs + i] = src[src_offs + i];
879
    }
880
  },
881
  // Join array of chunks to single array.
882
  flattenChunks: function (chunks) {
883
    var i, l, len, pos, chunk, result;
884

    
885
    // calculate data length
886
    len = 0;
887
    for (i = 0, l = chunks.length; i < l; i++) {
888
      len += chunks[i].length;
889
    }
890

    
891
    // join chunks
892
    result = new Uint8Array(len);
893
    pos = 0;
894
    for (i = 0, l = chunks.length; i < l; i++) {
895
      chunk = chunks[i];
896
      result.set(chunk, pos);
897
      pos += chunk.length;
898
    }
899

    
900
    return result;
901
  }
902
};
903

    
904
var fnUntyped = {
905
  arraySet: function (dest, src, src_offs, len, dest_offs) {
906
    for (var i = 0; i < len; i++) {
907
      dest[dest_offs + i] = src[src_offs + i];
908
    }
909
  },
910
  // Join array of chunks to single array.
911
  flattenChunks: function (chunks) {
912
    return [].concat.apply([], chunks);
913
  }
914
};
915

    
916

    
917
// Enable/Disable typed arrays use, for testing
918
//
919
exports.setTyped = function (on) {
920
  if (on) {
921
    exports.Buf8  = Uint8Array;
922
    exports.Buf16 = Uint16Array;
923
    exports.Buf32 = Int32Array;
924
    exports.assign(exports, fnTyped);
925
  } else {
926
    exports.Buf8  = Array;
927
    exports.Buf16 = Array;
928
    exports.Buf32 = Array;
929
    exports.assign(exports, fnUntyped);
930
  }
931
};
932

    
933
exports.setTyped(TYPED_OK);
934

    
935
},{}],4:[function(require,module,exports){
936
// String encode/decode helpers
937
'use strict';
938

    
939

    
940
var utils = require('./common');
941

    
942

    
943
// Quick check if we can use fast array to bin string conversion
944
//
945
// - apply(Array) can fail on Android 2.2
946
// - apply(Uint8Array) can fail on iOS 5.1 Safari
947
//
948
var STR_APPLY_OK = true;
949
var STR_APPLY_UIA_OK = true;
950

    
951
try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
952
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
953

    
954

    
955
// Table with utf8 lengths (calculated by first byte of sequence)
956
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
957
// because max possible codepoint is 0x10ffff
958
var _utf8len = new utils.Buf8(256);
959
for (var q = 0; q < 256; q++) {
960
  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
961
}
962
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
963

    
964

    
965
// convert string to array (typed, when possible)
966
exports.string2buf = function (str) {
967
  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
968

    
969
  // count binary size
970
  for (m_pos = 0; m_pos < str_len; m_pos++) {
971
    c = str.charCodeAt(m_pos);
972
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
973
      c2 = str.charCodeAt(m_pos + 1);
974
      if ((c2 & 0xfc00) === 0xdc00) {
975
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
976
        m_pos++;
977
      }
978
    }
979
    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
980
  }
981

    
982
  // allocate buffer
983
  buf = new utils.Buf8(buf_len);
984

    
985
  // convert
986
  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
987
    c = str.charCodeAt(m_pos);
988
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
989
      c2 = str.charCodeAt(m_pos + 1);
990
      if ((c2 & 0xfc00) === 0xdc00) {
991
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
992
        m_pos++;
993
      }
994
    }
995
    if (c < 0x80) {
996
      /* one byte */
997
      buf[i++] = c;
998
    } else if (c < 0x800) {
999
      /* two bytes */
1000
      buf[i++] = 0xC0 | (c >>> 6);
1001
      buf[i++] = 0x80 | (c & 0x3f);
1002
    } else if (c < 0x10000) {
1003
      /* three bytes */
1004
      buf[i++] = 0xE0 | (c >>> 12);
1005
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
1006
      buf[i++] = 0x80 | (c & 0x3f);
1007
    } else {
1008
      /* four bytes */
1009
      buf[i++] = 0xf0 | (c >>> 18);
1010
      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
1011
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
1012
      buf[i++] = 0x80 | (c & 0x3f);
1013
    }
1014
  }
1015

    
1016
  return buf;
1017
};
1018

    
1019
// Helper (used in 2 places)
1020
function buf2binstring(buf, len) {
1021
  // On Chrome, the arguments in a function call that are allowed is `65534`.
1022
  // If the length of the buffer is smaller than that, we can use this optimization,
1023
  // otherwise we will take a slower path.
1024
  if (len < 65534) {
1025
    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
1026
      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
1027
    }
1028
  }
1029

    
1030
  var result = '';
1031
  for (var i = 0; i < len; i++) {
1032
    result += String.fromCharCode(buf[i]);
1033
  }
1034
  return result;
1035
}
1036

    
1037

    
1038
// Convert byte array to binary string
1039
exports.buf2binstring = function (buf) {
1040
  return buf2binstring(buf, buf.length);
1041
};
1042

    
1043

    
1044
// Convert binary string (typed, when possible)
1045
exports.binstring2buf = function (str) {
1046
  var buf = new utils.Buf8(str.length);
1047
  for (var i = 0, len = buf.length; i < len; i++) {
1048
    buf[i] = str.charCodeAt(i);
1049
  }
1050
  return buf;
1051
};
1052

    
1053

    
1054
// convert array to string
1055
exports.buf2string = function (buf, max) {
1056
  var i, out, c, c_len;
1057
  var len = max || buf.length;
1058

    
1059
  // Reserve max possible length (2 words per char)
1060
  // NB: by unknown reasons, Array is significantly faster for
1061
  //     String.fromCharCode.apply than Uint16Array.
1062
  var utf16buf = new Array(len * 2);
1063

    
1064
  for (out = 0, i = 0; i < len;) {
1065
    c = buf[i++];
1066
    // quick process ascii
1067
    if (c < 0x80) { utf16buf[out++] = c; continue; }
1068

    
1069
    c_len = _utf8len[c];
1070
    // skip 5 & 6 byte codes
1071
    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
1072

    
1073
    // apply mask on first byte
1074
    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
1075
    // join the rest
1076
    while (c_len > 1 && i < len) {
1077
      c = (c << 6) | (buf[i++] & 0x3f);
1078
      c_len--;
1079
    }
1080

    
1081
    // terminated by end of string?
1082
    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
1083

    
1084
    if (c < 0x10000) {
1085
      utf16buf[out++] = c;
1086
    } else {
1087
      c -= 0x10000;
1088
      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
1089
      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
1090
    }
1091
  }
1092

    
1093
  return buf2binstring(utf16buf, out);
1094
};
1095

    
1096

    
1097
// Calculate max possible position in utf8 buffer,
1098
// that will not break sequence. If that's not possible
1099
// - (very small limits) return max size as is.
1100
//
1101
// buf[] - utf8 bytes array
1102
// max   - length limit (mandatory);
1103
exports.utf8border = function (buf, max) {
1104
  var pos;
1105

    
1106
  max = max || buf.length;
1107
  if (max > buf.length) { max = buf.length; }
1108

    
1109
  // go back from last position, until start of sequence found
1110
  pos = max - 1;
1111
  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
1112

    
1113
  // Very small and broken sequence,
1114
  // return max, because we should return something anyway.
1115
  if (pos < 0) { return max; }
1116

    
1117
  // If we came to start of buffer - that means buffer is too small,
1118
  // return max too.
1119
  if (pos === 0) { return max; }
1120

    
1121
  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
1122
};
1123

    
1124
},{"./common":3}],5:[function(require,module,exports){
1125
'use strict';
1126

    
1127
// Note: adler32 takes 12% for level 0 and 2% for level 6.
1128
// It isn't worth it to make additional optimizations as in original.
1129
// Small size is preferable.
1130

    
1131
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
1132
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
1133
//
1134
// This software is provided 'as-is', without any express or implied
1135
// warranty. In no event will the authors be held liable for any damages
1136
// arising from the use of this software.
1137
//
1138
// Permission is granted to anyone to use this software for any purpose,
1139
// including commercial applications, and to alter it and redistribute it
1140
// freely, subject to the following restrictions:
1141
//
1142
// 1. The origin of this software must not be misrepresented; you must not
1143
//   claim that you wrote the original software. If you use this software
1144
//   in a product, an acknowledgment in the product documentation would be
1145
//   appreciated but is not required.
1146
// 2. Altered source versions must be plainly marked as such, and must not be
1147
//   misrepresented as being the original software.
1148
// 3. This notice may not be removed or altered from any source distribution.
1149

    
1150
function adler32(adler, buf, len, pos) {
1151
  var s1 = (adler & 0xffff) |0,
1152
      s2 = ((adler >>> 16) & 0xffff) |0,
1153
      n = 0;
1154

    
1155
  while (len !== 0) {
1156
    // Set limit ~ twice less than 5552, to keep
1157
    // s2 in 31-bits, because we force signed ints.
1158
    // in other case %= will fail.
1159
    n = len > 2000 ? 2000 : len;
1160
    len -= n;
1161

    
1162
    do {
1163
      s1 = (s1 + buf[pos++]) |0;
1164
      s2 = (s2 + s1) |0;
1165
    } while (--n);
1166

    
1167
    s1 %= 65521;
1168
    s2 %= 65521;
1169
  }
1170

    
1171
  return (s1 | (s2 << 16)) |0;
1172
}
1173

    
1174

    
1175
module.exports = adler32;
1176

    
1177
},{}],6:[function(require,module,exports){
1178
'use strict';
1179

    
1180
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
1181
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
1182
//
1183
// This software is provided 'as-is', without any express or implied
1184
// warranty. In no event will the authors be held liable for any damages
1185
// arising from the use of this software.
1186
//
1187
// Permission is granted to anyone to use this software for any purpose,
1188
// including commercial applications, and to alter it and redistribute it
1189
// freely, subject to the following restrictions:
1190
//
1191
// 1. The origin of this software must not be misrepresented; you must not
1192
//   claim that you wrote the original software. If you use this software
1193
//   in a product, an acknowledgment in the product documentation would be
1194
//   appreciated but is not required.
1195
// 2. Altered source versions must be plainly marked as such, and must not be
1196
//   misrepresented as being the original software.
1197
// 3. This notice may not be removed or altered from any source distribution.
1198

    
1199
module.exports = {
1200

    
1201
  /* Allowed flush values; see deflate() and inflate() below for details */
1202
  Z_NO_FLUSH:         0,
1203
  Z_PARTIAL_FLUSH:    1,
1204
  Z_SYNC_FLUSH:       2,
1205
  Z_FULL_FLUSH:       3,
1206
  Z_FINISH:           4,
1207
  Z_BLOCK:            5,
1208
  Z_TREES:            6,
1209

    
1210
  /* Return codes for the compression/decompression functions. Negative values
1211
  * are errors, positive values are used for special but normal events.
1212
  */
1213
  Z_OK:               0,
1214
  Z_STREAM_END:       1,
1215
  Z_NEED_DICT:        2,
1216
  Z_ERRNO:           -1,
1217
  Z_STREAM_ERROR:    -2,
1218
  Z_DATA_ERROR:      -3,
1219
  //Z_MEM_ERROR:     -4,
1220
  Z_BUF_ERROR:       -5,
1221
  //Z_VERSION_ERROR: -6,
1222

    
1223
  /* compression levels */
1224
  Z_NO_COMPRESSION:         0,
1225
  Z_BEST_SPEED:             1,
1226
  Z_BEST_COMPRESSION:       9,
1227
  Z_DEFAULT_COMPRESSION:   -1,
1228

    
1229

    
1230
  Z_FILTERED:               1,
1231
  Z_HUFFMAN_ONLY:           2,
1232
  Z_RLE:                    3,
1233
  Z_FIXED:                  4,
1234
  Z_DEFAULT_STRATEGY:       0,
1235

    
1236
  /* Possible values of the data_type field (though see inflate()) */
1237
  Z_BINARY:                 0,
1238
  Z_TEXT:                   1,
1239
  //Z_ASCII:                1, // = Z_TEXT (deprecated)
1240
  Z_UNKNOWN:                2,
1241

    
1242
  /* The deflate compression method */
1243
  Z_DEFLATED:               8
1244
  //Z_NULL:                 null // Use -1 or null inline, depending on var type
1245
};
1246

    
1247
},{}],7:[function(require,module,exports){
1248
'use strict';
1249

    
1250
// Note: we can't get significant speed boost here.
1251
// So write code to minimize size - no pregenerated tables
1252
// and array tools dependencies.
1253

    
1254
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
1255
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
1256
//
1257
// This software is provided 'as-is', without any express or implied
1258
// warranty. In no event will the authors be held liable for any damages
1259
// arising from the use of this software.
1260
//
1261
// Permission is granted to anyone to use this software for any purpose,
1262
// including commercial applications, and to alter it and redistribute it
1263
// freely, subject to the following restrictions:
1264
//
1265
// 1. The origin of this software must not be misrepresented; you must not
1266
//   claim that you wrote the original software. If you use this software
1267
//   in a product, an acknowledgment in the product documentation would be
1268
//   appreciated but is not required.
1269
// 2. Altered source versions must be plainly marked as such, and must not be
1270
//   misrepresented as being the original software.
1271
// 3. This notice may not be removed or altered from any source distribution.
1272

    
1273
// Use ordinary array, since untyped makes no boost here
1274
function makeTable() {
1275
  var c, table = [];
1276

    
1277
  for (var n = 0; n < 256; n++) {
1278
    c = n;
1279
    for (var k = 0; k < 8; k++) {
1280
      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
1281
    }
1282
    table[n] = c;
1283
  }
1284

    
1285
  return table;
1286
}
1287

    
1288
// Create table on load. Just 255 signed longs. Not a problem.
1289
var crcTable = makeTable();
1290

    
1291

    
1292
function crc32(crc, buf, len, pos) {
1293
  var t = crcTable,
1294
      end = pos + len;
1295

    
1296
  crc ^= -1;
1297

    
1298
  for (var i = pos; i < end; i++) {
1299
    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
1300
  }
1301

    
1302
  return (crc ^ (-1)); // >>> 0;
1303
}
1304

    
1305

    
1306
module.exports = crc32;
1307

    
1308
},{}],8:[function(require,module,exports){
1309
'use strict';
1310

    
1311
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
1312
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
1313
//
1314
// This software is provided 'as-is', without any express or implied
1315
// warranty. In no event will the authors be held liable for any damages
1316
// arising from the use of this software.
1317
//
1318
// Permission is granted to anyone to use this software for any purpose,
1319
// including commercial applications, and to alter it and redistribute it
1320
// freely, subject to the following restrictions:
1321
//
1322
// 1. The origin of this software must not be misrepresented; you must not
1323
//   claim that you wrote the original software. If you use this software
1324
//   in a product, an acknowledgment in the product documentation would be
1325
//   appreciated but is not required.
1326
// 2. Altered source versions must be plainly marked as such, and must not be
1327
//   misrepresented as being the original software.
1328
// 3. This notice may not be removed or altered from any source distribution.
1329

    
1330
var utils   = require('../utils/common');
1331
var trees   = require('./trees');
1332
var adler32 = require('./adler32');
1333
var crc32   = require('./crc32');
1334
var msg     = require('./messages');
1335

    
1336
/* Public constants ==========================================================*/
1337
/* ===========================================================================*/
1338

    
1339

    
1340
/* Allowed flush values; see deflate() and inflate() below for details */
1341
var Z_NO_FLUSH      = 0;
1342
var Z_PARTIAL_FLUSH = 1;
1343
//var Z_SYNC_FLUSH    = 2;
1344
var Z_FULL_FLUSH    = 3;
1345
var Z_FINISH        = 4;
1346
var Z_BLOCK         = 5;
1347
//var Z_TREES         = 6;
1348

    
1349

    
1350
/* Return codes for the compression/decompression functions. Negative values
1351
 * are errors, positive values are used for special but normal events.
1352
 */
1353
var Z_OK            = 0;
1354
var Z_STREAM_END    = 1;
1355
//var Z_NEED_DICT     = 2;
1356
//var Z_ERRNO         = -1;
1357
var Z_STREAM_ERROR  = -2;
1358
var Z_DATA_ERROR    = -3;
1359
//var Z_MEM_ERROR     = -4;
1360
var Z_BUF_ERROR     = -5;
1361
//var Z_VERSION_ERROR = -6;
1362

    
1363

    
1364
/* compression levels */
1365
//var Z_NO_COMPRESSION      = 0;
1366
//var Z_BEST_SPEED          = 1;
1367
//var Z_BEST_COMPRESSION    = 9;
1368
var Z_DEFAULT_COMPRESSION = -1;
1369

    
1370

    
1371
var Z_FILTERED            = 1;
1372
var Z_HUFFMAN_ONLY        = 2;
1373
var Z_RLE                 = 3;
1374
var Z_FIXED               = 4;
1375
var Z_DEFAULT_STRATEGY    = 0;
1376

    
1377
/* Possible values of the data_type field (though see inflate()) */
1378
//var Z_BINARY              = 0;
1379
//var Z_TEXT                = 1;
1380
//var Z_ASCII               = 1; // = Z_TEXT
1381
var Z_UNKNOWN             = 2;
1382

    
1383

    
1384
/* The deflate compression method */
1385
var Z_DEFLATED  = 8;
1386

    
1387
/*============================================================================*/
1388

    
1389

    
1390
var MAX_MEM_LEVEL = 9;
1391
/* Maximum value for memLevel in deflateInit2 */
1392
var MAX_WBITS = 15;
1393
/* 32K LZ77 window */
1394
var DEF_MEM_LEVEL = 8;
1395

    
1396

    
1397
var LENGTH_CODES  = 29;
1398
/* number of length codes, not counting the special END_BLOCK code */
1399
var LITERALS      = 256;
1400
/* number of literal bytes 0..255 */
1401
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
1402
/* number of Literal or Length codes, including the END_BLOCK code */
1403
var D_CODES       = 30;
1404
/* number of distance codes */
1405
var BL_CODES      = 19;
1406
/* number of codes used to transfer the bit lengths */
1407
var HEAP_SIZE     = 2 * L_CODES + 1;
1408
/* maximum heap size */
1409
var MAX_BITS  = 15;
1410
/* All codes must not exceed MAX_BITS bits */
1411

    
1412
var MIN_MATCH = 3;
1413
var MAX_MATCH = 258;
1414
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
1415

    
1416
var PRESET_DICT = 0x20;
1417

    
1418
var INIT_STATE = 42;
1419
var EXTRA_STATE = 69;
1420
var NAME_STATE = 73;
1421
var COMMENT_STATE = 91;
1422
var HCRC_STATE = 103;
1423
var BUSY_STATE = 113;
1424
var FINISH_STATE = 666;
1425

    
1426
var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
1427
var BS_BLOCK_DONE     = 2; /* block flush performed */
1428
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
1429
var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
1430

    
1431
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
1432

    
1433
function err(strm, errorCode) {
1434
  strm.msg = msg[errorCode];
1435
  return errorCode;
1436
}
1437

    
1438
function rank(f) {
1439
  return ((f) << 1) - ((f) > 4 ? 9 : 0);
1440
}
1441

    
1442
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
1443

    
1444

    
1445
/* =========================================================================
1446
 * Flush as much pending output as possible. All deflate() output goes
1447
 * through this function so some applications may wish to modify it
1448
 * to avoid allocating a large strm->output buffer and copying into it.
1449
 * (See also read_buf()).
1450
 */
1451
function flush_pending(strm) {
1452
  var s = strm.state;
1453

    
1454
  //_tr_flush_bits(s);
1455
  var len = s.pending;
1456
  if (len > strm.avail_out) {
1457
    len = strm.avail_out;
1458
  }
1459
  if (len === 0) { return; }
1460

    
1461
  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
1462
  strm.next_out += len;
1463
  s.pending_out += len;
1464
  strm.total_out += len;
1465
  strm.avail_out -= len;
1466
  s.pending -= len;
1467
  if (s.pending === 0) {
1468
    s.pending_out = 0;
1469
  }
1470
}
1471

    
1472

    
1473
function flush_block_only(s, last) {
1474
  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
1475
  s.block_start = s.strstart;
1476
  flush_pending(s.strm);
1477
}
1478

    
1479

    
1480
function put_byte(s, b) {
1481
  s.pending_buf[s.pending++] = b;
1482
}
1483

    
1484

    
1485
/* =========================================================================
1486
 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
1487
 * IN assertion: the stream state is correct and there is enough room in
1488
 * pending_buf.
1489
 */
1490
function putShortMSB(s, b) {
1491
//  put_byte(s, (Byte)(b >> 8));
1492
//  put_byte(s, (Byte)(b & 0xff));
1493
  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
1494
  s.pending_buf[s.pending++] = b & 0xff;
1495
}
1496

    
1497

    
1498
/* ===========================================================================
1499
 * Read a new buffer from the current input stream, update the adler32
1500
 * and total number of bytes read.  All deflate() input goes through
1501
 * this function so some applications may wish to modify it to avoid
1502
 * allocating a large strm->input buffer and copying from it.
1503
 * (See also flush_pending()).
1504
 */
1505
function read_buf(strm, buf, start, size) {
1506
  var len = strm.avail_in;
1507

    
1508
  if (len > size) { len = size; }
1509
  if (len === 0) { return 0; }
1510

    
1511
  strm.avail_in -= len;
1512

    
1513
  // zmemcpy(buf, strm->next_in, len);
1514
  utils.arraySet(buf, strm.input, strm.next_in, len, start);
1515
  if (strm.state.wrap === 1) {
1516
    strm.adler = adler32(strm.adler, buf, len, start);
1517
  }
1518

    
1519
  else if (strm.state.wrap === 2) {
1520
    strm.adler = crc32(strm.adler, buf, len, start);
1521
  }
1522

    
1523
  strm.next_in += len;
1524
  strm.total_in += len;
1525

    
1526
  return len;
1527
}
1528

    
1529

    
1530
/* ===========================================================================
1531
 * Set match_start to the longest match starting at the given string and
1532
 * return its length. Matches shorter or equal to prev_length are discarded,
1533
 * in which case the result is equal to prev_length and match_start is
1534
 * garbage.
1535
 * IN assertions: cur_match is the head of the hash chain for the current
1536
 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1537
 * OUT assertion: the match length is not greater than s->lookahead.
1538
 */
1539
function longest_match(s, cur_match) {
1540
  var chain_length = s.max_chain_length;      /* max hash chain length */
1541
  var scan = s.strstart; /* current string */
1542
  var match;                       /* matched string */
1543
  var len;                           /* length of current match */
1544
  var best_len = s.prev_length;              /* best match length so far */
1545
  var nice_match = s.nice_match;             /* stop if match long enough */
1546
  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
1547
      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
1548

    
1549
  var _win = s.window; // shortcut
1550

    
1551
  var wmask = s.w_mask;
1552
  var prev  = s.prev;
1553

    
1554
  /* Stop when cur_match becomes <= limit. To simplify the code,
1555
   * we prevent matches with the string of window index 0.
1556
   */
1557

    
1558
  var strend = s.strstart + MAX_MATCH;
1559
  var scan_end1  = _win[scan + best_len - 1];
1560
  var scan_end   = _win[scan + best_len];
1561

    
1562
  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1563
   * It is easy to get rid of this optimization if necessary.
1564
   */
1565
  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1566

    
1567
  /* Do not waste too much time if we already have a good match: */
1568
  if (s.prev_length >= s.good_match) {
1569
    chain_length >>= 2;
1570
  }
1571
  /* Do not look for matches beyond the end of the input. This is necessary
1572
   * to make deflate deterministic.
1573
   */
1574
  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
1575

    
1576
  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1577

    
1578
  do {
1579
    // Assert(cur_match < s->strstart, "no future");
1580
    match = cur_match;
1581

    
1582
    /* Skip to next match if the match length cannot increase
1583
     * or if the match length is less than 2.  Note that the checks below
1584
     * for insufficient lookahead only occur occasionally for performance
1585
     * reasons.  Therefore uninitialized memory will be accessed, and
1586
     * conditional jumps will be made that depend on those values.
1587
     * However the length of the match is limited to the lookahead, so
1588
     * the output of deflate is not affected by the uninitialized values.
1589
     */
1590

    
1591
    if (_win[match + best_len]     !== scan_end  ||
1592
        _win[match + best_len - 1] !== scan_end1 ||
1593
        _win[match]                !== _win[scan] ||
1594
        _win[++match]              !== _win[scan + 1]) {
1595
      continue;
1596
    }
1597

    
1598
    /* The check at best_len-1 can be removed because it will be made
1599
     * again later. (This heuristic is not always a win.)
1600
     * It is not necessary to compare scan[2] and match[2] since they
1601
     * are always equal when the other bytes match, given that
1602
     * the hash keys are equal and that HASH_BITS >= 8.
1603
     */
1604
    scan += 2;
1605
    match++;
1606
    // Assert(*scan == *match, "match[2]?");
1607

    
1608
    /* We check for insufficient lookahead only every 8th comparison;
1609
     * the 256th check will be made at strstart+258.
1610
     */
1611
    do {
1612
      /*jshint noempty:false*/
1613
    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1614
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1615
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1616
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1617
             scan < strend);
1618

    
1619
    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1620

    
1621
    len = MAX_MATCH - (strend - scan);
1622
    scan = strend - MAX_MATCH;
1623

    
1624
    if (len > best_len) {
1625
      s.match_start = cur_match;
1626
      best_len = len;
1627
      if (len >= nice_match) {
1628
        break;
1629
      }
1630
      scan_end1  = _win[scan + best_len - 1];
1631
      scan_end   = _win[scan + best_len];
1632
    }
1633
  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
1634

    
1635
  if (best_len <= s.lookahead) {
1636
    return best_len;
1637
  }
1638
  return s.lookahead;
1639
}
1640

    
1641

    
1642
/* ===========================================================================
1643
 * Fill the window when the lookahead becomes insufficient.
1644
 * Updates strstart and lookahead.
1645
 *
1646
 * IN assertion: lookahead < MIN_LOOKAHEAD
1647
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1648
 *    At least one byte has been read, or avail_in == 0; reads are
1649
 *    performed for at least two bytes (required for the zip translate_eol
1650
 *    option -- not supported here).
1651
 */
1652
function fill_window(s) {
1653
  var _w_size = s.w_size;
1654
  var p, n, m, more, str;
1655

    
1656
  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1657

    
1658
  do {
1659
    more = s.window_size - s.lookahead - s.strstart;
1660

    
1661
    // JS ints have 32 bit, block below not needed
1662
    /* Deal with !@#$% 64K limit: */
1663
    //if (sizeof(int) <= 2) {
1664
    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1665
    //        more = wsize;
1666
    //
1667
    //  } else if (more == (unsigned)(-1)) {
1668
    //        /* Very unlikely, but possible on 16 bit machine if
1669
    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
1670
    //         */
1671
    //        more--;
1672
    //    }
1673
    //}
1674

    
1675

    
1676
    /* If the window is almost full and there is insufficient lookahead,
1677
     * move the upper half to the lower one to make room in the upper half.
1678
     */
1679
    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
1680

    
1681
      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
1682
      s.match_start -= _w_size;
1683
      s.strstart -= _w_size;
1684
      /* we now have strstart >= MAX_DIST */
1685
      s.block_start -= _w_size;
1686

    
1687
      /* Slide the hash table (could be avoided with 32 bit values
1688
       at the expense of memory usage). We slide even when level == 0
1689
       to keep the hash table consistent if we switch back to level > 0
1690
       later. (Using level 0 permanently is not an optimal usage of
1691
       zlib, so we don't care about this pathological case.)
1692
       */
1693

    
1694
      n = s.hash_size;
1695
      p = n;
1696
      do {
1697
        m = s.head[--p];
1698
        s.head[p] = (m >= _w_size ? m - _w_size : 0);
1699
      } while (--n);
1700

    
1701
      n = _w_size;
1702
      p = n;
1703
      do {
1704
        m = s.prev[--p];
1705
        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
1706
        /* If n is not on any hash chain, prev[n] is garbage but
1707
         * its value will never be used.
1708
         */
1709
      } while (--n);
1710

    
1711
      more += _w_size;
1712
    }
1713
    if (s.strm.avail_in === 0) {
1714
      break;
1715
    }
1716

    
1717
    /* If there was no sliding:
1718
     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1719
     *    more == window_size - lookahead - strstart
1720
     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1721
     * => more >= window_size - 2*WSIZE + 2
1722
     * In the BIG_MEM or MMAP case (not yet supported),
1723
     *   window_size == input_size + MIN_LOOKAHEAD  &&
1724
     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1725
     * Otherwise, window_size == 2*WSIZE so more >= 2.
1726
     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1727
     */
1728
    //Assert(more >= 2, "more < 2");
1729
    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
1730
    s.lookahead += n;
1731

    
1732
    /* Initialize the hash value now that we have some input: */
1733
    if (s.lookahead + s.insert >= MIN_MATCH) {
1734
      str = s.strstart - s.insert;
1735
      s.ins_h = s.window[str];
1736

    
1737
      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
1738
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
1739
//#if MIN_MATCH != 3
1740
//        Call update_hash() MIN_MATCH-3 more times
1741
//#endif
1742
      while (s.insert) {
1743
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
1744
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
1745

    
1746
        s.prev[str & s.w_mask] = s.head[s.ins_h];
1747
        s.head[s.ins_h] = str;
1748
        str++;
1749
        s.insert--;
1750
        if (s.lookahead + s.insert < MIN_MATCH) {
1751
          break;
1752
        }
1753
      }
1754
    }
1755
    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1756
     * but this is not important since only literal bytes will be emitted.
1757
     */
1758

    
1759
  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
1760

    
1761
  /* If the WIN_INIT bytes after the end of the current data have never been
1762
   * written, then zero those bytes in order to avoid memory check reports of
1763
   * the use of uninitialized (or uninitialised as Julian writes) bytes by
1764
   * the longest match routines.  Update the high water mark for the next
1765
   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1766
   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1767
   */
1768
//  if (s.high_water < s.window_size) {
1769
//    var curr = s.strstart + s.lookahead;
1770
//    var init = 0;
1771
//
1772
//    if (s.high_water < curr) {
1773
//      /* Previous high water mark below current data -- zero WIN_INIT
1774
//       * bytes or up to end of window, whichever is less.
1775
//       */
1776
//      init = s.window_size - curr;
1777
//      if (init > WIN_INIT)
1778
//        init = WIN_INIT;
1779
//      zmemzero(s->window + curr, (unsigned)init);
1780
//      s->high_water = curr + init;
1781
//    }
1782
//    else if (s->high_water < (ulg)curr + WIN_INIT) {
1783
//      /* High water mark at or above current data, but below current data
1784
//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1785
//       * to end of window, whichever is less.
1786
//       */
1787
//      init = (ulg)curr + WIN_INIT - s->high_water;
1788
//      if (init > s->window_size - s->high_water)
1789
//        init = s->window_size - s->high_water;
1790
//      zmemzero(s->window + s->high_water, (unsigned)init);
1791
//      s->high_water += init;
1792
//    }
1793
//  }
1794
//
1795
//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1796
//    "not enough room for search");
1797
}
1798

    
1799
/* ===========================================================================
1800
 * Copy without compression as much as possible from the input stream, return
1801
 * the current block state.
1802
 * This function does not insert new strings in the dictionary since
1803
 * uncompressible data is probably not useful. This function is used
1804
 * only for the level=0 compression option.
1805
 * NOTE: this function should be optimized to avoid extra copying from
1806
 * window to pending_buf.
1807
 */
1808
function deflate_stored(s, flush) {
1809
  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1810
   * to pending_buf_size, and each stored block has a 5 byte header:
1811
   */
1812
  var max_block_size = 0xffff;
1813

    
1814
  if (max_block_size > s.pending_buf_size - 5) {
1815
    max_block_size = s.pending_buf_size - 5;
1816
  }
1817

    
1818
  /* Copy as much as possible from input to output: */
1819
  for (;;) {
1820
    /* Fill the window as much as possible: */
1821
    if (s.lookahead <= 1) {
1822

    
1823
      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1824
      //  s->block_start >= (long)s->w_size, "slide too late");
1825
//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
1826
//        s.block_start >= s.w_size)) {
1827
//        throw  new Error("slide too late");
1828
//      }
1829

    
1830
      fill_window(s);
1831
      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
1832
        return BS_NEED_MORE;
1833
      }
1834

    
1835
      if (s.lookahead === 0) {
1836
        break;
1837
      }
1838
      /* flush the current block */
1839
    }
1840
    //Assert(s->block_start >= 0L, "block gone");
1841
//    if (s.block_start < 0) throw new Error("block gone");
1842

    
1843
    s.strstart += s.lookahead;
1844
    s.lookahead = 0;
1845

    
1846
    /* Emit a stored block if pending_buf will be full: */
1847
    var max_start = s.block_start + max_block_size;
1848

    
1849
    if (s.strstart === 0 || s.strstart >= max_start) {
1850
      /* strstart == 0 is possible when wraparound on 16-bit machine */
1851
      s.lookahead = s.strstart - max_start;
1852
      s.strstart = max_start;
1853
      /*** FLUSH_BLOCK(s, 0); ***/
1854
      flush_block_only(s, false);
1855
      if (s.strm.avail_out === 0) {
1856
        return BS_NEED_MORE;
1857
      }
1858
      /***/
1859

    
1860

    
1861
    }
1862
    /* Flush if we may have to slide, otherwise block_start may become
1863
     * negative and the data will be gone:
1864
     */
1865
    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
1866
      /*** FLUSH_BLOCK(s, 0); ***/
1867
      flush_block_only(s, false);
1868
      if (s.strm.avail_out === 0) {
1869
        return BS_NEED_MORE;
1870
      }
1871
      /***/
1872
    }
1873
  }
1874

    
1875
  s.insert = 0;
1876

    
1877
  if (flush === Z_FINISH) {
1878
    /*** FLUSH_BLOCK(s, 1); ***/
1879
    flush_block_only(s, true);
1880
    if (s.strm.avail_out === 0) {
1881
      return BS_FINISH_STARTED;
1882
    }
1883
    /***/
1884
    return BS_FINISH_DONE;
1885
  }
1886

    
1887
  if (s.strstart > s.block_start) {
1888
    /*** FLUSH_BLOCK(s, 0); ***/
1889
    flush_block_only(s, false);
1890
    if (s.strm.avail_out === 0) {
1891
      return BS_NEED_MORE;
1892
    }
1893
    /***/
1894
  }
1895

    
1896
  return BS_NEED_MORE;
1897
}
1898

    
1899
/* ===========================================================================
1900
 * Compress as much as possible from the input stream, return the current
1901
 * block state.
1902
 * This function does not perform lazy evaluation of matches and inserts
1903
 * new strings in the dictionary only for unmatched strings or for short
1904
 * matches. It is used only for the fast compression options.
1905
 */
1906
function deflate_fast(s, flush) {
1907
  var hash_head;        /* head of the hash chain */
1908
  var bflush;           /* set if current block must be flushed */
1909

    
1910
  for (;;) {
1911
    /* Make sure that we always have enough lookahead, except
1912
     * at the end of the input file. We need MAX_MATCH bytes
1913
     * for the next match, plus MIN_MATCH bytes to insert the
1914
     * string following the next match.
1915
     */
1916
    if (s.lookahead < MIN_LOOKAHEAD) {
1917
      fill_window(s);
1918
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
1919
        return BS_NEED_MORE;
1920
      }
1921
      if (s.lookahead === 0) {
1922
        break; /* flush the current block */
1923
      }
1924
    }
1925

    
1926
    /* Insert the string window[strstart .. strstart+2] in the
1927
     * dictionary, and set hash_head to the head of the hash chain:
1928
     */
1929
    hash_head = 0/*NIL*/;
1930
    if (s.lookahead >= MIN_MATCH) {
1931
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1932
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1933
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1934
      s.head[s.ins_h] = s.strstart;
1935
      /***/
1936
    }
1937

    
1938
    /* Find the longest match, discarding those <= prev_length.
1939
     * At this point we have always match_length < MIN_MATCH
1940
     */
1941
    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
1942
      /* To simplify the code, we prevent matches with the string
1943
       * of window index 0 (in particular we have to avoid a match
1944
       * of the string with itself at the start of the input file).
1945
       */
1946
      s.match_length = longest_match(s, hash_head);
1947
      /* longest_match() sets match_start */
1948
    }
1949
    if (s.match_length >= MIN_MATCH) {
1950
      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
1951

    
1952
      /*** _tr_tally_dist(s, s.strstart - s.match_start,
1953
                     s.match_length - MIN_MATCH, bflush); ***/
1954
      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
1955

    
1956
      s.lookahead -= s.match_length;
1957

    
1958
      /* Insert new strings in the hash table only if the match length
1959
       * is not too large. This saves time but degrades compression.
1960
       */
1961
      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
1962
        s.match_length--; /* string at strstart already in table */
1963
        do {
1964
          s.strstart++;
1965
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1966
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1967
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1968
          s.head[s.ins_h] = s.strstart;
1969
          /***/
1970
          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1971
           * always MIN_MATCH bytes ahead.
1972
           */
1973
        } while (--s.match_length !== 0);
1974
        s.strstart++;
1975
      } else
1976
      {
1977
        s.strstart += s.match_length;
1978
        s.match_length = 0;
1979
        s.ins_h = s.window[s.strstart];
1980
        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
1981
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
1982

    
1983
//#if MIN_MATCH != 3
1984
//                Call UPDATE_HASH() MIN_MATCH-3 more times
1985
//#endif
1986
        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1987
         * matter since it will be recomputed at next deflate call.
1988
         */
1989
      }
1990
    } else {
1991
      /* No match, output a literal byte */
1992
      //Tracevv((stderr,"%c", s.window[s.strstart]));
1993
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
1994
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
1995

    
1996
      s.lookahead--;
1997
      s.strstart++;
1998
    }
1999
    if (bflush) {
2000
      /*** FLUSH_BLOCK(s, 0); ***/
2001
      flush_block_only(s, false);
2002
      if (s.strm.avail_out === 0) {
2003
        return BS_NEED_MORE;
2004
      }
2005
      /***/
2006
    }
2007
  }
2008
  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
2009
  if (flush === Z_FINISH) {
2010
    /*** FLUSH_BLOCK(s, 1); ***/
2011
    flush_block_only(s, true);
2012
    if (s.strm.avail_out === 0) {
2013
      return BS_FINISH_STARTED;
2014
    }
2015
    /***/
2016
    return BS_FINISH_DONE;
2017
  }
2018
  if (s.last_lit) {
2019
    /*** FLUSH_BLOCK(s, 0); ***/
2020
    flush_block_only(s, false);
2021
    if (s.strm.avail_out === 0) {
2022
      return BS_NEED_MORE;
2023
    }
2024
    /***/
2025
  }
2026
  return BS_BLOCK_DONE;
2027
}
2028

    
2029
/* ===========================================================================
2030
 * Same as above, but achieves better compression. We use a lazy
2031
 * evaluation for matches: a match is finally adopted only if there is
2032
 * no better match at the next window position.
2033
 */
2034
function deflate_slow(s, flush) {
2035
  var hash_head;          /* head of hash chain */
2036
  var bflush;              /* set if current block must be flushed */
2037

    
2038
  var max_insert;
2039

    
2040
  /* Process the input block. */
2041
  for (;;) {
2042
    /* Make sure that we always have enough lookahead, except
2043
     * at the end of the input file. We need MAX_MATCH bytes
2044
     * for the next match, plus MIN_MATCH bytes to insert the
2045
     * string following the next match.
2046
     */
2047
    if (s.lookahead < MIN_LOOKAHEAD) {
2048
      fill_window(s);
2049
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
2050
        return BS_NEED_MORE;
2051
      }
2052
      if (s.lookahead === 0) { break; } /* flush the current block */
2053
    }
2054

    
2055
    /* Insert the string window[strstart .. strstart+2] in the
2056
     * dictionary, and set hash_head to the head of the hash chain:
2057
     */
2058
    hash_head = 0/*NIL*/;
2059
    if (s.lookahead >= MIN_MATCH) {
2060
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
2061
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
2062
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
2063
      s.head[s.ins_h] = s.strstart;
2064
      /***/
2065
    }
2066

    
2067
    /* Find the longest match, discarding those <= prev_length.
2068
     */
2069
    s.prev_length = s.match_length;
2070
    s.prev_match = s.match_start;
2071
    s.match_length = MIN_MATCH - 1;
2072

    
2073
    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
2074
        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
2075
      /* To simplify the code, we prevent matches with the string
2076
       * of window index 0 (in particular we have to avoid a match
2077
       * of the string with itself at the start of the input file).
2078
       */
2079
      s.match_length = longest_match(s, hash_head);
2080
      /* longest_match() sets match_start */
2081

    
2082
      if (s.match_length <= 5 &&
2083
         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
2084

    
2085
        /* If prev_match is also MIN_MATCH, match_start is garbage
2086
         * but we will ignore the current match anyway.
2087
         */
2088
        s.match_length = MIN_MATCH - 1;
2089
      }
2090
    }
2091
    /* If there was a match at the previous step and the current
2092
     * match is not better, output the previous match:
2093
     */
2094
    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
2095
      max_insert = s.strstart + s.lookahead - MIN_MATCH;
2096
      /* Do not insert strings in hash table beyond this. */
2097

    
2098
      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
2099

    
2100
      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
2101
                     s.prev_length - MIN_MATCH, bflush);***/
2102
      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
2103
      /* Insert in hash table all strings up to the end of the match.
2104
       * strstart-1 and strstart are already inserted. If there is not
2105
       * enough lookahead, the last two strings are not inserted in
2106
       * the hash table.
2107
       */
2108
      s.lookahead -= s.prev_length - 1;
2109
      s.prev_length -= 2;
2110
      do {
2111
        if (++s.strstart <= max_insert) {
2112
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
2113
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
2114
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
2115
          s.head[s.ins_h] = s.strstart;
2116
          /***/
2117
        }
2118
      } while (--s.prev_length !== 0);
2119
      s.match_available = 0;
2120
      s.match_length = MIN_MATCH - 1;
2121
      s.strstart++;
2122

    
2123
      if (bflush) {
2124
        /*** FLUSH_BLOCK(s, 0); ***/
2125
        flush_block_only(s, false);
2126
        if (s.strm.avail_out === 0) {
2127
          return BS_NEED_MORE;
2128
        }
2129
        /***/
2130
      }
2131

    
2132
    } else if (s.match_available) {
2133
      /* If there was no match at the previous position, output a
2134
       * single literal. If there was a match but the current match
2135
       * is longer, truncate the previous match to a single literal.
2136
       */
2137
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
2138
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
2139
      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
2140

    
2141
      if (bflush) {
2142
        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
2143
        flush_block_only(s, false);
2144
        /***/
2145
      }
2146
      s.strstart++;
2147
      s.lookahead--;
2148
      if (s.strm.avail_out === 0) {
2149
        return BS_NEED_MORE;
2150
      }
2151
    } else {
2152
      /* There is no previous match to compare with, wait for
2153
       * the next step to decide.
2154
       */
2155
      s.match_available = 1;
2156
      s.strstart++;
2157
      s.lookahead--;
2158
    }
2159
  }
2160
  //Assert (flush != Z_NO_FLUSH, "no flush?");
2161
  if (s.match_available) {
2162
    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
2163
    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
2164
    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
2165

    
2166
    s.match_available = 0;
2167
  }
2168
  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
2169
  if (flush === Z_FINISH) {
2170
    /*** FLUSH_BLOCK(s, 1); ***/
2171
    flush_block_only(s, true);
2172
    if (s.strm.avail_out === 0) {
2173
      return BS_FINISH_STARTED;
2174
    }
2175
    /***/
2176
    return BS_FINISH_DONE;
2177
  }
2178
  if (s.last_lit) {
2179
    /*** FLUSH_BLOCK(s, 0); ***/
2180
    flush_block_only(s, false);
2181
    if (s.strm.avail_out === 0) {
2182
      return BS_NEED_MORE;
2183
    }
2184
    /***/
2185
  }
2186

    
2187
  return BS_BLOCK_DONE;
2188
}
2189

    
2190

    
2191
/* ===========================================================================
2192
 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2193
 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2194
 * deflate switches away from Z_RLE.)
2195
 */
2196
function deflate_rle(s, flush) {
2197
  var bflush;            /* set if current block must be flushed */
2198
  var prev;              /* byte at distance one to match */
2199
  var scan, strend;      /* scan goes up to strend for length of run */
2200

    
2201
  var _win = s.window;
2202

    
2203
  for (;;) {
2204
    /* Make sure that we always have enough lookahead, except
2205
     * at the end of the input file. We need MAX_MATCH bytes
2206
     * for the longest run, plus one for the unrolled loop.
2207
     */
2208
    if (s.lookahead <= MAX_MATCH) {
2209
      fill_window(s);
2210
      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
2211
        return BS_NEED_MORE;
2212
      }
2213
      if (s.lookahead === 0) { break; } /* flush the current block */
2214
    }
2215

    
2216
    /* See how many times the previous byte repeats */
2217
    s.match_length = 0;
2218
    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
2219
      scan = s.strstart - 1;
2220
      prev = _win[scan];
2221
      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
2222
        strend = s.strstart + MAX_MATCH;
2223
        do {
2224
          /*jshint noempty:false*/
2225
        } while (prev === _win[++scan] && prev === _win[++scan] &&
2226
                 prev === _win[++scan] && prev === _win[++scan] &&
2227
                 prev === _win[++scan] && prev === _win[++scan] &&
2228
                 prev === _win[++scan] && prev === _win[++scan] &&
2229
                 scan < strend);
2230
        s.match_length = MAX_MATCH - (strend - scan);
2231
        if (s.match_length > s.lookahead) {
2232
          s.match_length = s.lookahead;
2233
        }
2234
      }
2235
      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2236
    }
2237

    
2238
    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2239
    if (s.match_length >= MIN_MATCH) {
2240
      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
2241

    
2242
      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
2243
      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
2244

    
2245
      s.lookahead -= s.match_length;
2246
      s.strstart += s.match_length;
2247
      s.match_length = 0;
2248
    } else {
2249
      /* No match, output a literal byte */
2250
      //Tracevv((stderr,"%c", s->window[s->strstart]));
2251
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2252
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2253

    
2254
      s.lookahead--;
2255
      s.strstart++;
2256
    }
2257
    if (bflush) {
2258
      /*** FLUSH_BLOCK(s, 0); ***/
2259
      flush_block_only(s, false);
2260
      if (s.strm.avail_out === 0) {
2261
        return BS_NEED_MORE;
2262
      }
2263
      /***/
2264
    }
2265
  }
2266
  s.insert = 0;
2267
  if (flush === Z_FINISH) {
2268
    /*** FLUSH_BLOCK(s, 1); ***/
2269
    flush_block_only(s, true);
2270
    if (s.strm.avail_out === 0) {
2271
      return BS_FINISH_STARTED;
2272
    }
2273
    /***/
2274
    return BS_FINISH_DONE;
2275
  }
2276
  if (s.last_lit) {
2277
    /*** FLUSH_BLOCK(s, 0); ***/
2278
    flush_block_only(s, false);
2279
    if (s.strm.avail_out === 0) {
2280
      return BS_NEED_MORE;
2281
    }
2282
    /***/
2283
  }
2284
  return BS_BLOCK_DONE;
2285
}
2286

    
2287
/* ===========================================================================
2288
 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2289
 * (It will be regenerated if this run of deflate switches away from Huffman.)
2290
 */
2291
function deflate_huff(s, flush) {
2292
  var bflush;             /* set if current block must be flushed */
2293

    
2294
  for (;;) {
2295
    /* Make sure that we have a literal to write. */
2296
    if (s.lookahead === 0) {
2297
      fill_window(s);
2298
      if (s.lookahead === 0) {
2299
        if (flush === Z_NO_FLUSH) {
2300
          return BS_NEED_MORE;
2301
        }
2302
        break;      /* flush the current block */
2303
      }
2304
    }
2305

    
2306
    /* Output a literal byte */
2307
    s.match_length = 0;
2308
    //Tracevv((stderr,"%c", s->window[s->strstart]));
2309
    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2310
    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2311
    s.lookahead--;
2312
    s.strstart++;
2313
    if (bflush) {
2314
      /*** FLUSH_BLOCK(s, 0); ***/
2315
      flush_block_only(s, false);
2316
      if (s.strm.avail_out === 0) {
2317
        return BS_NEED_MORE;
2318
      }
2319
      /***/
2320
    }
2321
  }
2322
  s.insert = 0;
2323
  if (flush === Z_FINISH) {
2324
    /*** FLUSH_BLOCK(s, 1); ***/
2325
    flush_block_only(s, true);
2326
    if (s.strm.avail_out === 0) {
2327
      return BS_FINISH_STARTED;
2328
    }
2329
    /***/
2330
    return BS_FINISH_DONE;
2331
  }
2332
  if (s.last_lit) {
2333
    /*** FLUSH_BLOCK(s, 0); ***/
2334
    flush_block_only(s, false);
2335
    if (s.strm.avail_out === 0) {
2336
      return BS_NEED_MORE;
2337
    }
2338
    /***/
2339
  }
2340
  return BS_BLOCK_DONE;
2341
}
2342

    
2343
/* Values for max_lazy_match, good_match and max_chain_length, depending on
2344
 * the desired pack level (0..9). The values given below have been tuned to
2345
 * exclude worst case performance for pathological files. Better values may be
2346
 * found for specific files.
2347
 */
2348
function Config(good_length, max_lazy, nice_length, max_chain, func) {
2349
  this.good_length = good_length;
2350
  this.max_lazy = max_lazy;
2351
  this.nice_length = nice_length;
2352
  this.max_chain = max_chain;
2353
  this.func = func;
2354
}
2355

    
2356
var configuration_table;
2357

    
2358
configuration_table = [
2359
  /*      good lazy nice chain */
2360
  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
2361
  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
2362
  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
2363
  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
2364

    
2365
  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
2366
  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
2367
  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
2368
  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
2369
  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
2370
  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
2371
];
2372

    
2373

    
2374
/* ===========================================================================
2375
 * Initialize the "longest match" routines for a new zlib stream
2376
 */
2377
function lm_init(s) {
2378
  s.window_size = 2 * s.w_size;
2379

    
2380
  /*** CLEAR_HASH(s); ***/
2381
  zero(s.head); // Fill with NIL (= 0);
2382

    
2383
  /* Set the default configuration parameters:
2384
   */
2385
  s.max_lazy_match = configuration_table[s.level].max_lazy;
2386
  s.good_match = configuration_table[s.level].good_length;
2387
  s.nice_match = configuration_table[s.level].nice_length;
2388
  s.max_chain_length = configuration_table[s.level].max_chain;
2389

    
2390
  s.strstart = 0;
2391
  s.block_start = 0;
2392
  s.lookahead = 0;
2393
  s.insert = 0;
2394
  s.match_length = s.prev_length = MIN_MATCH - 1;
2395
  s.match_available = 0;
2396
  s.ins_h = 0;
2397
}
2398

    
2399

    
2400
function DeflateState() {
2401
  this.strm = null;            /* pointer back to this zlib stream */
2402
  this.status = 0;            /* as the name implies */
2403
  this.pending_buf = null;      /* output still pending */
2404
  this.pending_buf_size = 0;  /* size of pending_buf */
2405
  this.pending_out = 0;       /* next pending byte to output to the stream */
2406
  this.pending = 0;           /* nb of bytes in the pending buffer */
2407
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
2408
  this.gzhead = null;         /* gzip header information to write */
2409
  this.gzindex = 0;           /* where in extra, name, or comment */
2410
  this.method = Z_DEFLATED; /* can only be DEFLATED */
2411
  this.last_flush = -1;   /* value of flush param for previous deflate call */
2412

    
2413
  this.w_size = 0;  /* LZ77 window size (32K by default) */
2414
  this.w_bits = 0;  /* log2(w_size)  (8..16) */
2415
  this.w_mask = 0;  /* w_size - 1 */
2416

    
2417
  this.window = null;
2418
  /* Sliding window. Input bytes are read into the second half of the window,
2419
   * and move to the first half later to keep a dictionary of at least wSize
2420
   * bytes. With this organization, matches are limited to a distance of
2421
   * wSize-MAX_MATCH bytes, but this ensures that IO is always
2422
   * performed with a length multiple of the block size.
2423
   */
2424

    
2425
  this.window_size = 0;
2426
  /* Actual size of window: 2*wSize, except when the user input buffer
2427
   * is directly used as sliding window.
2428
   */
2429

    
2430
  this.prev = null;
2431
  /* Link to older string with same hash index. To limit the size of this
2432
   * array to 64K, this link is maintained only for the last 32K strings.
2433
   * An index in this array is thus a window index modulo 32K.
2434
   */
2435

    
2436
  this.head = null;   /* Heads of the hash chains or NIL. */
2437

    
2438
  this.ins_h = 0;       /* hash index of string to be inserted */
2439
  this.hash_size = 0;   /* number of elements in hash table */
2440
  this.hash_bits = 0;   /* log2(hash_size) */
2441
  this.hash_mask = 0;   /* hash_size-1 */
2442

    
2443
  this.hash_shift = 0;
2444
  /* Number of bits by which ins_h must be shifted at each input
2445
   * step. It must be such that after MIN_MATCH steps, the oldest
2446
   * byte no longer takes part in the hash key, that is:
2447
   *   hash_shift * MIN_MATCH >= hash_bits
2448
   */
2449

    
2450
  this.block_start = 0;
2451
  /* Window position at the beginning of the current output block. Gets
2452
   * negative when the window is moved backwards.
2453
   */
2454

    
2455
  this.match_length = 0;      /* length of best match */
2456
  this.prev_match = 0;        /* previous match */
2457
  this.match_available = 0;   /* set if previous match exists */
2458
  this.strstart = 0;          /* start of string to insert */
2459
  this.match_start = 0;       /* start of matching string */
2460
  this.lookahead = 0;         /* number of valid bytes ahead in window */
2461

    
2462
  this.prev_length = 0;
2463
  /* Length of the best match at previous step. Matches not greater than this
2464
   * are discarded. This is used in the lazy match evaluation.
2465
   */
2466

    
2467
  this.max_chain_length = 0;
2468
  /* To speed up deflation, hash chains are never searched beyond this
2469
   * length.  A higher limit improves compression ratio but degrades the
2470
   * speed.
2471
   */
2472

    
2473
  this.max_lazy_match = 0;
2474
  /* Attempt to find a better match only when the current match is strictly
2475
   * smaller than this value. This mechanism is used only for compression
2476
   * levels >= 4.
2477
   */
2478
  // That's alias to max_lazy_match, don't use directly
2479
  //this.max_insert_length = 0;
2480
  /* Insert new strings in the hash table only if the match length is not
2481
   * greater than this length. This saves time but degrades compression.
2482
   * max_insert_length is used only for compression levels <= 3.
2483
   */
2484

    
2485
  this.level = 0;     /* compression level (1..9) */
2486
  this.strategy = 0;  /* favor or force Huffman coding*/
2487

    
2488
  this.good_match = 0;
2489
  /* Use a faster search when the previous match is longer than this */
2490

    
2491
  this.nice_match = 0; /* Stop searching when current match exceeds this */
2492

    
2493
              /* used by trees.c: */
2494

    
2495
  /* Didn't use ct_data typedef below to suppress compiler warning */
2496

    
2497
  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
2498
  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
2499
  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
2500

    
2501
  // Use flat array of DOUBLE size, with interleaved fata,
2502
  // because JS does not support effective
2503
  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
2504
  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
2505
  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
2506
  zero(this.dyn_ltree);
2507
  zero(this.dyn_dtree);
2508
  zero(this.bl_tree);
2509

    
2510
  this.l_desc   = null;         /* desc. for literal tree */
2511
  this.d_desc   = null;         /* desc. for distance tree */
2512
  this.bl_desc  = null;         /* desc. for bit length tree */
2513

    
2514
  //ush bl_count[MAX_BITS+1];
2515
  this.bl_count = new utils.Buf16(MAX_BITS + 1);
2516
  /* number of codes at each bit length for an optimal tree */
2517

    
2518
  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
2519
  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
2520
  zero(this.heap);
2521

    
2522
  this.heap_len = 0;               /* number of elements in the heap */
2523
  this.heap_max = 0;               /* element of largest frequency */
2524
  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2525
   * The same heap array is used to build all trees.
2526
   */
2527

    
2528
  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
2529
  zero(this.depth);
2530
  /* Depth of each subtree used as tie breaker for trees of equal frequency
2531
   */
2532

    
2533
  this.l_buf = 0;          /* buffer index for literals or lengths */
2534

    
2535
  this.lit_bufsize = 0;
2536
  /* Size of match buffer for literals/lengths.  There are 4 reasons for
2537
   * limiting lit_bufsize to 64K:
2538
   *   - frequencies can be kept in 16 bit counters
2539
   *   - if compression is not successful for the first block, all input
2540
   *     data is still in the window so we can still emit a stored block even
2541
   *     when input comes from standard input.  (This can also be done for
2542
   *     all blocks if lit_bufsize is not greater than 32K.)
2543
   *   - if compression is not successful for a file smaller than 64K, we can
2544
   *     even emit a stored file instead of a stored block (saving 5 bytes).
2545
   *     This is applicable only for zip (not gzip or zlib).
2546
   *   - creating new Huffman trees less frequently may not provide fast
2547
   *     adaptation to changes in the input data statistics. (Take for
2548
   *     example a binary file with poorly compressible code followed by
2549
   *     a highly compressible string table.) Smaller buffer sizes give
2550
   *     fast adaptation but have of course the overhead of transmitting
2551
   *     trees more frequently.
2552
   *   - I can't count above 4
2553
   */
2554

    
2555
  this.last_lit = 0;      /* running index in l_buf */
2556

    
2557
  this.d_buf = 0;
2558
  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
2559
   * the same number of elements. To use different lengths, an extra flag
2560
   * array would be necessary.
2561
   */
2562

    
2563
  this.opt_len = 0;       /* bit length of current block with optimal trees */
2564
  this.static_len = 0;    /* bit length of current block with static trees */
2565
  this.matches = 0;       /* number of string matches in current block */
2566
  this.insert = 0;        /* bytes at end of window left to insert */
2567

    
2568

    
2569
  this.bi_buf = 0;
2570
  /* Output buffer. bits are inserted starting at the bottom (least
2571
   * significant bits).
2572
   */
2573
  this.bi_valid = 0;
2574
  /* Number of valid bits in bi_buf.  All bits above the last valid bit
2575
   * are always zero.
2576
   */
2577

    
2578
  // Used for window memory init. We safely ignore it for JS. That makes
2579
  // sense only for pointers and memory check tools.
2580
  //this.high_water = 0;
2581
  /* High water mark offset in window for initialized bytes -- bytes above
2582
   * this are set to zero in order to avoid memory check warnings when
2583
   * longest match routines access bytes past the input.  This is then
2584
   * updated to the new high water mark.
2585
   */
2586
}
2587

    
2588

    
2589
function deflateResetKeep(strm) {
2590
  var s;
2591

    
2592
  if (!strm || !strm.state) {
2593
    return err(strm, Z_STREAM_ERROR);
2594
  }
2595

    
2596
  strm.total_in = strm.total_out = 0;
2597
  strm.data_type = Z_UNKNOWN;
2598

    
2599
  s = strm.state;
2600
  s.pending = 0;
2601
  s.pending_out = 0;
2602

    
2603
  if (s.wrap < 0) {
2604
    s.wrap = -s.wrap;
2605
    /* was made negative by deflate(..., Z_FINISH); */
2606
  }
2607
  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
2608
  strm.adler = (s.wrap === 2) ?
2609
    0  // crc32(0, Z_NULL, 0)
2610
  :
2611
    1; // adler32(0, Z_NULL, 0)
2612
  s.last_flush = Z_NO_FLUSH;
2613
  trees._tr_init(s);
2614
  return Z_OK;
2615
}
2616

    
2617

    
2618
function deflateReset(strm) {
2619
  var ret = deflateResetKeep(strm);
2620
  if (ret === Z_OK) {
2621
    lm_init(strm.state);
2622
  }
2623
  return ret;
2624
}
2625

    
2626

    
2627
function deflateSetHeader(strm, head) {
2628
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
2629
  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
2630
  strm.state.gzhead = head;
2631
  return Z_OK;
2632
}
2633

    
2634

    
2635
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
2636
  if (!strm) { // === Z_NULL
2637
    return Z_STREAM_ERROR;
2638
  }
2639
  var wrap = 1;
2640

    
2641
  if (level === Z_DEFAULT_COMPRESSION) {
2642
    level = 6;
2643
  }
2644

    
2645
  if (windowBits < 0) { /* suppress zlib wrapper */
2646
    wrap = 0;
2647
    windowBits = -windowBits;
2648
  }
2649

    
2650
  else if (windowBits > 15) {
2651
    wrap = 2;           /* write gzip wrapper instead */
2652
    windowBits -= 16;
2653
  }
2654

    
2655

    
2656
  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
2657
    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
2658
    strategy < 0 || strategy > Z_FIXED) {
2659
    return err(strm, Z_STREAM_ERROR);
2660
  }
2661

    
2662

    
2663
  if (windowBits === 8) {
2664
    windowBits = 9;
2665
  }
2666
  /* until 256-byte window bug fixed */
2667

    
2668
  var s = new DeflateState();
2669

    
2670
  strm.state = s;
2671
  s.strm = strm;
2672

    
2673
  s.wrap = wrap;
2674
  s.gzhead = null;
2675
  s.w_bits = windowBits;
2676
  s.w_size = 1 << s.w_bits;
2677
  s.w_mask = s.w_size - 1;
2678

    
2679
  s.hash_bits = memLevel + 7;
2680
  s.hash_size = 1 << s.hash_bits;
2681
  s.hash_mask = s.hash_size - 1;
2682
  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
2683

    
2684
  s.window = new utils.Buf8(s.w_size * 2);
2685
  s.head = new utils.Buf16(s.hash_size);
2686
  s.prev = new utils.Buf16(s.w_size);
2687

    
2688
  // Don't need mem init magic for JS.
2689
  //s.high_water = 0;  /* nothing written to s->window yet */
2690

    
2691
  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
2692

    
2693
  s.pending_buf_size = s.lit_bufsize * 4;
2694

    
2695
  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
2696
  //s->pending_buf = (uchf *) overlay;
2697
  s.pending_buf = new utils.Buf8(s.pending_buf_size);
2698

    
2699
  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
2700
  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
2701
  s.d_buf = 1 * s.lit_bufsize;
2702

    
2703
  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
2704
  s.l_buf = (1 + 2) * s.lit_bufsize;
2705

    
2706
  s.level = level;
2707
  s.strategy = strategy;
2708
  s.method = method;
2709

    
2710
  return deflateReset(strm);
2711
}
2712

    
2713
function deflateInit(strm, level) {
2714
  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2715
}
2716

    
2717

    
2718
function deflate(strm, flush) {
2719
  var old_flush, s;
2720
  var beg, val; // for gzip header write only
2721

    
2722
  if (!strm || !strm.state ||
2723
    flush > Z_BLOCK || flush < 0) {
2724
    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
2725
  }
2726

    
2727
  s = strm.state;
2728

    
2729
  if (!strm.output ||
2730
      (!strm.input && strm.avail_in !== 0) ||
2731
      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
2732
    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
2733
  }
2734

    
2735
  s.strm = strm; /* just in case */
2736
  old_flush = s.last_flush;
2737
  s.last_flush = flush;
2738

    
2739
  /* Write the header */
2740
  if (s.status === INIT_STATE) {
2741

    
2742
    if (s.wrap === 2) { // GZIP header
2743
      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
2744
      put_byte(s, 31);
2745
      put_byte(s, 139);
2746
      put_byte(s, 8);
2747
      if (!s.gzhead) { // s->gzhead == Z_NULL
2748
        put_byte(s, 0);
2749
        put_byte(s, 0);
2750
        put_byte(s, 0);
2751
        put_byte(s, 0);
2752
        put_byte(s, 0);
2753
        put_byte(s, s.level === 9 ? 2 :
2754
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2755
                     4 : 0));
2756
        put_byte(s, OS_CODE);
2757
        s.status = BUSY_STATE;
2758
      }
2759
      else {
2760
        put_byte(s, (s.gzhead.text ? 1 : 0) +
2761
                    (s.gzhead.hcrc ? 2 : 0) +
2762
                    (!s.gzhead.extra ? 0 : 4) +
2763
                    (!s.gzhead.name ? 0 : 8) +
2764
                    (!s.gzhead.comment ? 0 : 16)
2765
        );
2766
        put_byte(s, s.gzhead.time & 0xff);
2767
        put_byte(s, (s.gzhead.time >> 8) & 0xff);
2768
        put_byte(s, (s.gzhead.time >> 16) & 0xff);
2769
        put_byte(s, (s.gzhead.time >> 24) & 0xff);
2770
        put_byte(s, s.level === 9 ? 2 :
2771
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2772
                     4 : 0));
2773
        put_byte(s, s.gzhead.os & 0xff);
2774
        if (s.gzhead.extra && s.gzhead.extra.length) {
2775
          put_byte(s, s.gzhead.extra.length & 0xff);
2776
          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
2777
        }
2778
        if (s.gzhead.hcrc) {
2779
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
2780
        }
2781
        s.gzindex = 0;
2782
        s.status = EXTRA_STATE;
2783
      }
2784
    }
2785
    else // DEFLATE header
2786
    {
2787
      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
2788
      var level_flags = -1;
2789

    
2790
      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
2791
        level_flags = 0;
2792
      } else if (s.level < 6) {
2793
        level_flags = 1;
2794
      } else if (s.level === 6) {
2795
        level_flags = 2;
2796
      } else {
2797
        level_flags = 3;
2798
      }
2799
      header |= (level_flags << 6);
2800
      if (s.strstart !== 0) { header |= PRESET_DICT; }
2801
      header += 31 - (header % 31);
2802

    
2803
      s.status = BUSY_STATE;
2804
      putShortMSB(s, header);
2805

    
2806
      /* Save the adler32 of the preset dictionary: */
2807
      if (s.strstart !== 0) {
2808
        putShortMSB(s, strm.adler >>> 16);
2809
        putShortMSB(s, strm.adler & 0xffff);
2810
      }
2811
      strm.adler = 1; // adler32(0L, Z_NULL, 0);
2812
    }
2813
  }
2814

    
2815
//#ifdef GZIP
2816
  if (s.status === EXTRA_STATE) {
2817
    if (s.gzhead.extra/* != Z_NULL*/) {
2818
      beg = s.pending;  /* start of bytes to update crc */
2819

    
2820
      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
2821
        if (s.pending === s.pending_buf_size) {
2822
          if (s.gzhead.hcrc && s.pending > beg) {
2823
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2824
          }
2825
          flush_pending(strm);
2826
          beg = s.pending;
2827
          if (s.pending === s.pending_buf_size) {
2828
            break;
2829
          }
2830
        }
2831
        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
2832
        s.gzindex++;
2833
      }
2834
      if (s.gzhead.hcrc && s.pending > beg) {
2835
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2836
      }
2837
      if (s.gzindex === s.gzhead.extra.length) {
2838
        s.gzindex = 0;
2839
        s.status = NAME_STATE;
2840
      }
2841
    }
2842
    else {
2843
      s.status = NAME_STATE;
2844
    }
2845
  }
2846
  if (s.status === NAME_STATE) {
2847
    if (s.gzhead.name/* != Z_NULL*/) {
2848
      beg = s.pending;  /* start of bytes to update crc */
2849
      //int val;
2850

    
2851
      do {
2852
        if (s.pending === s.pending_buf_size) {
2853
          if (s.gzhead.hcrc && s.pending > beg) {
2854
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2855
          }
2856
          flush_pending(strm);
2857
          beg = s.pending;
2858
          if (s.pending === s.pending_buf_size) {
2859
            val = 1;
2860
            break;
2861
          }
2862
        }
2863
        // JS specific: little magic to add zero terminator to end of string
2864
        if (s.gzindex < s.gzhead.name.length) {
2865
          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
2866
        } else {
2867
          val = 0;
2868
        }
2869
        put_byte(s, val);
2870
      } while (val !== 0);
2871

    
2872
      if (s.gzhead.hcrc && s.pending > beg) {
2873
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2874
      }
2875
      if (val === 0) {
2876
        s.gzindex = 0;
2877
        s.status = COMMENT_STATE;
2878
      }
2879
    }
2880
    else {
2881
      s.status = COMMENT_STATE;
2882
    }
2883
  }
2884
  if (s.status === COMMENT_STATE) {
2885
    if (s.gzhead.comment/* != Z_NULL*/) {
2886
      beg = s.pending;  /* start of bytes to update crc */
2887
      //int val;
2888

    
2889
      do {
2890
        if (s.pending === s.pending_buf_size) {
2891
          if (s.gzhead.hcrc && s.pending > beg) {
2892
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2893
          }
2894
          flush_pending(strm);
2895
          beg = s.pending;
2896
          if (s.pending === s.pending_buf_size) {
2897
            val = 1;
2898
            break;
2899
          }
2900
        }
2901
        // JS specific: little magic to add zero terminator to end of string
2902
        if (s.gzindex < s.gzhead.comment.length) {
2903
          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
2904
        } else {
2905
          val = 0;
2906
        }
2907
        put_byte(s, val);
2908
      } while (val !== 0);
2909

    
2910
      if (s.gzhead.hcrc && s.pending > beg) {
2911
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2912
      }
2913
      if (val === 0) {
2914
        s.status = HCRC_STATE;
2915
      }
2916
    }
2917
    else {
2918
      s.status = HCRC_STATE;
2919
    }
2920
  }
2921
  if (s.status === HCRC_STATE) {
2922
    if (s.gzhead.hcrc) {
2923
      if (s.pending + 2 > s.pending_buf_size) {
2924
        flush_pending(strm);
2925
      }
2926
      if (s.pending + 2 <= s.pending_buf_size) {
2927
        put_byte(s, strm.adler & 0xff);
2928
        put_byte(s, (strm.adler >> 8) & 0xff);
2929
        strm.adler = 0; //crc32(0L, Z_NULL, 0);
2930
        s.status = BUSY_STATE;
2931
      }
2932
    }
2933
    else {
2934
      s.status = BUSY_STATE;
2935
    }
2936
  }
2937
//#endif
2938

    
2939
  /* Flush as much pending output as possible */
2940
  if (s.pending !== 0) {
2941
    flush_pending(strm);
2942
    if (strm.avail_out === 0) {
2943
      /* Since avail_out is 0, deflate will be called again with
2944
       * more output space, but possibly with both pending and
2945
       * avail_in equal to zero. There won't be anything to do,
2946
       * but this is not an error situation so make sure we
2947
       * return OK instead of BUF_ERROR at next call of deflate:
2948
       */
2949
      s.last_flush = -1;
2950
      return Z_OK;
2951
    }
2952

    
2953
    /* Make sure there is something to do and avoid duplicate consecutive
2954
     * flushes. For repeated and useless calls with Z_FINISH, we keep
2955
     * returning Z_STREAM_END instead of Z_BUF_ERROR.
2956
     */
2957
  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
2958
    flush !== Z_FINISH) {
2959
    return err(strm, Z_BUF_ERROR);
2960
  }
2961

    
2962
  /* User must not provide more input after the first FINISH: */
2963
  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
2964
    return err(strm, Z_BUF_ERROR);
2965
  }
2966

    
2967
  /* Start a new block or continue the current one.
2968
   */
2969
  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
2970
    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
2971
    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
2972
      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
2973
        configuration_table[s.level].func(s, flush));
2974

    
2975
    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
2976
      s.status = FINISH_STATE;
2977
    }
2978
    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
2979
      if (strm.avail_out === 0) {
2980
        s.last_flush = -1;
2981
        /* avoid BUF_ERROR next call, see above */
2982
      }
2983
      return Z_OK;
2984
      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
2985
       * of deflate should use the same flush parameter to make sure
2986
       * that the flush is complete. So we don't have to output an
2987
       * empty block here, this will be done at next call. This also
2988
       * ensures that for a very small output buffer, we emit at most
2989
       * one empty block.
2990
       */
2991
    }
2992
    if (bstate === BS_BLOCK_DONE) {
2993
      if (flush === Z_PARTIAL_FLUSH) {
2994
        trees._tr_align(s);
2995
      }
2996
      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
2997

    
2998
        trees._tr_stored_block(s, 0, 0, false);
2999
        /* For a full flush, this empty block will be recognized
3000
         * as a special marker by inflate_sync().
3001
         */
3002
        if (flush === Z_FULL_FLUSH) {
3003
          /*** CLEAR_HASH(s); ***/             /* forget history */
3004
          zero(s.head); // Fill with NIL (= 0);
3005

    
3006
          if (s.lookahead === 0) {
3007
            s.strstart = 0;
3008
            s.block_start = 0;
3009
            s.insert = 0;
3010
          }
3011
        }
3012
      }
3013
      flush_pending(strm);
3014
      if (strm.avail_out === 0) {
3015
        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
3016
        return Z_OK;
3017
      }
3018
    }
3019
  }
3020
  //Assert(strm->avail_out > 0, "bug2");
3021
  //if (strm.avail_out <= 0) { throw new Error("bug2");}
3022

    
3023
  if (flush !== Z_FINISH) { return Z_OK; }
3024
  if (s.wrap <= 0) { return Z_STREAM_END; }
3025

    
3026
  /* Write the trailer */
3027
  if (s.wrap === 2) {
3028
    put_byte(s, strm.adler & 0xff);
3029
    put_byte(s, (strm.adler >> 8) & 0xff);
3030
    put_byte(s, (strm.adler >> 16) & 0xff);
3031
    put_byte(s, (strm.adler >> 24) & 0xff);
3032
    put_byte(s, strm.total_in & 0xff);
3033
    put_byte(s, (strm.total_in >> 8) & 0xff);
3034
    put_byte(s, (strm.total_in >> 16) & 0xff);
3035
    put_byte(s, (strm.total_in >> 24) & 0xff);
3036
  }
3037
  else
3038
  {
3039
    putShortMSB(s, strm.adler >>> 16);
3040
    putShortMSB(s, strm.adler & 0xffff);
3041
  }
3042

    
3043
  flush_pending(strm);
3044
  /* If avail_out is zero, the application will call deflate again
3045
   * to flush the rest.
3046
   */
3047
  if (s.wrap > 0) { s.wrap = -s.wrap; }
3048
  /* write the trailer only once! */
3049
  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
3050
}
3051

    
3052
function deflateEnd(strm) {
3053
  var status;
3054

    
3055
  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
3056
    return Z_STREAM_ERROR;
3057
  }
3058

    
3059
  status = strm.state.status;
3060
  if (status !== INIT_STATE &&
3061
    status !== EXTRA_STATE &&
3062
    status !== NAME_STATE &&
3063
    status !== COMMENT_STATE &&
3064
    status !== HCRC_STATE &&
3065
    status !== BUSY_STATE &&
3066
    status !== FINISH_STATE
3067
  ) {
3068
    return err(strm, Z_STREAM_ERROR);
3069
  }
3070

    
3071
  strm.state = null;
3072

    
3073
  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
3074
}
3075

    
3076

    
3077
/* =========================================================================
3078
 * Initializes the compression dictionary from the given byte
3079
 * sequence without producing any compressed output.
3080
 */
3081
function deflateSetDictionary(strm, dictionary) {
3082
  var dictLength = dictionary.length;
3083

    
3084
  var s;
3085
  var str, n;
3086
  var wrap;
3087
  var avail;
3088
  var next;
3089
  var input;
3090
  var tmpDict;
3091

    
3092
  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
3093
    return Z_STREAM_ERROR;
3094
  }
3095

    
3096
  s = strm.state;
3097
  wrap = s.wrap;
3098

    
3099
  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
3100
    return Z_STREAM_ERROR;
3101
  }
3102

    
3103
  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
3104
  if (wrap === 1) {
3105
    /* adler32(strm->adler, dictionary, dictLength); */
3106
    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
3107
  }
3108

    
3109
  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
3110

    
3111
  /* if dictionary would fill window, just replace the history */
3112
  if (dictLength >= s.w_size) {
3113
    if (wrap === 0) {            /* already empty otherwise */
3114
      /*** CLEAR_HASH(s); ***/
3115
      zero(s.head); // Fill with NIL (= 0);
3116
      s.strstart = 0;
3117
      s.block_start = 0;
3118
      s.insert = 0;
3119
    }
3120
    /* use the tail */
3121
    // dictionary = dictionary.slice(dictLength - s.w_size);
3122
    tmpDict = new utils.Buf8(s.w_size);
3123
    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
3124
    dictionary = tmpDict;
3125
    dictLength = s.w_size;
3126
  }
3127
  /* insert dictionary into window and hash */
3128
  avail = strm.avail_in;
3129
  next = strm.next_in;
3130
  input = strm.input;
3131
  strm.avail_in = dictLength;
3132
  strm.next_in = 0;
3133
  strm.input = dictionary;
3134
  fill_window(s);
3135
  while (s.lookahead >= MIN_MATCH) {
3136
    str = s.strstart;
3137
    n = s.lookahead - (MIN_MATCH - 1);
3138
    do {
3139
      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
3140
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
3141

    
3142
      s.prev[str & s.w_mask] = s.head[s.ins_h];
3143

    
3144
      s.head[s.ins_h] = str;
3145
      str++;
3146
    } while (--n);
3147
    s.strstart = str;
3148
    s.lookahead = MIN_MATCH - 1;
3149
    fill_window(s);
3150
  }
3151
  s.strstart += s.lookahead;
3152
  s.block_start = s.strstart;
3153
  s.insert = s.lookahead;
3154
  s.lookahead = 0;
3155
  s.match_length = s.prev_length = MIN_MATCH - 1;
3156
  s.match_available = 0;
3157
  strm.next_in = next;
3158
  strm.input = input;
3159
  strm.avail_in = avail;
3160
  s.wrap = wrap;
3161
  return Z_OK;
3162
}
3163

    
3164

    
3165
exports.deflateInit = deflateInit;
3166
exports.deflateInit2 = deflateInit2;
3167
exports.deflateReset = deflateReset;
3168
exports.deflateResetKeep = deflateResetKeep;
3169
exports.deflateSetHeader = deflateSetHeader;
3170
exports.deflate = deflate;
3171
exports.deflateEnd = deflateEnd;
3172
exports.deflateSetDictionary = deflateSetDictionary;
3173
exports.deflateInfo = 'pako deflate (from Nodeca project)';
3174

    
3175
/* Not implemented
3176
exports.deflateBound = deflateBound;
3177
exports.deflateCopy = deflateCopy;
3178
exports.deflateParams = deflateParams;
3179
exports.deflatePending = deflatePending;
3180
exports.deflatePrime = deflatePrime;
3181
exports.deflateTune = deflateTune;
3182
*/
3183

    
3184
},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(require,module,exports){
3185
'use strict';
3186

    
3187
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
3188
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
3189
//
3190
// This software is provided 'as-is', without any express or implied
3191
// warranty. In no event will the authors be held liable for any damages
3192
// arising from the use of this software.
3193
//
3194
// Permission is granted to anyone to use this software for any purpose,
3195
// including commercial applications, and to alter it and redistribute it
3196
// freely, subject to the following restrictions:
3197
//
3198
// 1. The origin of this software must not be misrepresented; you must not
3199
//   claim that you wrote the original software. If you use this software
3200
//   in a product, an acknowledgment in the product documentation would be
3201
//   appreciated but is not required.
3202
// 2. Altered source versions must be plainly marked as such, and must not be
3203
//   misrepresented as being the original software.
3204
// 3. This notice may not be removed or altered from any source distribution.
3205

    
3206
function GZheader() {
3207
  /* true if compressed data believed to be text */
3208
  this.text       = 0;
3209
  /* modification time */
3210
  this.time       = 0;
3211
  /* extra flags (not used when writing a gzip file) */
3212
  this.xflags     = 0;
3213
  /* operating system */
3214
  this.os         = 0;
3215
  /* pointer to extra field or Z_NULL if none */
3216
  this.extra      = null;
3217
  /* extra field length (valid if extra != Z_NULL) */
3218
  this.extra_len  = 0; // Actually, we don't need it in JS,
3219
                       // but leave for few code modifications
3220

    
3221
  //
3222
  // Setup limits is not necessary because in js we should not preallocate memory
3223
  // for inflate use constant limit in 65536 bytes
3224
  //
3225

    
3226
  /* space at extra (only when reading header) */
3227
  // this.extra_max  = 0;
3228
  /* pointer to zero-terminated file name or Z_NULL */
3229
  this.name       = '';
3230
  /* space at name (only when reading header) */
3231
  // this.name_max   = 0;
3232
  /* pointer to zero-terminated comment or Z_NULL */
3233
  this.comment    = '';
3234
  /* space at comment (only when reading header) */
3235
  // this.comm_max   = 0;
3236
  /* true if there was or will be a header crc */
3237
  this.hcrc       = 0;
3238
  /* true when done reading gzip header (not used when writing a gzip file) */
3239
  this.done       = false;
3240
}
3241

    
3242
module.exports = GZheader;
3243

    
3244
},{}],10:[function(require,module,exports){
3245
'use strict';
3246

    
3247
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
3248
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
3249
//
3250
// This software is provided 'as-is', without any express or implied
3251
// warranty. In no event will the authors be held liable for any damages
3252
// arising from the use of this software.
3253
//
3254
// Permission is granted to anyone to use this software for any purpose,
3255
// including commercial applications, and to alter it and redistribute it
3256
// freely, subject to the following restrictions:
3257
//
3258
// 1. The origin of this software must not be misrepresented; you must not
3259
//   claim that you wrote the original software. If you use this software
3260
//   in a product, an acknowledgment in the product documentation would be
3261
//   appreciated but is not required.
3262
// 2. Altered source versions must be plainly marked as such, and must not be
3263
//   misrepresented as being the original software.
3264
// 3. This notice may not be removed or altered from any source distribution.
3265

    
3266
// See state defs from inflate.js
3267
var BAD = 30;       /* got a data error -- remain here until reset */
3268
var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
3269

    
3270
/*
3271
   Decode literal, length, and distance codes and write out the resulting
3272
   literal and match bytes until either not enough input or output is
3273
   available, an end-of-block is encountered, or a data error is encountered.
3274
   When large enough input and output buffers are supplied to inflate(), for
3275
   example, a 16K input buffer and a 64K output buffer, more than 95% of the
3276
   inflate execution time is spent in this routine.
3277

    
3278
   Entry assumptions:
3279

    
3280
        state.mode === LEN
3281
        strm.avail_in >= 6
3282
        strm.avail_out >= 258
3283
        start >= strm.avail_out
3284
        state.bits < 8
3285

    
3286
   On return, state.mode is one of:
3287

    
3288
        LEN -- ran out of enough output space or enough available input
3289
        TYPE -- reached end of block code, inflate() to interpret next block
3290
        BAD -- error in block data
3291

    
3292
   Notes:
3293

    
3294
    - The maximum input bits used by a length/distance pair is 15 bits for the
3295
      length code, 5 bits for the length extra, 15 bits for the distance code,
3296
      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
3297
      Therefore if strm.avail_in >= 6, then there is enough input to avoid
3298
      checking for available input while decoding.
3299

    
3300
    - The maximum bytes that a single length/distance pair can output is 258
3301
      bytes, which is the maximum length that can be coded.  inflate_fast()
3302
      requires strm.avail_out >= 258 for each loop to avoid checking for
3303
      output space.
3304
 */
3305
module.exports = function inflate_fast(strm, start) {
3306
  var state;
3307
  var _in;                    /* local strm.input */
3308
  var last;                   /* have enough input while in < last */
3309
  var _out;                   /* local strm.output */
3310
  var beg;                    /* inflate()'s initial strm.output */
3311
  var end;                    /* while out < end, enough space available */
3312
//#ifdef INFLATE_STRICT
3313
  var dmax;                   /* maximum distance from zlib header */
3314
//#endif
3315
  var wsize;                  /* window size or zero if not using window */
3316
  var whave;                  /* valid bytes in the window */
3317
  var wnext;                  /* window write index */
3318
  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
3319
  var s_window;               /* allocated sliding window, if wsize != 0 */
3320
  var hold;                   /* local strm.hold */
3321
  var bits;                   /* local strm.bits */
3322
  var lcode;                  /* local strm.lencode */
3323
  var dcode;                  /* local strm.distcode */
3324
  var lmask;                  /* mask for first level of length codes */
3325
  var dmask;                  /* mask for first level of distance codes */
3326
  var here;                   /* retrieved table entry */
3327
  var op;                     /* code bits, operation, extra bits, or */
3328
                              /*  window position, window bytes to copy */
3329
  var len;                    /* match length, unused bytes */
3330
  var dist;                   /* match distance */
3331
  var from;                   /* where to copy match from */
3332
  var from_source;
3333

    
3334

    
3335
  var input, output; // JS specific, because we have no pointers
3336

    
3337
  /* copy state to local variables */
3338
  state = strm.state;
3339
  //here = state.here;
3340
  _in = strm.next_in;
3341
  input = strm.input;
3342
  last = _in + (strm.avail_in - 5);
3343
  _out = strm.next_out;
3344
  output = strm.output;
3345
  beg = _out - (start - strm.avail_out);
3346
  end = _out + (strm.avail_out - 257);
3347
//#ifdef INFLATE_STRICT
3348
  dmax = state.dmax;
3349
//#endif
3350
  wsize = state.wsize;
3351
  whave = state.whave;
3352
  wnext = state.wnext;
3353
  s_window = state.window;
3354
  hold = state.hold;
3355
  bits = state.bits;
3356
  lcode = state.lencode;
3357
  dcode = state.distcode;
3358
  lmask = (1 << state.lenbits) - 1;
3359
  dmask = (1 << state.distbits) - 1;
3360

    
3361

    
3362
  /* decode literals and length/distances until end-of-block or not enough
3363
     input data or output space */
3364

    
3365
  top:
3366
  do {
3367
    if (bits < 15) {
3368
      hold += input[_in++] << bits;
3369
      bits += 8;
3370
      hold += input[_in++] << bits;
3371
      bits += 8;
3372
    }
3373

    
3374
    here = lcode[hold & lmask];
3375

    
3376
    dolen:
3377
    for (;;) { // Goto emulation
3378
      op = here >>> 24/*here.bits*/;
3379
      hold >>>= op;
3380
      bits -= op;
3381
      op = (here >>> 16) & 0xff/*here.op*/;
3382
      if (op === 0) {                          /* literal */
3383
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
3384
        //        "inflate:         literal '%c'\n" :
3385
        //        "inflate:         literal 0x%02x\n", here.val));
3386
        output[_out++] = here & 0xffff/*here.val*/;
3387
      }
3388
      else if (op & 16) {                     /* length base */
3389
        len = here & 0xffff/*here.val*/;
3390
        op &= 15;                           /* number of extra bits */
3391
        if (op) {
3392
          if (bits < op) {
3393
            hold += input[_in++] << bits;
3394
            bits += 8;
3395
          }
3396
          len += hold & ((1 << op) - 1);
3397
          hold >>>= op;
3398
          bits -= op;
3399
        }
3400
        //Tracevv((stderr, "inflate:         length %u\n", len));
3401
        if (bits < 15) {
3402
          hold += input[_in++] << bits;
3403
          bits += 8;
3404
          hold += input[_in++] << bits;
3405
          bits += 8;
3406
        }
3407
        here = dcode[hold & dmask];
3408

    
3409
        dodist:
3410
        for (;;) { // goto emulation
3411
          op = here >>> 24/*here.bits*/;
3412
          hold >>>= op;
3413
          bits -= op;
3414
          op = (here >>> 16) & 0xff/*here.op*/;
3415

    
3416
          if (op & 16) {                      /* distance base */
3417
            dist = here & 0xffff/*here.val*/;
3418
            op &= 15;                       /* number of extra bits */
3419
            if (bits < op) {
3420
              hold += input[_in++] << bits;
3421
              bits += 8;
3422
              if (bits < op) {
3423
                hold += input[_in++] << bits;
3424
                bits += 8;
3425
              }
3426
            }
3427
            dist += hold & ((1 << op) - 1);
3428
//#ifdef INFLATE_STRICT
3429
            if (dist > dmax) {
3430
              strm.msg = 'invalid distance too far back';
3431
              state.mode = BAD;
3432
              break top;
3433
            }
3434
//#endif
3435
            hold >>>= op;
3436
            bits -= op;
3437
            //Tracevv((stderr, "inflate:         distance %u\n", dist));
3438
            op = _out - beg;                /* max distance in output */
3439
            if (dist > op) {                /* see if copy from window */
3440
              op = dist - op;               /* distance back in window */
3441
              if (op > whave) {
3442
                if (state.sane) {
3443
                  strm.msg = 'invalid distance too far back';
3444
                  state.mode = BAD;
3445
                  break top;
3446
                }
3447

    
3448
// (!) This block is disabled in zlib defaults,
3449
// don't enable it for binary compatibility
3450
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
3451
//                if (len <= op - whave) {
3452
//                  do {
3453
//                    output[_out++] = 0;
3454
//                  } while (--len);
3455
//                  continue top;
3456
//                }
3457
//                len -= op - whave;
3458
//                do {
3459
//                  output[_out++] = 0;
3460
//                } while (--op > whave);
3461
//                if (op === 0) {
3462
//                  from = _out - dist;
3463
//                  do {
3464
//                    output[_out++] = output[from++];
3465
//                  } while (--len);
3466
//                  continue top;
3467
//                }
3468
//#endif
3469
              }
3470
              from = 0; // window index
3471
              from_source = s_window;
3472
              if (wnext === 0) {           /* very common case */
3473
                from += wsize - op;
3474
                if (op < len) {         /* some from window */
3475
                  len -= op;
3476
                  do {
3477
                    output[_out++] = s_window[from++];
3478
                  } while (--op);
3479
                  from = _out - dist;  /* rest from output */
3480
                  from_source = output;
3481
                }
3482
              }
3483
              else if (wnext < op) {      /* wrap around window */
3484
                from += wsize + wnext - op;
3485
                op -= wnext;
3486
                if (op < len) {         /* some from end of window */
3487
                  len -= op;
3488
                  do {
3489
                    output[_out++] = s_window[from++];
3490
                  } while (--op);
3491
                  from = 0;
3492
                  if (wnext < len) {  /* some from start of window */
3493
                    op = wnext;
3494
                    len -= op;
3495
                    do {
3496
                      output[_out++] = s_window[from++];
3497
                    } while (--op);
3498
                    from = _out - dist;      /* rest from output */
3499
                    from_source = output;
3500
                  }
3501
                }
3502
              }
3503
              else {                      /* contiguous in window */
3504
                from += wnext - op;
3505
                if (op < len) {         /* some from window */
3506
                  len -= op;
3507
                  do {
3508
                    output[_out++] = s_window[from++];
3509
                  } while (--op);
3510
                  from = _out - dist;  /* rest from output */
3511
                  from_source = output;
3512
                }
3513
              }
3514
              while (len > 2) {
3515
                output[_out++] = from_source[from++];
3516
                output[_out++] = from_source[from++];
3517
                output[_out++] = from_source[from++];
3518
                len -= 3;
3519
              }
3520
              if (len) {
3521
                output[_out++] = from_source[from++];
3522
                if (len > 1) {
3523
                  output[_out++] = from_source[from++];
3524
                }
3525
              }
3526
            }
3527
            else {
3528
              from = _out - dist;          /* copy direct from output */
3529
              do {                        /* minimum length is three */
3530
                output[_out++] = output[from++];
3531
                output[_out++] = output[from++];
3532
                output[_out++] = output[from++];
3533
                len -= 3;
3534
              } while (len > 2);
3535
              if (len) {
3536
                output[_out++] = output[from++];
3537
                if (len > 1) {
3538
                  output[_out++] = output[from++];
3539
                }
3540
              }
3541
            }
3542
          }
3543
          else if ((op & 64) === 0) {          /* 2nd level distance code */
3544
            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3545
            continue dodist;
3546
          }
3547
          else {
3548
            strm.msg = 'invalid distance code';
3549
            state.mode = BAD;
3550
            break top;
3551
          }
3552

    
3553
          break; // need to emulate goto via "continue"
3554
        }
3555
      }
3556
      else if ((op & 64) === 0) {              /* 2nd level length code */
3557
        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3558
        continue dolen;
3559
      }
3560
      else if (op & 32) {                     /* end-of-block */
3561
        //Tracevv((stderr, "inflate:         end of block\n"));
3562
        state.mode = TYPE;
3563
        break top;
3564
      }
3565
      else {
3566
        strm.msg = 'invalid literal/length code';
3567
        state.mode = BAD;
3568
        break top;
3569
      }
3570

    
3571
      break; // need to emulate goto via "continue"
3572
    }
3573
  } while (_in < last && _out < end);
3574

    
3575
  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
3576
  len = bits >> 3;
3577
  _in -= len;
3578
  bits -= len << 3;
3579
  hold &= (1 << bits) - 1;
3580

    
3581
  /* update state and return */
3582
  strm.next_in = _in;
3583
  strm.next_out = _out;
3584
  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
3585
  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
3586
  state.hold = hold;
3587
  state.bits = bits;
3588
  return;
3589
};
3590

    
3591
},{}],11:[function(require,module,exports){
3592
'use strict';
3593

    
3594
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
3595
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
3596
//
3597
// This software is provided 'as-is', without any express or implied
3598
// warranty. In no event will the authors be held liable for any damages
3599
// arising from the use of this software.
3600
//
3601
// Permission is granted to anyone to use this software for any purpose,
3602
// including commercial applications, and to alter it and redistribute it
3603
// freely, subject to the following restrictions:
3604
//
3605
// 1. The origin of this software must not be misrepresented; you must not
3606
//   claim that you wrote the original software. If you use this software
3607
//   in a product, an acknowledgment in the product documentation would be
3608
//   appreciated but is not required.
3609
// 2. Altered source versions must be plainly marked as such, and must not be
3610
//   misrepresented as being the original software.
3611
// 3. This notice may not be removed or altered from any source distribution.
3612

    
3613
var utils         = require('../utils/common');
3614
var adler32       = require('./adler32');
3615
var crc32         = require('./crc32');
3616
var inflate_fast  = require('./inffast');
3617
var inflate_table = require('./inftrees');
3618

    
3619
var CODES = 0;
3620
var LENS = 1;
3621
var DISTS = 2;
3622

    
3623
/* Public constants ==========================================================*/
3624
/* ===========================================================================*/
3625

    
3626

    
3627
/* Allowed flush values; see deflate() and inflate() below for details */
3628
//var Z_NO_FLUSH      = 0;
3629
//var Z_PARTIAL_FLUSH = 1;
3630
//var Z_SYNC_FLUSH    = 2;
3631
//var Z_FULL_FLUSH    = 3;
3632
var Z_FINISH        = 4;
3633
var Z_BLOCK         = 5;
3634
var Z_TREES         = 6;
3635

    
3636

    
3637
/* Return codes for the compression/decompression functions. Negative values
3638
 * are errors, positive values are used for special but normal events.
3639
 */
3640
var Z_OK            = 0;
3641
var Z_STREAM_END    = 1;
3642
var Z_NEED_DICT     = 2;
3643
//var Z_ERRNO         = -1;
3644
var Z_STREAM_ERROR  = -2;
3645
var Z_DATA_ERROR    = -3;
3646
var Z_MEM_ERROR     = -4;
3647
var Z_BUF_ERROR     = -5;
3648
//var Z_VERSION_ERROR = -6;
3649

    
3650
/* The deflate compression method */
3651
var Z_DEFLATED  = 8;
3652

    
3653

    
3654
/* STATES ====================================================================*/
3655
/* ===========================================================================*/
3656

    
3657

    
3658
var    HEAD = 1;       /* i: waiting for magic header */
3659
var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
3660
var    TIME = 3;       /* i: waiting for modification time (gzip) */
3661
var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
3662
var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
3663
var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
3664
var    NAME = 7;       /* i: waiting for end of file name (gzip) */
3665
var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
3666
var    HCRC = 9;       /* i: waiting for header crc (gzip) */
3667
var    DICTID = 10;    /* i: waiting for dictionary check value */
3668
var    DICT = 11;      /* waiting for inflateSetDictionary() call */
3669
var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
3670
var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
3671
var        STORED = 14;    /* i: waiting for stored size (length and complement) */
3672
var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
3673
var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
3674
var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
3675
var        LENLENS = 18;   /* i: waiting for code length code lengths */
3676
var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
3677
var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
3678
var            LEN = 21;       /* i: waiting for length/lit/eob code */
3679
var            LENEXT = 22;    /* i: waiting for length extra bits */
3680
var            DIST = 23;      /* i: waiting for distance code */
3681
var            DISTEXT = 24;   /* i: waiting for distance extra bits */
3682
var            MATCH = 25;     /* o: waiting for output space to copy string */
3683
var            LIT = 26;       /* o: waiting for output space to write literal */
3684
var    CHECK = 27;     /* i: waiting for 32-bit check value */
3685
var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
3686
var    DONE = 29;      /* finished check, done -- remain here until reset */
3687
var    BAD = 30;       /* got a data error -- remain here until reset */
3688
var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
3689
var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
3690

    
3691
/* ===========================================================================*/
3692

    
3693

    
3694

    
3695
var ENOUGH_LENS = 852;
3696
var ENOUGH_DISTS = 592;
3697
//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
3698

    
3699
var MAX_WBITS = 15;
3700
/* 32K LZ77 window */
3701
var DEF_WBITS = MAX_WBITS;
3702

    
3703

    
3704
function zswap32(q) {
3705
  return  (((q >>> 24) & 0xff) +
3706
          ((q >>> 8) & 0xff00) +
3707
          ((q & 0xff00) << 8) +
3708
          ((q & 0xff) << 24));
3709
}
3710

    
3711

    
3712
function InflateState() {
3713
  this.mode = 0;             /* current inflate mode */
3714
  this.last = false;          /* true if processing last block */
3715
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
3716
  this.havedict = false;      /* true if dictionary provided */
3717
  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
3718
  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
3719
  this.check = 0;             /* protected copy of check value */
3720
  this.total = 0;             /* protected copy of output count */
3721
  // TODO: may be {}
3722
  this.head = null;           /* where to save gzip header information */
3723

    
3724
  /* sliding window */
3725
  this.wbits = 0;             /* log base 2 of requested window size */
3726
  this.wsize = 0;             /* window size or zero if not using window */
3727
  this.whave = 0;             /* valid bytes in the window */
3728
  this.wnext = 0;             /* window write index */
3729
  this.window = null;         /* allocated sliding window, if needed */
3730

    
3731
  /* bit accumulator */
3732
  this.hold = 0;              /* input bit accumulator */
3733
  this.bits = 0;              /* number of bits in "in" */
3734

    
3735
  /* for string and stored block copying */
3736
  this.length = 0;            /* literal or length of data to copy */
3737
  this.offset = 0;            /* distance back to copy string from */
3738

    
3739
  /* for table and code decoding */
3740
  this.extra = 0;             /* extra bits needed */
3741

    
3742
  /* fixed and dynamic code tables */
3743
  this.lencode = null;          /* starting table for length/literal codes */
3744
  this.distcode = null;         /* starting table for distance codes */
3745
  this.lenbits = 0;           /* index bits for lencode */
3746
  this.distbits = 0;          /* index bits for distcode */
3747

    
3748
  /* dynamic table building */
3749
  this.ncode = 0;             /* number of code length code lengths */
3750
  this.nlen = 0;              /* number of length code lengths */
3751
  this.ndist = 0;             /* number of distance code lengths */
3752
  this.have = 0;              /* number of code lengths in lens[] */
3753
  this.next = null;              /* next available space in codes[] */
3754

    
3755
  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
3756
  this.work = new utils.Buf16(288); /* work area for code table building */
3757

    
3758
  /*
3759
   because we don't have pointers in js, we use lencode and distcode directly
3760
   as buffers so we don't need codes
3761
  */
3762
  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
3763
  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
3764
  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
3765
  this.sane = 0;                   /* if false, allow invalid distance too far */
3766
  this.back = 0;                   /* bits back of last unprocessed length/lit */
3767
  this.was = 0;                    /* initial length of match */
3768
}
3769

    
3770
function inflateResetKeep(strm) {
3771
  var state;
3772

    
3773
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3774
  state = strm.state;
3775
  strm.total_in = strm.total_out = state.total = 0;
3776
  strm.msg = ''; /*Z_NULL*/
3777
  if (state.wrap) {       /* to support ill-conceived Java test suite */
3778
    strm.adler = state.wrap & 1;
3779
  }
3780
  state.mode = HEAD;
3781
  state.last = 0;
3782
  state.havedict = 0;
3783
  state.dmax = 32768;
3784
  state.head = null/*Z_NULL*/;
3785
  state.hold = 0;
3786
  state.bits = 0;
3787
  //state.lencode = state.distcode = state.next = state.codes;
3788
  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
3789
  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
3790

    
3791
  state.sane = 1;
3792
  state.back = -1;
3793
  //Tracev((stderr, "inflate: reset\n"));
3794
  return Z_OK;
3795
}
3796

    
3797
function inflateReset(strm) {
3798
  var state;
3799

    
3800
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3801
  state = strm.state;
3802
  state.wsize = 0;
3803
  state.whave = 0;
3804
  state.wnext = 0;
3805
  return inflateResetKeep(strm);
3806

    
3807
}
3808

    
3809
function inflateReset2(strm, windowBits) {
3810
  var wrap;
3811
  var state;
3812

    
3813
  /* get the state */
3814
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3815
  state = strm.state;
3816

    
3817
  /* extract wrap request from windowBits parameter */
3818
  if (windowBits < 0) {
3819
    wrap = 0;
3820
    windowBits = -windowBits;
3821
  }
3822
  else {
3823
    wrap = (windowBits >> 4) + 1;
3824
    if (windowBits < 48) {
3825
      windowBits &= 15;
3826
    }
3827
  }
3828

    
3829
  /* set number of window bits, free window if different */
3830
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
3831
    return Z_STREAM_ERROR;
3832
  }
3833
  if (state.window !== null && state.wbits !== windowBits) {
3834
    state.window = null;
3835
  }
3836

    
3837
  /* update state and reset the rest of it */
3838
  state.wrap = wrap;
3839
  state.wbits = windowBits;
3840
  return inflateReset(strm);
3841
}
3842

    
3843
function inflateInit2(strm, windowBits) {
3844
  var ret;
3845
  var state;
3846

    
3847
  if (!strm) { return Z_STREAM_ERROR; }
3848
  //strm.msg = Z_NULL;                 /* in case we return an error */
3849

    
3850
  state = new InflateState();
3851

    
3852
  //if (state === Z_NULL) return Z_MEM_ERROR;
3853
  //Tracev((stderr, "inflate: allocated\n"));
3854
  strm.state = state;
3855
  state.window = null/*Z_NULL*/;
3856
  ret = inflateReset2(strm, windowBits);
3857
  if (ret !== Z_OK) {
3858
    strm.state = null/*Z_NULL*/;
3859
  }
3860
  return ret;
3861
}
3862

    
3863
function inflateInit(strm) {
3864
  return inflateInit2(strm, DEF_WBITS);
3865
}
3866

    
3867

    
3868
/*
3869
 Return state with length and distance decoding tables and index sizes set to
3870
 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
3871
 If BUILDFIXED is defined, then instead this routine builds the tables the
3872
 first time it's called, and returns those tables the first time and
3873
 thereafter.  This reduces the size of the code by about 2K bytes, in
3874
 exchange for a little execution time.  However, BUILDFIXED should not be
3875
 used for threaded applications, since the rewriting of the tables and virgin
3876
 may not be thread-safe.
3877
 */
3878
var virgin = true;
3879

    
3880
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
3881

    
3882
function fixedtables(state) {
3883
  /* build fixed huffman tables if first call (may not be thread safe) */
3884
  if (virgin) {
3885
    var sym;
3886

    
3887
    lenfix = new utils.Buf32(512);
3888
    distfix = new utils.Buf32(32);
3889

    
3890
    /* literal/length table */
3891
    sym = 0;
3892
    while (sym < 144) { state.lens[sym++] = 8; }
3893
    while (sym < 256) { state.lens[sym++] = 9; }
3894
    while (sym < 280) { state.lens[sym++] = 7; }
3895
    while (sym < 288) { state.lens[sym++] = 8; }
3896

    
3897
    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
3898

    
3899
    /* distance table */
3900
    sym = 0;
3901
    while (sym < 32) { state.lens[sym++] = 5; }
3902

    
3903
    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
3904

    
3905
    /* do this just once */
3906
    virgin = false;
3907
  }
3908

    
3909
  state.lencode = lenfix;
3910
  state.lenbits = 9;
3911
  state.distcode = distfix;
3912
  state.distbits = 5;
3913
}
3914

    
3915

    
3916
/*
3917
 Update the window with the last wsize (normally 32K) bytes written before
3918
 returning.  If window does not exist yet, create it.  This is only called
3919
 when a window is already in use, or when output has been written during this
3920
 inflate call, but the end of the deflate stream has not been reached yet.
3921
 It is also called to create a window for dictionary data when a dictionary
3922
 is loaded.
3923

    
3924
 Providing output buffers larger than 32K to inflate() should provide a speed
3925
 advantage, since only the last 32K of output is copied to the sliding window
3926
 upon return from inflate(), and since all distances after the first 32K of
3927
 output will fall in the output data, making match copies simpler and faster.
3928
 The advantage may be dependent on the size of the processor's data caches.
3929
 */
3930
function updatewindow(strm, src, end, copy) {
3931
  var dist;
3932
  var state = strm.state;
3933

    
3934
  /* if it hasn't been done already, allocate space for the window */
3935
  if (state.window === null) {
3936
    state.wsize = 1 << state.wbits;
3937
    state.wnext = 0;
3938
    state.whave = 0;
3939

    
3940
    state.window = new utils.Buf8(state.wsize);
3941
  }
3942

    
3943
  /* copy state->wsize or less output bytes into the circular window */
3944
  if (copy >= state.wsize) {
3945
    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
3946
    state.wnext = 0;
3947
    state.whave = state.wsize;
3948
  }
3949
  else {
3950
    dist = state.wsize - state.wnext;
3951
    if (dist > copy) {
3952
      dist = copy;
3953
    }
3954
    //zmemcpy(state->window + state->wnext, end - copy, dist);
3955
    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
3956
    copy -= dist;
3957
    if (copy) {
3958
      //zmemcpy(state->window, end - copy, copy);
3959
      utils.arraySet(state.window, src, end - copy, copy, 0);
3960
      state.wnext = copy;
3961
      state.whave = state.wsize;
3962
    }
3963
    else {
3964
      state.wnext += dist;
3965
      if (state.wnext === state.wsize) { state.wnext = 0; }
3966
      if (state.whave < state.wsize) { state.whave += dist; }
3967
    }
3968
  }
3969
  return 0;
3970
}
3971

    
3972
function inflate(strm, flush) {
3973
  var state;
3974
  var input, output;          // input/output buffers
3975
  var next;                   /* next input INDEX */
3976
  var put;                    /* next output INDEX */
3977
  var have, left;             /* available input and output */
3978
  var hold;                   /* bit buffer */
3979
  var bits;                   /* bits in bit buffer */
3980
  var _in, _out;              /* save starting available input and output */
3981
  var copy;                   /* number of stored or match bytes to copy */
3982
  var from;                   /* where to copy match bytes from */
3983
  var from_source;
3984
  var here = 0;               /* current decoding table entry */
3985
  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
3986
  //var last;                   /* parent table entry */
3987
  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
3988
  var len;                    /* length to copy for repeats, bits to drop */
3989
  var ret;                    /* return code */
3990
  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
3991
  var opts;
3992

    
3993
  var n; // temporary var for NEED_BITS
3994

    
3995
  var order = /* permutation of code lengths */
3996
    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
3997

    
3998

    
3999
  if (!strm || !strm.state || !strm.output ||
4000
      (!strm.input && strm.avail_in !== 0)) {
4001
    return Z_STREAM_ERROR;
4002
  }
4003

    
4004
  state = strm.state;
4005
  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
4006

    
4007

    
4008
  //--- LOAD() ---
4009
  put = strm.next_out;
4010
  output = strm.output;
4011
  left = strm.avail_out;
4012
  next = strm.next_in;
4013
  input = strm.input;
4014
  have = strm.avail_in;
4015
  hold = state.hold;
4016
  bits = state.bits;
4017
  //---
4018

    
4019
  _in = have;
4020
  _out = left;
4021
  ret = Z_OK;
4022

    
4023
  inf_leave: // goto emulation
4024
  for (;;) {
4025
    switch (state.mode) {
4026
      case HEAD:
4027
        if (state.wrap === 0) {
4028
          state.mode = TYPEDO;
4029
          break;
4030
        }
4031
        //=== NEEDBITS(16);
4032
        while (bits < 16) {
4033
          if (have === 0) { break inf_leave; }
4034
          have--;
4035
          hold += input[next++] << bits;
4036
          bits += 8;
4037
        }
4038
        //===//
4039
        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
4040
          state.check = 0/*crc32(0L, Z_NULL, 0)*/;
4041
          //=== CRC2(state.check, hold);
4042
          hbuf[0] = hold & 0xff;
4043
          hbuf[1] = (hold >>> 8) & 0xff;
4044
          state.check = crc32(state.check, hbuf, 2, 0);
4045
          //===//
4046

    
4047
          //=== INITBITS();
4048
          hold = 0;
4049
          bits = 0;
4050
          //===//
4051
          state.mode = FLAGS;
4052
          break;
4053
        }
4054
        state.flags = 0;           /* expect zlib header */
4055
        if (state.head) {
4056
          state.head.done = false;
4057
        }
4058
        if (!(state.wrap & 1) ||   /* check if zlib header allowed */
4059
          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
4060
          strm.msg = 'incorrect header check';
4061
          state.mode = BAD;
4062
          break;
4063
        }
4064
        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
4065
          strm.msg = 'unknown compression method';
4066
          state.mode = BAD;
4067
          break;
4068
        }
4069
        //--- DROPBITS(4) ---//
4070
        hold >>>= 4;
4071
        bits -= 4;
4072
        //---//
4073
        len = (hold & 0x0f)/*BITS(4)*/ + 8;
4074
        if (state.wbits === 0) {
4075
          state.wbits = len;
4076
        }
4077
        else if (len > state.wbits) {
4078
          strm.msg = 'invalid window size';
4079
          state.mode = BAD;
4080
          break;
4081
        }
4082
        state.dmax = 1 << len;
4083
        //Tracev((stderr, "inflate:   zlib header ok\n"));
4084
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
4085
        state.mode = hold & 0x200 ? DICTID : TYPE;
4086
        //=== INITBITS();
4087
        hold = 0;
4088
        bits = 0;
4089
        //===//
4090
        break;
4091
      case FLAGS:
4092
        //=== NEEDBITS(16); */
4093
        while (bits < 16) {
4094
          if (have === 0) { break inf_leave; }
4095
          have--;
4096
          hold += input[next++] << bits;
4097
          bits += 8;
4098
        }
4099
        //===//
4100
        state.flags = hold;
4101
        if ((state.flags & 0xff) !== Z_DEFLATED) {
4102
          strm.msg = 'unknown compression method';
4103
          state.mode = BAD;
4104
          break;
4105
        }
4106
        if (state.flags & 0xe000) {
4107
          strm.msg = 'unknown header flags set';
4108
          state.mode = BAD;
4109
          break;
4110
        }
4111
        if (state.head) {
4112
          state.head.text = ((hold >> 8) & 1);
4113
        }
4114
        if (state.flags & 0x0200) {
4115
          //=== CRC2(state.check, hold);
4116
          hbuf[0] = hold & 0xff;
4117
          hbuf[1] = (hold >>> 8) & 0xff;
4118
          state.check = crc32(state.check, hbuf, 2, 0);
4119
          //===//
4120
        }
4121
        //=== INITBITS();
4122
        hold = 0;
4123
        bits = 0;
4124
        //===//
4125
        state.mode = TIME;
4126
        /* falls through */
4127
      case TIME:
4128
        //=== NEEDBITS(32); */
4129
        while (bits < 32) {
4130
          if (have === 0) { break inf_leave; }
4131
          have--;
4132
          hold += input[next++] << bits;
4133
          bits += 8;
4134
        }
4135
        //===//
4136
        if (state.head) {
4137
          state.head.time = hold;
4138
        }
4139
        if (state.flags & 0x0200) {
4140
          //=== CRC4(state.check, hold)
4141
          hbuf[0] = hold & 0xff;
4142
          hbuf[1] = (hold >>> 8) & 0xff;
4143
          hbuf[2] = (hold >>> 16) & 0xff;
4144
          hbuf[3] = (hold >>> 24) & 0xff;
4145
          state.check = crc32(state.check, hbuf, 4, 0);
4146
          //===
4147
        }
4148
        //=== INITBITS();
4149
        hold = 0;
4150
        bits = 0;
4151
        //===//
4152
        state.mode = OS;
4153
        /* falls through */
4154
      case OS:
4155
        //=== NEEDBITS(16); */
4156
        while (bits < 16) {
4157
          if (have === 0) { break inf_leave; }
4158
          have--;
4159
          hold += input[next++] << bits;
4160
          bits += 8;
4161
        }
4162
        //===//
4163
        if (state.head) {
4164
          state.head.xflags = (hold & 0xff);
4165
          state.head.os = (hold >> 8);
4166
        }
4167
        if (state.flags & 0x0200) {
4168
          //=== CRC2(state.check, hold);
4169
          hbuf[0] = hold & 0xff;
4170
          hbuf[1] = (hold >>> 8) & 0xff;
4171
          state.check = crc32(state.check, hbuf, 2, 0);
4172
          //===//
4173
        }
4174
        //=== INITBITS();
4175
        hold = 0;
4176
        bits = 0;
4177
        //===//
4178
        state.mode = EXLEN;
4179
        /* falls through */
4180
      case EXLEN:
4181
        if (state.flags & 0x0400) {
4182
          //=== NEEDBITS(16); */
4183
          while (bits < 16) {
4184
            if (have === 0) { break inf_leave; }
4185
            have--;
4186
            hold += input[next++] << bits;
4187
            bits += 8;
4188
          }
4189
          //===//
4190
          state.length = hold;
4191
          if (state.head) {
4192
            state.head.extra_len = hold;
4193
          }
4194
          if (state.flags & 0x0200) {
4195
            //=== CRC2(state.check, hold);
4196
            hbuf[0] = hold & 0xff;
4197
            hbuf[1] = (hold >>> 8) & 0xff;
4198
            state.check = crc32(state.check, hbuf, 2, 0);
4199
            //===//
4200
          }
4201
          //=== INITBITS();
4202
          hold = 0;
4203
          bits = 0;
4204
          //===//
4205
        }
4206
        else if (state.head) {
4207
          state.head.extra = null/*Z_NULL*/;
4208
        }
4209
        state.mode = EXTRA;
4210
        /* falls through */
4211
      case EXTRA:
4212
        if (state.flags & 0x0400) {
4213
          copy = state.length;
4214
          if (copy > have) { copy = have; }
4215
          if (copy) {
4216
            if (state.head) {
4217
              len = state.head.extra_len - state.length;
4218
              if (!state.head.extra) {
4219
                // Use untyped array for more convenient processing later
4220
                state.head.extra = new Array(state.head.extra_len);
4221
              }
4222
              utils.arraySet(
4223
                state.head.extra,
4224
                input,
4225
                next,
4226
                // extra field is limited to 65536 bytes
4227
                // - no need for additional size check
4228
                copy,
4229
                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
4230
                len
4231
              );
4232
              //zmemcpy(state.head.extra + len, next,
4233
              //        len + copy > state.head.extra_max ?
4234
              //        state.head.extra_max - len : copy);
4235
            }
4236
            if (state.flags & 0x0200) {
4237
              state.check = crc32(state.check, input, copy, next);
4238
            }
4239
            have -= copy;
4240
            next += copy;
4241
            state.length -= copy;
4242
          }
4243
          if (state.length) { break inf_leave; }
4244
        }
4245
        state.length = 0;
4246
        state.mode = NAME;
4247
        /* falls through */
4248
      case NAME:
4249
        if (state.flags & 0x0800) {
4250
          if (have === 0) { break inf_leave; }
4251
          copy = 0;
4252
          do {
4253
            // TODO: 2 or 1 bytes?
4254
            len = input[next + copy++];
4255
            /* use constant limit because in js we should not preallocate memory */
4256
            if (state.head && len &&
4257
                (state.length < 65536 /*state.head.name_max*/)) {
4258
              state.head.name += String.fromCharCode(len);
4259
            }
4260
          } while (len && copy < have);
4261

    
4262
          if (state.flags & 0x0200) {
4263
            state.check = crc32(state.check, input, copy, next);
4264
          }
4265
          have -= copy;
4266
          next += copy;
4267
          if (len) { break inf_leave; }
4268
        }
4269
        else if (state.head) {
4270
          state.head.name = null;
4271
        }
4272
        state.length = 0;
4273
        state.mode = COMMENT;
4274
        /* falls through */
4275
      case COMMENT:
4276
        if (state.flags & 0x1000) {
4277
          if (have === 0) { break inf_leave; }
4278
          copy = 0;
4279
          do {
4280
            len = input[next + copy++];
4281
            /* use constant limit because in js we should not preallocate memory */
4282
            if (state.head && len &&
4283
                (state.length < 65536 /*state.head.comm_max*/)) {
4284
              state.head.comment += String.fromCharCode(len);
4285
            }
4286
          } while (len && copy < have);
4287
          if (state.flags & 0x0200) {
4288
            state.check = crc32(state.check, input, copy, next);
4289
          }
4290
          have -= copy;
4291
          next += copy;
4292
          if (len) { break inf_leave; }
4293
        }
4294
        else if (state.head) {
4295
          state.head.comment = null;
4296
        }
4297
        state.mode = HCRC;
4298
        /* falls through */
4299
      case HCRC:
4300
        if (state.flags & 0x0200) {
4301
          //=== NEEDBITS(16); */
4302
          while (bits < 16) {
4303
            if (have === 0) { break inf_leave; }
4304
            have--;
4305
            hold += input[next++] << bits;
4306
            bits += 8;
4307
          }
4308
          //===//
4309
          if (hold !== (state.check & 0xffff)) {
4310
            strm.msg = 'header crc mismatch';
4311
            state.mode = BAD;
4312
            break;
4313
          }
4314
          //=== INITBITS();
4315
          hold = 0;
4316
          bits = 0;
4317
          //===//
4318
        }
4319
        if (state.head) {
4320
          state.head.hcrc = ((state.flags >> 9) & 1);
4321
          state.head.done = true;
4322
        }
4323
        strm.adler = state.check = 0;
4324
        state.mode = TYPE;
4325
        break;
4326
      case DICTID:
4327
        //=== NEEDBITS(32); */
4328
        while (bits < 32) {
4329
          if (have === 0) { break inf_leave; }
4330
          have--;
4331
          hold += input[next++] << bits;
4332
          bits += 8;
4333
        }
4334
        //===//
4335
        strm.adler = state.check = zswap32(hold);
4336
        //=== INITBITS();
4337
        hold = 0;
4338
        bits = 0;
4339
        //===//
4340
        state.mode = DICT;
4341
        /* falls through */
4342
      case DICT:
4343
        if (state.havedict === 0) {
4344
          //--- RESTORE() ---
4345
          strm.next_out = put;
4346
          strm.avail_out = left;
4347
          strm.next_in = next;
4348
          strm.avail_in = have;
4349
          state.hold = hold;
4350
          state.bits = bits;
4351
          //---
4352
          return Z_NEED_DICT;
4353
        }
4354
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
4355
        state.mode = TYPE;
4356
        /* falls through */
4357
      case TYPE:
4358
        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
4359
        /* falls through */
4360
      case TYPEDO:
4361
        if (state.last) {
4362
          //--- BYTEBITS() ---//
4363
          hold >>>= bits & 7;
4364
          bits -= bits & 7;
4365
          //---//
4366
          state.mode = CHECK;
4367
          break;
4368
        }
4369
        //=== NEEDBITS(3); */
4370
        while (bits < 3) {
4371
          if (have === 0) { break inf_leave; }
4372
          have--;
4373
          hold += input[next++] << bits;
4374
          bits += 8;
4375
        }
4376
        //===//
4377
        state.last = (hold & 0x01)/*BITS(1)*/;
4378
        //--- DROPBITS(1) ---//
4379
        hold >>>= 1;
4380
        bits -= 1;
4381
        //---//
4382

    
4383
        switch ((hold & 0x03)/*BITS(2)*/) {
4384
          case 0:                             /* stored block */
4385
            //Tracev((stderr, "inflate:     stored block%s\n",
4386
            //        state.last ? " (last)" : ""));
4387
            state.mode = STORED;
4388
            break;
4389
          case 1:                             /* fixed block */
4390
            fixedtables(state);
4391
            //Tracev((stderr, "inflate:     fixed codes block%s\n",
4392
            //        state.last ? " (last)" : ""));
4393
            state.mode = LEN_;             /* decode codes */
4394
            if (flush === Z_TREES) {
4395
              //--- DROPBITS(2) ---//
4396
              hold >>>= 2;
4397
              bits -= 2;
4398
              //---//
4399
              break inf_leave;
4400
            }
4401
            break;
4402
          case 2:                             /* dynamic block */
4403
            //Tracev((stderr, "inflate:     dynamic codes block%s\n",
4404
            //        state.last ? " (last)" : ""));
4405
            state.mode = TABLE;
4406
            break;
4407
          case 3:
4408
            strm.msg = 'invalid block type';
4409
            state.mode = BAD;
4410
        }
4411
        //--- DROPBITS(2) ---//
4412
        hold >>>= 2;
4413
        bits -= 2;
4414
        //---//
4415
        break;
4416
      case STORED:
4417
        //--- BYTEBITS() ---// /* go to byte boundary */
4418
        hold >>>= bits & 7;
4419
        bits -= bits & 7;
4420
        //---//
4421
        //=== NEEDBITS(32); */
4422
        while (bits < 32) {
4423
          if (have === 0) { break inf_leave; }
4424
          have--;
4425
          hold += input[next++] << bits;
4426
          bits += 8;
4427
        }
4428
        //===//
4429
        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
4430
          strm.msg = 'invalid stored block lengths';
4431
          state.mode = BAD;
4432
          break;
4433
        }
4434
        state.length = hold & 0xffff;
4435
        //Tracev((stderr, "inflate:       stored length %u\n",
4436
        //        state.length));
4437
        //=== INITBITS();
4438
        hold = 0;
4439
        bits = 0;
4440
        //===//
4441
        state.mode = COPY_;
4442
        if (flush === Z_TREES) { break inf_leave; }
4443
        /* falls through */
4444
      case COPY_:
4445
        state.mode = COPY;
4446
        /* falls through */
4447
      case COPY:
4448
        copy = state.length;
4449
        if (copy) {
4450
          if (copy > have) { copy = have; }
4451
          if (copy > left) { copy = left; }
4452
          if (copy === 0) { break inf_leave; }
4453
          //--- zmemcpy(put, next, copy); ---
4454
          utils.arraySet(output, input, next, copy, put);
4455
          //---//
4456
          have -= copy;
4457
          next += copy;
4458
          left -= copy;
4459
          put += copy;
4460
          state.length -= copy;
4461
          break;
4462
        }
4463
        //Tracev((stderr, "inflate:       stored end\n"));
4464
        state.mode = TYPE;
4465
        break;
4466
      case TABLE:
4467
        //=== NEEDBITS(14); */
4468
        while (bits < 14) {
4469
          if (have === 0) { break inf_leave; }
4470
          have--;
4471
          hold += input[next++] << bits;
4472
          bits += 8;
4473
        }
4474
        //===//
4475
        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
4476
        //--- DROPBITS(5) ---//
4477
        hold >>>= 5;
4478
        bits -= 5;
4479
        //---//
4480
        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
4481
        //--- DROPBITS(5) ---//
4482
        hold >>>= 5;
4483
        bits -= 5;
4484
        //---//
4485
        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
4486
        //--- DROPBITS(4) ---//
4487
        hold >>>= 4;
4488
        bits -= 4;
4489
        //---//
4490
//#ifndef PKZIP_BUG_WORKAROUND
4491
        if (state.nlen > 286 || state.ndist > 30) {
4492
          strm.msg = 'too many length or distance symbols';
4493
          state.mode = BAD;
4494
          break;
4495
        }
4496
//#endif
4497
        //Tracev((stderr, "inflate:       table sizes ok\n"));
4498
        state.have = 0;
4499
        state.mode = LENLENS;
4500
        /* falls through */
4501
      case LENLENS:
4502
        while (state.have < state.ncode) {
4503
          //=== NEEDBITS(3);
4504
          while (bits < 3) {
4505
            if (have === 0) { break inf_leave; }
4506
            have--;
4507
            hold += input[next++] << bits;
4508
            bits += 8;
4509
          }
4510
          //===//
4511
          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
4512
          //--- DROPBITS(3) ---//
4513
          hold >>>= 3;
4514
          bits -= 3;
4515
          //---//
4516
        }
4517
        while (state.have < 19) {
4518
          state.lens[order[state.have++]] = 0;
4519
        }
4520
        // We have separate tables & no pointers. 2 commented lines below not needed.
4521
        //state.next = state.codes;
4522
        //state.lencode = state.next;
4523
        // Switch to use dynamic table
4524
        state.lencode = state.lendyn;
4525
        state.lenbits = 7;
4526

    
4527
        opts = { bits: state.lenbits };
4528
        ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
4529
        state.lenbits = opts.bits;
4530

    
4531
        if (ret) {
4532
          strm.msg = 'invalid code lengths set';
4533
          state.mode = BAD;
4534
          break;
4535
        }
4536
        //Tracev((stderr, "inflate:       code lengths ok\n"));
4537
        state.have = 0;
4538
        state.mode = CODELENS;
4539
        /* falls through */
4540
      case CODELENS:
4541
        while (state.have < state.nlen + state.ndist) {
4542
          for (;;) {
4543
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
4544
            here_bits = here >>> 24;
4545
            here_op = (here >>> 16) & 0xff;
4546
            here_val = here & 0xffff;
4547

    
4548
            if ((here_bits) <= bits) { break; }
4549
            //--- PULLBYTE() ---//
4550
            if (have === 0) { break inf_leave; }
4551
            have--;
4552
            hold += input[next++] << bits;
4553
            bits += 8;
4554
            //---//
4555
          }
4556
          if (here_val < 16) {
4557
            //--- DROPBITS(here.bits) ---//
4558
            hold >>>= here_bits;
4559
            bits -= here_bits;
4560
            //---//
4561
            state.lens[state.have++] = here_val;
4562
          }
4563
          else {
4564
            if (here_val === 16) {
4565
              //=== NEEDBITS(here.bits + 2);
4566
              n = here_bits + 2;
4567
              while (bits < n) {
4568
                if (have === 0) { break inf_leave; }
4569
                have--;
4570
                hold += input[next++] << bits;
4571
                bits += 8;
4572
              }
4573
              //===//
4574
              //--- DROPBITS(here.bits) ---//
4575
              hold >>>= here_bits;
4576
              bits -= here_bits;
4577
              //---//
4578
              if (state.have === 0) {
4579
                strm.msg = 'invalid bit length repeat';
4580
                state.mode = BAD;
4581
                break;
4582
              }
4583
              len = state.lens[state.have - 1];
4584
              copy = 3 + (hold & 0x03);//BITS(2);
4585
              //--- DROPBITS(2) ---//
4586
              hold >>>= 2;
4587
              bits -= 2;
4588
              //---//
4589
            }
4590
            else if (here_val === 17) {
4591
              //=== NEEDBITS(here.bits + 3);
4592
              n = here_bits + 3;
4593
              while (bits < n) {
4594
                if (have === 0) { break inf_leave; }
4595
                have--;
4596
                hold += input[next++] << bits;
4597
                bits += 8;
4598
              }
4599
              //===//
4600
              //--- DROPBITS(here.bits) ---//
4601
              hold >>>= here_bits;
4602
              bits -= here_bits;
4603
              //---//
4604
              len = 0;
4605
              copy = 3 + (hold & 0x07);//BITS(3);
4606
              //--- DROPBITS(3) ---//
4607
              hold >>>= 3;
4608
              bits -= 3;
4609
              //---//
4610
            }
4611
            else {
4612
              //=== NEEDBITS(here.bits + 7);
4613
              n = here_bits + 7;
4614
              while (bits < n) {
4615
                if (have === 0) { break inf_leave; }
4616
                have--;
4617
                hold += input[next++] << bits;
4618
                bits += 8;
4619
              }
4620
              //===//
4621
              //--- DROPBITS(here.bits) ---//
4622
              hold >>>= here_bits;
4623
              bits -= here_bits;
4624
              //---//
4625
              len = 0;
4626
              copy = 11 + (hold & 0x7f);//BITS(7);
4627
              //--- DROPBITS(7) ---//
4628
              hold >>>= 7;
4629
              bits -= 7;
4630
              //---//
4631
            }
4632
            if (state.have + copy > state.nlen + state.ndist) {
4633
              strm.msg = 'invalid bit length repeat';
4634
              state.mode = BAD;
4635
              break;
4636
            }
4637
            while (copy--) {
4638
              state.lens[state.have++] = len;
4639
            }
4640
          }
4641
        }
4642

    
4643
        /* handle error breaks in while */
4644
        if (state.mode === BAD) { break; }
4645

    
4646
        /* check for end-of-block code (better have one) */
4647
        if (state.lens[256] === 0) {
4648
          strm.msg = 'invalid code -- missing end-of-block';
4649
          state.mode = BAD;
4650
          break;
4651
        }
4652

    
4653
        /* build code tables -- note: do not change the lenbits or distbits
4654
           values here (9 and 6) without reading the comments in inftrees.h
4655
           concerning the ENOUGH constants, which depend on those values */
4656
        state.lenbits = 9;
4657

    
4658
        opts = { bits: state.lenbits };
4659
        ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
4660
        // We have separate tables & no pointers. 2 commented lines below not needed.
4661
        // state.next_index = opts.table_index;
4662
        state.lenbits = opts.bits;
4663
        // state.lencode = state.next;
4664

    
4665
        if (ret) {
4666
          strm.msg = 'invalid literal/lengths set';
4667
          state.mode = BAD;
4668
          break;
4669
        }
4670

    
4671
        state.distbits = 6;
4672
        //state.distcode.copy(state.codes);
4673
        // Switch to use dynamic table
4674
        state.distcode = state.distdyn;
4675
        opts = { bits: state.distbits };
4676
        ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
4677
        // We have separate tables & no pointers. 2 commented lines below not needed.
4678
        // state.next_index = opts.table_index;
4679
        state.distbits = opts.bits;
4680
        // state.distcode = state.next;
4681

    
4682
        if (ret) {
4683
          strm.msg = 'invalid distances set';
4684
          state.mode = BAD;
4685
          break;
4686
        }
4687
        //Tracev((stderr, 'inflate:       codes ok\n'));
4688
        state.mode = LEN_;
4689
        if (flush === Z_TREES) { break inf_leave; }
4690
        /* falls through */
4691
      case LEN_:
4692
        state.mode = LEN;
4693
        /* falls through */
4694
      case LEN:
4695
        if (have >= 6 && left >= 258) {
4696
          //--- RESTORE() ---
4697
          strm.next_out = put;
4698
          strm.avail_out = left;
4699
          strm.next_in = next;
4700
          strm.avail_in = have;
4701
          state.hold = hold;
4702
          state.bits = bits;
4703
          //---
4704
          inflate_fast(strm, _out);
4705
          //--- LOAD() ---
4706
          put = strm.next_out;
4707
          output = strm.output;
4708
          left = strm.avail_out;
4709
          next = strm.next_in;
4710
          input = strm.input;
4711
          have = strm.avail_in;
4712
          hold = state.hold;
4713
          bits = state.bits;
4714
          //---
4715

    
4716
          if (state.mode === TYPE) {
4717
            state.back = -1;
4718
          }
4719
          break;
4720
        }
4721
        state.back = 0;
4722
        for (;;) {
4723
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
4724
          here_bits = here >>> 24;
4725
          here_op = (here >>> 16) & 0xff;
4726
          here_val = here & 0xffff;
4727

    
4728
          if (here_bits <= bits) { break; }
4729
          //--- PULLBYTE() ---//
4730
          if (have === 0) { break inf_leave; }
4731
          have--;
4732
          hold += input[next++] << bits;
4733
          bits += 8;
4734
          //---//
4735
        }
4736
        if (here_op && (here_op & 0xf0) === 0) {
4737
          last_bits = here_bits;
4738
          last_op = here_op;
4739
          last_val = here_val;
4740
          for (;;) {
4741
            here = state.lencode[last_val +
4742
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4743
            here_bits = here >>> 24;
4744
            here_op = (here >>> 16) & 0xff;
4745
            here_val = here & 0xffff;
4746

    
4747
            if ((last_bits + here_bits) <= bits) { break; }
4748
            //--- PULLBYTE() ---//
4749
            if (have === 0) { break inf_leave; }
4750
            have--;
4751
            hold += input[next++] << bits;
4752
            bits += 8;
4753
            //---//
4754
          }
4755
          //--- DROPBITS(last.bits) ---//
4756
          hold >>>= last_bits;
4757
          bits -= last_bits;
4758
          //---//
4759
          state.back += last_bits;
4760
        }
4761
        //--- DROPBITS(here.bits) ---//
4762
        hold >>>= here_bits;
4763
        bits -= here_bits;
4764
        //---//
4765
        state.back += here_bits;
4766
        state.length = here_val;
4767
        if (here_op === 0) {
4768
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
4769
          //        "inflate:         literal '%c'\n" :
4770
          //        "inflate:         literal 0x%02x\n", here.val));
4771
          state.mode = LIT;
4772
          break;
4773
        }
4774
        if (here_op & 32) {
4775
          //Tracevv((stderr, "inflate:         end of block\n"));
4776
          state.back = -1;
4777
          state.mode = TYPE;
4778
          break;
4779
        }
4780
        if (here_op & 64) {
4781
          strm.msg = 'invalid literal/length code';
4782
          state.mode = BAD;
4783
          break;
4784
        }
4785
        state.extra = here_op & 15;
4786
        state.mode = LENEXT;
4787
        /* falls through */
4788
      case LENEXT:
4789
        if (state.extra) {
4790
          //=== NEEDBITS(state.extra);
4791
          n = state.extra;
4792
          while (bits < n) {
4793
            if (have === 0) { break inf_leave; }
4794
            have--;
4795
            hold += input[next++] << bits;
4796
            bits += 8;
4797
          }
4798
          //===//
4799
          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
4800
          //--- DROPBITS(state.extra) ---//
4801
          hold >>>= state.extra;
4802
          bits -= state.extra;
4803
          //---//
4804
          state.back += state.extra;
4805
        }
4806
        //Tracevv((stderr, "inflate:         length %u\n", state.length));
4807
        state.was = state.length;
4808
        state.mode = DIST;
4809
        /* falls through */
4810
      case DIST:
4811
        for (;;) {
4812
          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
4813
          here_bits = here >>> 24;
4814
          here_op = (here >>> 16) & 0xff;
4815
          here_val = here & 0xffff;
4816

    
4817
          if ((here_bits) <= bits) { break; }
4818
          //--- PULLBYTE() ---//
4819
          if (have === 0) { break inf_leave; }
4820
          have--;
4821
          hold += input[next++] << bits;
4822
          bits += 8;
4823
          //---//
4824
        }
4825
        if ((here_op & 0xf0) === 0) {
4826
          last_bits = here_bits;
4827
          last_op = here_op;
4828
          last_val = here_val;
4829
          for (;;) {
4830
            here = state.distcode[last_val +
4831
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4832
            here_bits = here >>> 24;
4833
            here_op = (here >>> 16) & 0xff;
4834
            here_val = here & 0xffff;
4835

    
4836
            if ((last_bits + here_bits) <= bits) { break; }
4837
            //--- PULLBYTE() ---//
4838
            if (have === 0) { break inf_leave; }
4839
            have--;
4840
            hold += input[next++] << bits;
4841
            bits += 8;
4842
            //---//
4843
          }
4844
          //--- DROPBITS(last.bits) ---//
4845
          hold >>>= last_bits;
4846
          bits -= last_bits;
4847
          //---//
4848
          state.back += last_bits;
4849
        }
4850
        //--- DROPBITS(here.bits) ---//
4851
        hold >>>= here_bits;
4852
        bits -= here_bits;
4853
        //---//
4854
        state.back += here_bits;
4855
        if (here_op & 64) {
4856
          strm.msg = 'invalid distance code';
4857
          state.mode = BAD;
4858
          break;
4859
        }
4860
        state.offset = here_val;
4861
        state.extra = (here_op) & 15;
4862
        state.mode = DISTEXT;
4863
        /* falls through */
4864
      case DISTEXT:
4865
        if (state.extra) {
4866
          //=== NEEDBITS(state.extra);
4867
          n = state.extra;
4868
          while (bits < n) {
4869
            if (have === 0) { break inf_leave; }
4870
            have--;
4871
            hold += input[next++] << bits;
4872
            bits += 8;
4873
          }
4874
          //===//
4875
          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
4876
          //--- DROPBITS(state.extra) ---//
4877
          hold >>>= state.extra;
4878
          bits -= state.extra;
4879
          //---//
4880
          state.back += state.extra;
4881
        }
4882
//#ifdef INFLATE_STRICT
4883
        if (state.offset > state.dmax) {
4884
          strm.msg = 'invalid distance too far back';
4885
          state.mode = BAD;
4886
          break;
4887
        }
4888
//#endif
4889
        //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
4890
        state.mode = MATCH;
4891
        /* falls through */
4892
      case MATCH:
4893
        if (left === 0) { break inf_leave; }
4894
        copy = _out - left;
4895
        if (state.offset > copy) {         /* copy from window */
4896
          copy = state.offset - copy;
4897
          if (copy > state.whave) {
4898
            if (state.sane) {
4899
              strm.msg = 'invalid distance too far back';
4900
              state.mode = BAD;
4901
              break;
4902
            }
4903
// (!) This block is disabled in zlib defaults,
4904
// don't enable it for binary compatibility
4905
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
4906
//          Trace((stderr, "inflate.c too far\n"));
4907
//          copy -= state.whave;
4908
//          if (copy > state.length) { copy = state.length; }
4909
//          if (copy > left) { copy = left; }
4910
//          left -= copy;
4911
//          state.length -= copy;
4912
//          do {
4913
//            output[put++] = 0;
4914
//          } while (--copy);
4915
//          if (state.length === 0) { state.mode = LEN; }
4916
//          break;
4917
//#endif
4918
          }
4919
          if (copy > state.wnext) {
4920
            copy -= state.wnext;
4921
            from = state.wsize - copy;
4922
          }
4923
          else {
4924
            from = state.wnext - copy;
4925
          }
4926
          if (copy > state.length) { copy = state.length; }
4927
          from_source = state.window;
4928
        }
4929
        else {                              /* copy from output */
4930
          from_source = output;
4931
          from = put - state.offset;
4932
          copy = state.length;
4933
        }
4934
        if (copy > left) { copy = left; }
4935
        left -= copy;
4936
        state.length -= copy;
4937
        do {
4938
          output[put++] = from_source[from++];
4939
        } while (--copy);
4940
        if (state.length === 0) { state.mode = LEN; }
4941
        break;
4942
      case LIT:
4943
        if (left === 0) { break inf_leave; }
4944
        output[put++] = state.length;
4945
        left--;
4946
        state.mode = LEN;
4947
        break;
4948
      case CHECK:
4949
        if (state.wrap) {
4950
          //=== NEEDBITS(32);
4951
          while (bits < 32) {
4952
            if (have === 0) { break inf_leave; }
4953
            have--;
4954
            // Use '|' instead of '+' to make sure that result is signed
4955
            hold |= input[next++] << bits;
4956
            bits += 8;
4957
          }
4958
          //===//
4959
          _out -= left;
4960
          strm.total_out += _out;
4961
          state.total += _out;
4962
          if (_out) {
4963
            strm.adler = state.check =
4964
                /*UPDATE(state.check, put - _out, _out);*/
4965
                (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
4966

    
4967
          }
4968
          _out = left;
4969
          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
4970
          if ((state.flags ? hold : zswap32(hold)) !== state.check) {
4971
            strm.msg = 'incorrect data check';
4972
            state.mode = BAD;
4973
            break;
4974
          }
4975
          //=== INITBITS();
4976
          hold = 0;
4977
          bits = 0;
4978
          //===//
4979
          //Tracev((stderr, "inflate:   check matches trailer\n"));
4980
        }
4981
        state.mode = LENGTH;
4982
        /* falls through */
4983
      case LENGTH:
4984
        if (state.wrap && state.flags) {
4985
          //=== NEEDBITS(32);
4986
          while (bits < 32) {
4987
            if (have === 0) { break inf_leave; }
4988
            have--;
4989
            hold += input[next++] << bits;
4990
            bits += 8;
4991
          }
4992
          //===//
4993
          if (hold !== (state.total & 0xffffffff)) {
4994
            strm.msg = 'incorrect length check';
4995
            state.mode = BAD;
4996
            break;
4997
          }
4998
          //=== INITBITS();
4999
          hold = 0;
5000
          bits = 0;
5001
          //===//
5002
          //Tracev((stderr, "inflate:   length matches trailer\n"));
5003
        }
5004
        state.mode = DONE;
5005
        /* falls through */
5006
      case DONE:
5007
        ret = Z_STREAM_END;
5008
        break inf_leave;
5009
      case BAD:
5010
        ret = Z_DATA_ERROR;
5011
        break inf_leave;
5012
      case MEM:
5013
        return Z_MEM_ERROR;
5014
      case SYNC:
5015
        /* falls through */
5016
      default:
5017
        return Z_STREAM_ERROR;
5018
    }
5019
  }
5020

    
5021
  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
5022

    
5023
  /*
5024
     Return from inflate(), updating the total counts and the check value.
5025
     If there was no progress during the inflate() call, return a buffer
5026
     error.  Call updatewindow() to create and/or update the window state.
5027
     Note: a memory error from inflate() is non-recoverable.
5028
   */
5029

    
5030
  //--- RESTORE() ---
5031
  strm.next_out = put;
5032
  strm.avail_out = left;
5033
  strm.next_in = next;
5034
  strm.avail_in = have;
5035
  state.hold = hold;
5036
  state.bits = bits;
5037
  //---
5038

    
5039
  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
5040
                      (state.mode < CHECK || flush !== Z_FINISH))) {
5041
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
5042
      state.mode = MEM;
5043
      return Z_MEM_ERROR;
5044
    }
5045
  }
5046
  _in -= strm.avail_in;
5047
  _out -= strm.avail_out;
5048
  strm.total_in += _in;
5049
  strm.total_out += _out;
5050
  state.total += _out;
5051
  if (state.wrap && _out) {
5052
    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
5053
      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
5054
  }
5055
  strm.data_type = state.bits + (state.last ? 64 : 0) +
5056
                    (state.mode === TYPE ? 128 : 0) +
5057
                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
5058
  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
5059
    ret = Z_BUF_ERROR;
5060
  }
5061
  return ret;
5062
}
5063

    
5064
function inflateEnd(strm) {
5065

    
5066
  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
5067
    return Z_STREAM_ERROR;
5068
  }
5069

    
5070
  var state = strm.state;
5071
  if (state.window) {
5072
    state.window = null;
5073
  }
5074
  strm.state = null;
5075
  return Z_OK;
5076
}
5077

    
5078
function inflateGetHeader(strm, head) {
5079
  var state;
5080

    
5081
  /* check state */
5082
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
5083
  state = strm.state;
5084
  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
5085

    
5086
  /* save header structure */
5087
  state.head = head;
5088
  head.done = false;
5089
  return Z_OK;
5090
}
5091

    
5092
function inflateSetDictionary(strm, dictionary) {
5093
  var dictLength = dictionary.length;
5094

    
5095
  var state;
5096
  var dictid;
5097
  var ret;
5098

    
5099
  /* check state */
5100
  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
5101
  state = strm.state;
5102

    
5103
  if (state.wrap !== 0 && state.mode !== DICT) {
5104
    return Z_STREAM_ERROR;
5105
  }
5106

    
5107
  /* check for correct dictionary identifier */
5108
  if (state.mode === DICT) {
5109
    dictid = 1; /* adler32(0, null, 0)*/
5110
    /* dictid = adler32(dictid, dictionary, dictLength); */
5111
    dictid = adler32(dictid, dictionary, dictLength, 0);
5112
    if (dictid !== state.check) {
5113
      return Z_DATA_ERROR;
5114
    }
5115
  }
5116
  /* copy dictionary to window using updatewindow(), which will amend the
5117
   existing dictionary if appropriate */
5118
  ret = updatewindow(strm, dictionary, dictLength, dictLength);
5119
  if (ret) {
5120
    state.mode = MEM;
5121
    return Z_MEM_ERROR;
5122
  }
5123
  state.havedict = 1;
5124
  // Tracev((stderr, "inflate:   dictionary set\n"));
5125
  return Z_OK;
5126
}
5127

    
5128
exports.inflateReset = inflateReset;
5129
exports.inflateReset2 = inflateReset2;
5130
exports.inflateResetKeep = inflateResetKeep;
5131
exports.inflateInit = inflateInit;
5132
exports.inflateInit2 = inflateInit2;
5133
exports.inflate = inflate;
5134
exports.inflateEnd = inflateEnd;
5135
exports.inflateGetHeader = inflateGetHeader;
5136
exports.inflateSetDictionary = inflateSetDictionary;
5137
exports.inflateInfo = 'pako inflate (from Nodeca project)';
5138

    
5139
/* Not implemented
5140
exports.inflateCopy = inflateCopy;
5141
exports.inflateGetDictionary = inflateGetDictionary;
5142
exports.inflateMark = inflateMark;
5143
exports.inflatePrime = inflatePrime;
5144
exports.inflateSync = inflateSync;
5145
exports.inflateSyncPoint = inflateSyncPoint;
5146
exports.inflateUndermine = inflateUndermine;
5147
*/
5148

    
5149
},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(require,module,exports){
5150
'use strict';
5151

    
5152
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5153
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5154
//
5155
// This software is provided 'as-is', without any express or implied
5156
// warranty. In no event will the authors be held liable for any damages
5157
// arising from the use of this software.
5158
//
5159
// Permission is granted to anyone to use this software for any purpose,
5160
// including commercial applications, and to alter it and redistribute it
5161
// freely, subject to the following restrictions:
5162
//
5163
// 1. The origin of this software must not be misrepresented; you must not
5164
//   claim that you wrote the original software. If you use this software
5165
//   in a product, an acknowledgment in the product documentation would be
5166
//   appreciated but is not required.
5167
// 2. Altered source versions must be plainly marked as such, and must not be
5168
//   misrepresented as being the original software.
5169
// 3. This notice may not be removed or altered from any source distribution.
5170

    
5171
var utils = require('../utils/common');
5172

    
5173
var MAXBITS = 15;
5174
var ENOUGH_LENS = 852;
5175
var ENOUGH_DISTS = 592;
5176
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
5177

    
5178
var CODES = 0;
5179
var LENS = 1;
5180
var DISTS = 2;
5181

    
5182
var lbase = [ /* Length codes 257..285 base */
5183
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
5184
  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
5185
];
5186

    
5187
var lext = [ /* Length codes 257..285 extra */
5188
  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
5189
  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
5190
];
5191

    
5192
var dbase = [ /* Distance codes 0..29 base */
5193
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
5194
  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
5195
  8193, 12289, 16385, 24577, 0, 0
5196
];
5197

    
5198
var dext = [ /* Distance codes 0..29 extra */
5199
  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
5200
  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
5201
  28, 28, 29, 29, 64, 64
5202
];
5203

    
5204
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
5205
{
5206
  var bits = opts.bits;
5207
      //here = opts.here; /* table entry for duplication */
5208

    
5209
  var len = 0;               /* a code's length in bits */
5210
  var sym = 0;               /* index of code symbols */
5211
  var min = 0, max = 0;          /* minimum and maximum code lengths */
5212
  var root = 0;              /* number of index bits for root table */
5213
  var curr = 0;              /* number of index bits for current table */
5214
  var drop = 0;              /* code bits to drop for sub-table */
5215
  var left = 0;                   /* number of prefix codes available */
5216
  var used = 0;              /* code entries in table used */
5217
  var huff = 0;              /* Huffman code */
5218
  var incr;              /* for incrementing code, index */
5219
  var fill;              /* index for replicating entries */
5220
  var low;               /* low bits for current root entry */
5221
  var mask;              /* mask for low root bits */
5222
  var next;             /* next available space in table */
5223
  var base = null;     /* base value table to use */
5224
  var base_index = 0;
5225
//  var shoextra;    /* extra bits table to use */
5226
  var end;                    /* use base and extra for symbol > end */
5227
  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
5228
  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
5229
  var extra = null;
5230
  var extra_index = 0;
5231

    
5232
  var here_bits, here_op, here_val;
5233

    
5234
  /*
5235
   Process a set of code lengths to create a canonical Huffman code.  The
5236
   code lengths are lens[0..codes-1].  Each length corresponds to the
5237
   symbols 0..codes-1.  The Huffman code is generated by first sorting the
5238
   symbols by length from short to long, and retaining the symbol order
5239
   for codes with equal lengths.  Then the code starts with all zero bits
5240
   for the first code of the shortest length, and the codes are integer
5241
   increments for the same length, and zeros are appended as the length
5242
   increases.  For the deflate format, these bits are stored backwards
5243
   from their more natural integer increment ordering, and so when the
5244
   decoding tables are built in the large loop below, the integer codes
5245
   are incremented backwards.
5246

    
5247
   This routine assumes, but does not check, that all of the entries in
5248
   lens[] are in the range 0..MAXBITS.  The caller must assure this.
5249
   1..MAXBITS is interpreted as that code length.  zero means that that
5250
   symbol does not occur in this code.
5251

    
5252
   The codes are sorted by computing a count of codes for each length,
5253
   creating from that a table of starting indices for each length in the
5254
   sorted table, and then entering the symbols in order in the sorted
5255
   table.  The sorted table is work[], with that space being provided by
5256
   the caller.
5257

    
5258
   The length counts are used for other purposes as well, i.e. finding
5259
   the minimum and maximum length codes, determining if there are any
5260
   codes at all, checking for a valid set of lengths, and looking ahead
5261
   at length counts to determine sub-table sizes when building the
5262
   decoding tables.
5263
   */
5264

    
5265
  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
5266
  for (len = 0; len <= MAXBITS; len++) {
5267
    count[len] = 0;
5268
  }
5269
  for (sym = 0; sym < codes; sym++) {
5270
    count[lens[lens_index + sym]]++;
5271
  }
5272

    
5273
  /* bound code lengths, force root to be within code lengths */
5274
  root = bits;
5275
  for (max = MAXBITS; max >= 1; max--) {
5276
    if (count[max] !== 0) { break; }
5277
  }
5278
  if (root > max) {
5279
    root = max;
5280
  }
5281
  if (max === 0) {                     /* no symbols to code at all */
5282
    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
5283
    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
5284
    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
5285
    table[table_index++] = (1 << 24) | (64 << 16) | 0;
5286

    
5287

    
5288
    //table.op[opts.table_index] = 64;
5289
    //table.bits[opts.table_index] = 1;
5290
    //table.val[opts.table_index++] = 0;
5291
    table[table_index++] = (1 << 24) | (64 << 16) | 0;
5292

    
5293
    opts.bits = 1;
5294
    return 0;     /* no symbols, but wait for decoding to report error */
5295
  }
5296
  for (min = 1; min < max; min++) {
5297
    if (count[min] !== 0) { break; }
5298
  }
5299
  if (root < min) {
5300
    root = min;
5301
  }
5302

    
5303
  /* check for an over-subscribed or incomplete set of lengths */
5304
  left = 1;
5305
  for (len = 1; len <= MAXBITS; len++) {
5306
    left <<= 1;
5307
    left -= count[len];
5308
    if (left < 0) {
5309
      return -1;
5310
    }        /* over-subscribed */
5311
  }
5312
  if (left > 0 && (type === CODES || max !== 1)) {
5313
    return -1;                      /* incomplete set */
5314
  }
5315

    
5316
  /* generate offsets into symbol table for each length for sorting */
5317
  offs[1] = 0;
5318
  for (len = 1; len < MAXBITS; len++) {
5319
    offs[len + 1] = offs[len] + count[len];
5320
  }
5321

    
5322
  /* sort symbols by length, by symbol order within each length */
5323
  for (sym = 0; sym < codes; sym++) {
5324
    if (lens[lens_index + sym] !== 0) {
5325
      work[offs[lens[lens_index + sym]]++] = sym;
5326
    }
5327
  }
5328

    
5329
  /*
5330
   Create and fill in decoding tables.  In this loop, the table being
5331
   filled is at next and has curr index bits.  The code being used is huff
5332
   with length len.  That code is converted to an index by dropping drop
5333
   bits off of the bottom.  For codes where len is less than drop + curr,
5334
   those top drop + curr - len bits are incremented through all values to
5335
   fill the table with replicated entries.
5336

    
5337
   root is the number of index bits for the root table.  When len exceeds
5338
   root, sub-tables are created pointed to by the root entry with an index
5339
   of the low root bits of huff.  This is saved in low to check for when a
5340
   new sub-table should be started.  drop is zero when the root table is
5341
   being filled, and drop is root when sub-tables are being filled.
5342

    
5343
   When a new sub-table is needed, it is necessary to look ahead in the
5344
   code lengths to determine what size sub-table is needed.  The length
5345
   counts are used for this, and so count[] is decremented as codes are
5346
   entered in the tables.
5347

    
5348
   used keeps track of how many table entries have been allocated from the
5349
   provided *table space.  It is checked for LENS and DIST tables against
5350
   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
5351
   the initial root table size constants.  See the comments in inftrees.h
5352
   for more information.
5353

    
5354
   sym increments through all symbols, and the loop terminates when
5355
   all codes of length max, i.e. all codes, have been processed.  This
5356
   routine permits incomplete codes, so another loop after this one fills
5357
   in the rest of the decoding tables with invalid code markers.
5358
   */
5359

    
5360
  /* set up for code type */
5361
  // poor man optimization - use if-else instead of switch,
5362
  // to avoid deopts in old v8
5363
  if (type === CODES) {
5364
    base = extra = work;    /* dummy value--not used */
5365
    end = 19;
5366

    
5367
  } else if (type === LENS) {
5368
    base = lbase;
5369
    base_index -= 257;
5370
    extra = lext;
5371
    extra_index -= 257;
5372
    end = 256;
5373

    
5374
  } else {                    /* DISTS */
5375
    base = dbase;
5376
    extra = dext;
5377
    end = -1;
5378
  }
5379

    
5380
  /* initialize opts for loop */
5381
  huff = 0;                   /* starting code */
5382
  sym = 0;                    /* starting code symbol */
5383
  len = min;                  /* starting code length */
5384
  next = table_index;              /* current table to fill in */
5385
  curr = root;                /* current table index bits */
5386
  drop = 0;                   /* current bits to drop from code for index */
5387
  low = -1;                   /* trigger new sub-table when len > root */
5388
  used = 1 << root;          /* use root table entries */
5389
  mask = used - 1;            /* mask for comparing low */
5390

    
5391
  /* check available table space */
5392
  if ((type === LENS && used > ENOUGH_LENS) ||
5393
    (type === DISTS && used > ENOUGH_DISTS)) {
5394
    return 1;
5395
  }
5396

    
5397
  /* process all codes and make table entries */
5398
  for (;;) {
5399
    /* create table entry */
5400
    here_bits = len - drop;
5401
    if (work[sym] < end) {
5402
      here_op = 0;
5403
      here_val = work[sym];
5404
    }
5405
    else if (work[sym] > end) {
5406
      here_op = extra[extra_index + work[sym]];
5407
      here_val = base[base_index + work[sym]];
5408
    }
5409
    else {
5410
      here_op = 32 + 64;         /* end of block */
5411
      here_val = 0;
5412
    }
5413

    
5414
    /* replicate for those indices with low len bits equal to huff */
5415
    incr = 1 << (len - drop);
5416
    fill = 1 << curr;
5417
    min = fill;                 /* save offset to next table */
5418
    do {
5419
      fill -= incr;
5420
      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
5421
    } while (fill !== 0);
5422

    
5423
    /* backwards increment the len-bit code huff */
5424
    incr = 1 << (len - 1);
5425
    while (huff & incr) {
5426
      incr >>= 1;
5427
    }
5428
    if (incr !== 0) {
5429
      huff &= incr - 1;
5430
      huff += incr;
5431
    } else {
5432
      huff = 0;
5433
    }
5434

    
5435
    /* go to next symbol, update count, len */
5436
    sym++;
5437
    if (--count[len] === 0) {
5438
      if (len === max) { break; }
5439
      len = lens[lens_index + work[sym]];
5440
    }
5441

    
5442
    /* create new sub-table if needed */
5443
    if (len > root && (huff & mask) !== low) {
5444
      /* if first time, transition to sub-tables */
5445
      if (drop === 0) {
5446
        drop = root;
5447
      }
5448

    
5449
      /* increment past last table */
5450
      next += min;            /* here min is 1 << curr */
5451

    
5452
      /* determine length of next table */
5453
      curr = len - drop;
5454
      left = 1 << curr;
5455
      while (curr + drop < max) {
5456
        left -= count[curr + drop];
5457
        if (left <= 0) { break; }
5458
        curr++;
5459
        left <<= 1;
5460
      }
5461

    
5462
      /* check for enough space */
5463
      used += 1 << curr;
5464
      if ((type === LENS && used > ENOUGH_LENS) ||
5465
        (type === DISTS && used > ENOUGH_DISTS)) {
5466
        return 1;
5467
      }
5468

    
5469
      /* point entry in root table to sub-table */
5470
      low = huff & mask;
5471
      /*table.op[low] = curr;
5472
      table.bits[low] = root;
5473
      table.val[low] = next - opts.table_index;*/
5474
      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
5475
    }
5476
  }
5477

    
5478
  /* fill in remaining table entry if code is incomplete (guaranteed to have
5479
   at most one remaining entry, since if the code is incomplete, the
5480
   maximum code length that was allowed to get this far is one bit) */
5481
  if (huff !== 0) {
5482
    //table.op[next + huff] = 64;            /* invalid code marker */
5483
    //table.bits[next + huff] = len - drop;
5484
    //table.val[next + huff] = 0;
5485
    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
5486
  }
5487

    
5488
  /* set return parameters */
5489
  //opts.table_index += used;
5490
  opts.bits = root;
5491
  return 0;
5492
};
5493

    
5494
},{"../utils/common":3}],13:[function(require,module,exports){
5495
'use strict';
5496

    
5497
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5498
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5499
//
5500
// This software is provided 'as-is', without any express or implied
5501
// warranty. In no event will the authors be held liable for any damages
5502
// arising from the use of this software.
5503
//
5504
// Permission is granted to anyone to use this software for any purpose,
5505
// including commercial applications, and to alter it and redistribute it
5506
// freely, subject to the following restrictions:
5507
//
5508
// 1. The origin of this software must not be misrepresented; you must not
5509
//   claim that you wrote the original software. If you use this software
5510
//   in a product, an acknowledgment in the product documentation would be
5511
//   appreciated but is not required.
5512
// 2. Altered source versions must be plainly marked as such, and must not be
5513
//   misrepresented as being the original software.
5514
// 3. This notice may not be removed or altered from any source distribution.
5515

    
5516
module.exports = {
5517
  2:      'need dictionary',     /* Z_NEED_DICT       2  */
5518
  1:      'stream end',          /* Z_STREAM_END      1  */
5519
  0:      '',                    /* Z_OK              0  */
5520
  '-1':   'file error',          /* Z_ERRNO         (-1) */
5521
  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
5522
  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
5523
  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
5524
  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
5525
  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
5526
};
5527

    
5528
},{}],14:[function(require,module,exports){
5529
'use strict';
5530

    
5531
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5532
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5533
//
5534
// This software is provided 'as-is', without any express or implied
5535
// warranty. In no event will the authors be held liable for any damages
5536
// arising from the use of this software.
5537
//
5538
// Permission is granted to anyone to use this software for any purpose,
5539
// including commercial applications, and to alter it and redistribute it
5540
// freely, subject to the following restrictions:
5541
//
5542
// 1. The origin of this software must not be misrepresented; you must not
5543
//   claim that you wrote the original software. If you use this software
5544
//   in a product, an acknowledgment in the product documentation would be
5545
//   appreciated but is not required.
5546
// 2. Altered source versions must be plainly marked as such, and must not be
5547
//   misrepresented as being the original software.
5548
// 3. This notice may not be removed or altered from any source distribution.
5549

    
5550
/* eslint-disable space-unary-ops */
5551

    
5552
var utils = require('../utils/common');
5553

    
5554
/* Public constants ==========================================================*/
5555
/* ===========================================================================*/
5556

    
5557

    
5558
//var Z_FILTERED          = 1;
5559
//var Z_HUFFMAN_ONLY      = 2;
5560
//var Z_RLE               = 3;
5561
var Z_FIXED               = 4;
5562
//var Z_DEFAULT_STRATEGY  = 0;
5563

    
5564
/* Possible values of the data_type field (though see inflate()) */
5565
var Z_BINARY              = 0;
5566
var Z_TEXT                = 1;
5567
//var Z_ASCII             = 1; // = Z_TEXT
5568
var Z_UNKNOWN             = 2;
5569

    
5570
/*============================================================================*/
5571

    
5572

    
5573
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
5574

    
5575
// From zutil.h
5576

    
5577
var STORED_BLOCK = 0;
5578
var STATIC_TREES = 1;
5579
var DYN_TREES    = 2;
5580
/* The three kinds of block type */
5581

    
5582
var MIN_MATCH    = 3;
5583
var MAX_MATCH    = 258;
5584
/* The minimum and maximum match lengths */
5585

    
5586
// From deflate.h
5587
/* ===========================================================================
5588
 * Internal compression state.
5589
 */
5590

    
5591
var LENGTH_CODES  = 29;
5592
/* number of length codes, not counting the special END_BLOCK code */
5593

    
5594
var LITERALS      = 256;
5595
/* number of literal bytes 0..255 */
5596

    
5597
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
5598
/* number of Literal or Length codes, including the END_BLOCK code */
5599

    
5600
var D_CODES       = 30;
5601
/* number of distance codes */
5602

    
5603
var BL_CODES      = 19;
5604
/* number of codes used to transfer the bit lengths */
5605

    
5606
var HEAP_SIZE     = 2 * L_CODES + 1;
5607
/* maximum heap size */
5608

    
5609
var MAX_BITS      = 15;
5610
/* All codes must not exceed MAX_BITS bits */
5611

    
5612
var Buf_size      = 16;
5613
/* size of bit buffer in bi_buf */
5614

    
5615

    
5616
/* ===========================================================================
5617
 * Constants
5618
 */
5619

    
5620
var MAX_BL_BITS = 7;
5621
/* Bit length codes must not exceed MAX_BL_BITS bits */
5622

    
5623
var END_BLOCK   = 256;
5624
/* end of block literal code */
5625

    
5626
var REP_3_6     = 16;
5627
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
5628

    
5629
var REPZ_3_10   = 17;
5630
/* repeat a zero length 3-10 times  (3 bits of repeat count) */
5631

    
5632
var REPZ_11_138 = 18;
5633
/* repeat a zero length 11-138 times  (7 bits of repeat count) */
5634

    
5635
/* eslint-disable comma-spacing,array-bracket-spacing */
5636
var extra_lbits =   /* extra bits for each length code */
5637
  [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];
5638

    
5639
var extra_dbits =   /* extra bits for each distance code */
5640
  [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];
5641

    
5642
var extra_blbits =  /* extra bits for each bit length code */
5643
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
5644

    
5645
var bl_order =
5646
  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
5647
/* eslint-enable comma-spacing,array-bracket-spacing */
5648

    
5649
/* The lengths of the bit length codes are sent in order of decreasing
5650
 * probability, to avoid transmitting the lengths for unused bit length codes.
5651
 */
5652

    
5653
/* ===========================================================================
5654
 * Local data. These are initialized only once.
5655
 */
5656

    
5657
// We pre-fill arrays with 0 to avoid uninitialized gaps
5658

    
5659
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
5660

    
5661
// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
5662
var static_ltree  = new Array((L_CODES + 2) * 2);
5663
zero(static_ltree);
5664
/* The static literal tree. Since the bit lengths are imposed, there is no
5665
 * need for the L_CODES extra codes used during heap construction. However
5666
 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
5667
 * below).
5668
 */
5669

    
5670
var static_dtree  = new Array(D_CODES * 2);
5671
zero(static_dtree);
5672
/* The static distance tree. (Actually a trivial tree since all codes use
5673
 * 5 bits.)
5674
 */
5675

    
5676
var _dist_code    = new Array(DIST_CODE_LEN);
5677
zero(_dist_code);
5678
/* Distance codes. The first 256 values correspond to the distances
5679
 * 3 .. 258, the last 256 values correspond to the top 8 bits of
5680
 * the 15 bit distances.
5681
 */
5682

    
5683
var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
5684
zero(_length_code);
5685
/* length code for each normalized match length (0 == MIN_MATCH) */
5686

    
5687
var base_length   = new Array(LENGTH_CODES);
5688
zero(base_length);
5689
/* First normalized length for each code (0 = MIN_MATCH) */
5690

    
5691
var base_dist     = new Array(D_CODES);
5692
zero(base_dist);
5693
/* First normalized distance for each code (0 = distance of 1) */
5694

    
5695

    
5696
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
5697

    
5698
  this.static_tree  = static_tree;  /* static tree or NULL */
5699
  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
5700
  this.extra_base   = extra_base;   /* base index for extra_bits */
5701
  this.elems        = elems;        /* max number of elements in the tree */
5702
  this.max_length   = max_length;   /* max bit length for the codes */
5703

    
5704
  // show if `static_tree` has data or dummy - needed for monomorphic objects
5705
  this.has_stree    = static_tree && static_tree.length;
5706
}
5707

    
5708

    
5709
var static_l_desc;
5710
var static_d_desc;
5711
var static_bl_desc;
5712

    
5713

    
5714
function TreeDesc(dyn_tree, stat_desc) {
5715
  this.dyn_tree = dyn_tree;     /* the dynamic tree */
5716
  this.max_code = 0;            /* largest code with non zero frequency */
5717
  this.stat_desc = stat_desc;   /* the corresponding static tree */
5718
}
5719

    
5720

    
5721

    
5722
function d_code(dist) {
5723
  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
5724
}
5725

    
5726

    
5727
/* ===========================================================================
5728
 * Output a short LSB first on the stream.
5729
 * IN assertion: there is enough room in pendingBuf.
5730
 */
5731
function put_short(s, w) {
5732
//    put_byte(s, (uch)((w) & 0xff));
5733
//    put_byte(s, (uch)((ush)(w) >> 8));
5734
  s.pending_buf[s.pending++] = (w) & 0xff;
5735
  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
5736
}
5737

    
5738

    
5739
/* ===========================================================================
5740
 * Send a value on a given number of bits.
5741
 * IN assertion: length <= 16 and value fits in length bits.
5742
 */
5743
function send_bits(s, value, length) {
5744
  if (s.bi_valid > (Buf_size - length)) {
5745
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
5746
    put_short(s, s.bi_buf);
5747
    s.bi_buf = value >> (Buf_size - s.bi_valid);
5748
    s.bi_valid += length - Buf_size;
5749
  } else {
5750
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
5751
    s.bi_valid += length;
5752
  }
5753
}
5754

    
5755

    
5756
function send_code(s, c, tree) {
5757
  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
5758
}
5759

    
5760

    
5761
/* ===========================================================================
5762
 * Reverse the first len bits of a code, using straightforward code (a faster
5763
 * method would use a table)
5764
 * IN assertion: 1 <= len <= 15
5765
 */
5766
function bi_reverse(code, len) {
5767
  var res = 0;
5768
  do {
5769
    res |= code & 1;
5770
    code >>>= 1;
5771
    res <<= 1;
5772
  } while (--len > 0);
5773
  return res >>> 1;
5774
}
5775

    
5776

    
5777
/* ===========================================================================
5778
 * Flush the bit buffer, keeping at most 7 bits in it.
5779
 */
5780
function bi_flush(s) {
5781
  if (s.bi_valid === 16) {
5782
    put_short(s, s.bi_buf);
5783
    s.bi_buf = 0;
5784
    s.bi_valid = 0;
5785

    
5786
  } else if (s.bi_valid >= 8) {
5787
    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
5788
    s.bi_buf >>= 8;
5789
    s.bi_valid -= 8;
5790
  }
5791
}
5792

    
5793

    
5794
/* ===========================================================================
5795
 * Compute the optimal bit lengths for a tree and update the total bit length
5796
 * for the current block.
5797
 * IN assertion: the fields freq and dad are set, heap[heap_max] and
5798
 *    above are the tree nodes sorted by increasing frequency.
5799
 * OUT assertions: the field len is set to the optimal bit length, the
5800
 *     array bl_count contains the frequencies for each bit length.
5801
 *     The length opt_len is updated; static_len is also updated if stree is
5802
 *     not null.
5803
 */
5804
function gen_bitlen(s, desc)
5805
//    deflate_state *s;
5806
//    tree_desc *desc;    /* the tree descriptor */
5807
{
5808
  var tree            = desc.dyn_tree;
5809
  var max_code        = desc.max_code;
5810
  var stree           = desc.stat_desc.static_tree;
5811
  var has_stree       = desc.stat_desc.has_stree;
5812
  var extra           = desc.stat_desc.extra_bits;
5813
  var base            = desc.stat_desc.extra_base;
5814
  var max_length      = desc.stat_desc.max_length;
5815
  var h;              /* heap index */
5816
  var n, m;           /* iterate over the tree elements */
5817
  var bits;           /* bit length */
5818
  var xbits;          /* extra bits */
5819
  var f;              /* frequency */
5820
  var overflow = 0;   /* number of elements with bit length too large */
5821

    
5822
  for (bits = 0; bits <= MAX_BITS; bits++) {
5823
    s.bl_count[bits] = 0;
5824
  }
5825

    
5826
  /* In a first pass, compute the optimal bit lengths (which may
5827
   * overflow in the case of the bit length tree).
5828
   */
5829
  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
5830

    
5831
  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
5832
    n = s.heap[h];
5833
    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
5834
    if (bits > max_length) {
5835
      bits = max_length;
5836
      overflow++;
5837
    }
5838
    tree[n * 2 + 1]/*.Len*/ = bits;
5839
    /* We overwrite tree[n].Dad which is no longer needed */
5840

    
5841
    if (n > max_code) { continue; } /* not a leaf node */
5842

    
5843
    s.bl_count[bits]++;
5844
    xbits = 0;
5845
    if (n >= base) {
5846
      xbits = extra[n - base];
5847
    }
5848
    f = tree[n * 2]/*.Freq*/;
5849
    s.opt_len += f * (bits + xbits);
5850
    if (has_stree) {
5851
      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
5852
    }
5853
  }
5854
  if (overflow === 0) { return; }
5855

    
5856
  // Trace((stderr,"\nbit length overflow\n"));
5857
  /* This happens for example on obj2 and pic of the Calgary corpus */
5858

    
5859
  /* Find the first bit length which could increase: */
5860
  do {
5861
    bits = max_length - 1;
5862
    while (s.bl_count[bits] === 0) { bits--; }
5863
    s.bl_count[bits]--;      /* move one leaf down the tree */
5864
    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
5865
    s.bl_count[max_length]--;
5866
    /* The brother of the overflow item also moves one step up,
5867
     * but this does not affect bl_count[max_length]
5868
     */
5869
    overflow -= 2;
5870
  } while (overflow > 0);
5871

    
5872
  /* Now recompute all bit lengths, scanning in increasing frequency.
5873
   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
5874
   * lengths instead of fixing only the wrong ones. This idea is taken
5875
   * from 'ar' written by Haruhiko Okumura.)
5876
   */
5877
  for (bits = max_length; bits !== 0; bits--) {
5878
    n = s.bl_count[bits];
5879
    while (n !== 0) {
5880
      m = s.heap[--h];
5881
      if (m > max_code) { continue; }
5882
      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
5883
        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
5884
        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
5885
        tree[m * 2 + 1]/*.Len*/ = bits;
5886
      }
5887
      n--;
5888
    }
5889
  }
5890
}
5891

    
5892

    
5893
/* ===========================================================================
5894
 * Generate the codes for a given tree and bit counts (which need not be
5895
 * optimal).
5896
 * IN assertion: the array bl_count contains the bit length statistics for
5897
 * the given tree and the field len is set for all tree elements.
5898
 * OUT assertion: the field code is set for all tree elements of non
5899
 *     zero code length.
5900
 */
5901
function gen_codes(tree, max_code, bl_count)
5902
//    ct_data *tree;             /* the tree to decorate */
5903
//    int max_code;              /* largest code with non zero frequency */
5904
//    ushf *bl_count;            /* number of codes at each bit length */
5905
{
5906
  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
5907
  var code = 0;              /* running code value */
5908
  var bits;                  /* bit index */
5909
  var n;                     /* code index */
5910

    
5911
  /* The distribution counts are first used to generate the code values
5912
   * without bit reversal.
5913
   */
5914
  for (bits = 1; bits <= MAX_BITS; bits++) {
5915
    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
5916
  }
5917
  /* Check that the bit counts in bl_count are consistent. The last code
5918
   * must be all ones.
5919
   */
5920
  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
5921
  //        "inconsistent bit counts");
5922
  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
5923

    
5924
  for (n = 0;  n <= max_code; n++) {
5925
    var len = tree[n * 2 + 1]/*.Len*/;
5926
    if (len === 0) { continue; }
5927
    /* Now reverse the bits */
5928
    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
5929

    
5930
    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
5931
    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
5932
  }
5933
}
5934

    
5935

    
5936
/* ===========================================================================
5937
 * Initialize the various 'constant' tables.
5938
 */
5939
function tr_static_init() {
5940
  var n;        /* iterates over tree elements */
5941
  var bits;     /* bit counter */
5942
  var length;   /* length value */
5943
  var code;     /* code value */
5944
  var dist;     /* distance index */
5945
  var bl_count = new Array(MAX_BITS + 1);
5946
  /* number of codes at each bit length for an optimal tree */
5947

    
5948
  // do check in _tr_init()
5949
  //if (static_init_done) return;
5950

    
5951
  /* For some embedded targets, global variables are not initialized: */
5952
/*#ifdef NO_INIT_GLOBAL_POINTERS
5953
  static_l_desc.static_tree = static_ltree;
5954
  static_l_desc.extra_bits = extra_lbits;
5955
  static_d_desc.static_tree = static_dtree;
5956
  static_d_desc.extra_bits = extra_dbits;
5957
  static_bl_desc.extra_bits = extra_blbits;
5958
#endif*/
5959

    
5960
  /* Initialize the mapping length (0..255) -> length code (0..28) */
5961
  length = 0;
5962
  for (code = 0; code < LENGTH_CODES - 1; code++) {
5963
    base_length[code] = length;
5964
    for (n = 0; n < (1 << extra_lbits[code]); n++) {
5965
      _length_code[length++] = code;
5966
    }
5967
  }
5968
  //Assert (length == 256, "tr_static_init: length != 256");
5969
  /* Note that the length 255 (match length 258) can be represented
5970
   * in two different ways: code 284 + 5 bits or code 285, so we
5971
   * overwrite length_code[255] to use the best encoding:
5972
   */
5973
  _length_code[length - 1] = code;
5974

    
5975
  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
5976
  dist = 0;
5977
  for (code = 0; code < 16; code++) {
5978
    base_dist[code] = dist;
5979
    for (n = 0; n < (1 << extra_dbits[code]); n++) {
5980
      _dist_code[dist++] = code;
5981
    }
5982
  }
5983
  //Assert (dist == 256, "tr_static_init: dist != 256");
5984
  dist >>= 7; /* from now on, all distances are divided by 128 */
5985
  for (; code < D_CODES; code++) {
5986
    base_dist[code] = dist << 7;
5987
    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
5988
      _dist_code[256 + dist++] = code;
5989
    }
5990
  }
5991
  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
5992

    
5993
  /* Construct the codes of the static literal tree */
5994
  for (bits = 0; bits <= MAX_BITS; bits++) {
5995
    bl_count[bits] = 0;
5996
  }
5997

    
5998
  n = 0;
5999
  while (n <= 143) {
6000
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
6001
    n++;
6002
    bl_count[8]++;
6003
  }
6004
  while (n <= 255) {
6005
    static_ltree[n * 2 + 1]/*.Len*/ = 9;
6006
    n++;
6007
    bl_count[9]++;
6008
  }
6009
  while (n <= 279) {
6010
    static_ltree[n * 2 + 1]/*.Len*/ = 7;
6011
    n++;
6012
    bl_count[7]++;
6013
  }
6014
  while (n <= 287) {
6015
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
6016
    n++;
6017
    bl_count[8]++;
6018
  }
6019
  /* Codes 286 and 287 do not exist, but we must include them in the
6020
   * tree construction to get a canonical Huffman tree (longest code
6021
   * all ones)
6022
   */
6023
  gen_codes(static_ltree, L_CODES + 1, bl_count);
6024

    
6025
  /* The static distance tree is trivial: */
6026
  for (n = 0; n < D_CODES; n++) {
6027
    static_dtree[n * 2 + 1]/*.Len*/ = 5;
6028
    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
6029
  }
6030

    
6031
  // Now data ready and we can init static trees
6032
  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
6033
  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
6034
  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
6035

    
6036
  //static_init_done = true;
6037
}
6038

    
6039

    
6040
/* ===========================================================================
6041
 * Initialize a new block.
6042
 */
6043
function init_block(s) {
6044
  var n; /* iterates over tree elements */
6045

    
6046
  /* Initialize the trees. */
6047
  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
6048
  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
6049
  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
6050

    
6051
  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
6052
  s.opt_len = s.static_len = 0;
6053
  s.last_lit = s.matches = 0;
6054
}
6055

    
6056

    
6057
/* ===========================================================================
6058
 * Flush the bit buffer and align the output on a byte boundary
6059
 */
6060
function bi_windup(s)
6061
{
6062
  if (s.bi_valid > 8) {
6063
    put_short(s, s.bi_buf);
6064
  } else if (s.bi_valid > 0) {
6065
    //put_byte(s, (Byte)s->bi_buf);
6066
    s.pending_buf[s.pending++] = s.bi_buf;
6067
  }
6068
  s.bi_buf = 0;
6069
  s.bi_valid = 0;
6070
}
6071

    
6072
/* ===========================================================================
6073
 * Copy a stored block, storing first the length and its
6074
 * one's complement if requested.
6075
 */
6076
function copy_block(s, buf, len, header)
6077
//DeflateState *s;
6078
//charf    *buf;    /* the input data */
6079
//unsigned len;     /* its length */
6080
//int      header;  /* true if block header must be written */
6081
{
6082
  bi_windup(s);        /* align on byte boundary */
6083

    
6084
  if (header) {
6085
    put_short(s, len);
6086
    put_short(s, ~len);
6087
  }
6088
//  while (len--) {
6089
//    put_byte(s, *buf++);
6090
//  }
6091
  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
6092
  s.pending += len;
6093
}
6094

    
6095
/* ===========================================================================
6096
 * Compares to subtrees, using the tree depth as tie breaker when
6097
 * the subtrees have equal frequency. This minimizes the worst case length.
6098
 */
6099
function smaller(tree, n, m, depth) {
6100
  var _n2 = n * 2;
6101
  var _m2 = m * 2;
6102
  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
6103
         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
6104
}
6105

    
6106
/* ===========================================================================
6107
 * Restore the heap property by moving down the tree starting at node k,
6108
 * exchanging a node with the smallest of its two sons if necessary, stopping
6109
 * when the heap property is re-established (each father smaller than its
6110
 * two sons).
6111
 */
6112
function pqdownheap(s, tree, k)
6113
//    deflate_state *s;
6114
//    ct_data *tree;  /* the tree to restore */
6115
//    int k;               /* node to move down */
6116
{
6117
  var v = s.heap[k];
6118
  var j = k << 1;  /* left son of k */
6119
  while (j <= s.heap_len) {
6120
    /* Set j to the smallest of the two sons: */
6121
    if (j < s.heap_len &&
6122
      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
6123
      j++;
6124
    }
6125
    /* Exit if v is smaller than both sons */
6126
    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
6127

    
6128
    /* Exchange v with the smallest son */
6129
    s.heap[k] = s.heap[j];
6130
    k = j;
6131

    
6132
    /* And continue down the tree, setting j to the left son of k */
6133
    j <<= 1;
6134
  }
6135
  s.heap[k] = v;
6136
}
6137

    
6138

    
6139
// inlined manually
6140
// var SMALLEST = 1;
6141

    
6142
/* ===========================================================================
6143
 * Send the block data compressed using the given Huffman trees
6144
 */
6145
function compress_block(s, ltree, dtree)
6146
//    deflate_state *s;
6147
//    const ct_data *ltree; /* literal tree */
6148
//    const ct_data *dtree; /* distance tree */
6149
{
6150
  var dist;           /* distance of matched string */
6151
  var lc;             /* match length or unmatched char (if dist == 0) */
6152
  var lx = 0;         /* running index in l_buf */
6153
  var code;           /* the code to send */
6154
  var extra;          /* number of extra bits to send */
6155

    
6156
  if (s.last_lit !== 0) {
6157
    do {
6158
      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
6159
      lc = s.pending_buf[s.l_buf + lx];
6160
      lx++;
6161

    
6162
      if (dist === 0) {
6163
        send_code(s, lc, ltree); /* send a literal byte */
6164
        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
6165
      } else {
6166
        /* Here, lc is the match length - MIN_MATCH */
6167
        code = _length_code[lc];
6168
        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
6169
        extra = extra_lbits[code];
6170
        if (extra !== 0) {
6171
          lc -= base_length[code];
6172
          send_bits(s, lc, extra);       /* send the extra length bits */
6173
        }
6174
        dist--; /* dist is now the match distance - 1 */
6175
        code = d_code(dist);
6176
        //Assert (code < D_CODES, "bad d_code");
6177

    
6178
        send_code(s, code, dtree);       /* send the distance code */
6179
        extra = extra_dbits[code];
6180
        if (extra !== 0) {
6181
          dist -= base_dist[code];
6182
          send_bits(s, dist, extra);   /* send the extra distance bits */
6183
        }
6184
      } /* literal or match pair ? */
6185

    
6186
      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
6187
      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
6188
      //       "pendingBuf overflow");
6189

    
6190
    } while (lx < s.last_lit);
6191
  }
6192

    
6193
  send_code(s, END_BLOCK, ltree);
6194
}
6195

    
6196

    
6197
/* ===========================================================================
6198
 * Construct one Huffman tree and assigns the code bit strings and lengths.
6199
 * Update the total bit length for the current block.
6200
 * IN assertion: the field freq is set for all tree elements.
6201
 * OUT assertions: the fields len and code are set to the optimal bit length
6202
 *     and corresponding code. The length opt_len is updated; static_len is
6203
 *     also updated if stree is not null. The field max_code is set.
6204
 */
6205
function build_tree(s, desc)
6206
//    deflate_state *s;
6207
//    tree_desc *desc; /* the tree descriptor */
6208
{
6209
  var tree     = desc.dyn_tree;
6210
  var stree    = desc.stat_desc.static_tree;
6211
  var has_stree = desc.stat_desc.has_stree;
6212
  var elems    = desc.stat_desc.elems;
6213
  var n, m;          /* iterate over heap elements */
6214
  var max_code = -1; /* largest code with non zero frequency */
6215
  var node;          /* new node being created */
6216

    
6217
  /* Construct the initial heap, with least frequent element in
6218
   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
6219
   * heap[0] is not used.
6220
   */
6221
  s.heap_len = 0;
6222
  s.heap_max = HEAP_SIZE;
6223

    
6224
  for (n = 0; n < elems; n++) {
6225
    if (tree[n * 2]/*.Freq*/ !== 0) {
6226
      s.heap[++s.heap_len] = max_code = n;
6227
      s.depth[n] = 0;
6228

    
6229
    } else {
6230
      tree[n * 2 + 1]/*.Len*/ = 0;
6231
    }
6232
  }
6233

    
6234
  /* The pkzip format requires that at least one distance code exists,
6235
   * and that at least one bit should be sent even if there is only one
6236
   * possible code. So to avoid special checks later on we force at least
6237
   * two codes of non zero frequency.
6238
   */
6239
  while (s.heap_len < 2) {
6240
    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
6241
    tree[node * 2]/*.Freq*/ = 1;
6242
    s.depth[node] = 0;
6243
    s.opt_len--;
6244

    
6245
    if (has_stree) {
6246
      s.static_len -= stree[node * 2 + 1]/*.Len*/;
6247
    }
6248
    /* node is 0 or 1 so it does not have extra bits */
6249
  }
6250
  desc.max_code = max_code;
6251

    
6252
  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
6253
   * establish sub-heaps of increasing lengths:
6254
   */
6255
  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
6256

    
6257
  /* Construct the Huffman tree by repeatedly combining the least two
6258
   * frequent nodes.
6259
   */
6260
  node = elems;              /* next internal node of the tree */
6261
  do {
6262
    //pqremove(s, tree, n);  /* n = node of least frequency */
6263
    /*** pqremove ***/
6264
    n = s.heap[1/*SMALLEST*/];
6265
    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
6266
    pqdownheap(s, tree, 1/*SMALLEST*/);
6267
    /***/
6268

    
6269
    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
6270

    
6271
    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
6272
    s.heap[--s.heap_max] = m;
6273

    
6274
    /* Create a new node father of n and m */
6275
    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
6276
    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
6277
    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
6278

    
6279
    /* and insert the new node in the heap */
6280
    s.heap[1/*SMALLEST*/] = node++;
6281
    pqdownheap(s, tree, 1/*SMALLEST*/);
6282

    
6283
  } while (s.heap_len >= 2);
6284

    
6285
  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
6286

    
6287
  /* At this point, the fields freq and dad are set. We can now
6288
   * generate the bit lengths.
6289
   */
6290
  gen_bitlen(s, desc);
6291

    
6292
  /* The field len is now set, we can generate the bit codes */
6293
  gen_codes(tree, max_code, s.bl_count);
6294
}
6295

    
6296

    
6297
/* ===========================================================================
6298
 * Scan a literal or distance tree to determine the frequencies of the codes
6299
 * in the bit length tree.
6300
 */
6301
function scan_tree(s, tree, max_code)
6302
//    deflate_state *s;
6303
//    ct_data *tree;   /* the tree to be scanned */
6304
//    int max_code;    /* and its largest code of non zero frequency */
6305
{
6306
  var n;                     /* iterates over all tree elements */
6307
  var prevlen = -1;          /* last emitted length */
6308
  var curlen;                /* length of current code */
6309

    
6310
  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
6311

    
6312
  var count = 0;             /* repeat count of the current code */
6313
  var max_count = 7;         /* max repeat count */
6314
  var min_count = 4;         /* min repeat count */
6315

    
6316
  if (nextlen === 0) {
6317
    max_count = 138;
6318
    min_count = 3;
6319
  }
6320
  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
6321

    
6322
  for (n = 0; n <= max_code; n++) {
6323
    curlen = nextlen;
6324
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
6325

    
6326
    if (++count < max_count && curlen === nextlen) {
6327
      continue;
6328

    
6329
    } else if (count < min_count) {
6330
      s.bl_tree[curlen * 2]/*.Freq*/ += count;
6331

    
6332
    } else if (curlen !== 0) {
6333

    
6334
      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
6335
      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
6336

    
6337
    } else if (count <= 10) {
6338
      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
6339

    
6340
    } else {
6341
      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
6342
    }
6343

    
6344
    count = 0;
6345
    prevlen = curlen;
6346

    
6347
    if (nextlen === 0) {
6348
      max_count = 138;
6349
      min_count = 3;
6350

    
6351
    } else if (curlen === nextlen) {
6352
      max_count = 6;
6353
      min_count = 3;
6354

    
6355
    } else {
6356
      max_count = 7;
6357
      min_count = 4;
6358
    }
6359
  }
6360
}
6361

    
6362

    
6363
/* ===========================================================================
6364
 * Send a literal or distance tree in compressed form, using the codes in
6365
 * bl_tree.
6366
 */
6367
function send_tree(s, tree, max_code)
6368
//    deflate_state *s;
6369
//    ct_data *tree; /* the tree to be scanned */
6370
//    int max_code;       /* and its largest code of non zero frequency */
6371
{
6372
  var n;                     /* iterates over all tree elements */
6373
  var prevlen = -1;          /* last emitted length */
6374
  var curlen;                /* length of current code */
6375

    
6376
  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
6377

    
6378
  var count = 0;             /* repeat count of the current code */
6379
  var max_count = 7;         /* max repeat count */
6380
  var min_count = 4;         /* min repeat count */
6381

    
6382
  /* tree[max_code+1].Len = -1; */  /* guard already set */
6383
  if (nextlen === 0) {
6384
    max_count = 138;
6385
    min_count = 3;
6386
  }
6387

    
6388
  for (n = 0; n <= max_code; n++) {
6389
    curlen = nextlen;
6390
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
6391

    
6392
    if (++count < max_count && curlen === nextlen) {
6393
      continue;
6394

    
6395
    } else if (count < min_count) {
6396
      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
6397

    
6398
    } else if (curlen !== 0) {
6399
      if (curlen !== prevlen) {
6400
        send_code(s, curlen, s.bl_tree);
6401
        count--;
6402
      }
6403
      //Assert(count >= 3 && count <= 6, " 3_6?");
6404
      send_code(s, REP_3_6, s.bl_tree);
6405
      send_bits(s, count - 3, 2);
6406

    
6407
    } else if (count <= 10) {
6408
      send_code(s, REPZ_3_10, s.bl_tree);
6409
      send_bits(s, count - 3, 3);
6410

    
6411
    } else {
6412
      send_code(s, REPZ_11_138, s.bl_tree);
6413
      send_bits(s, count - 11, 7);
6414
    }
6415

    
6416
    count = 0;
6417
    prevlen = curlen;
6418
    if (nextlen === 0) {
6419
      max_count = 138;
6420
      min_count = 3;
6421

    
6422
    } else if (curlen === nextlen) {
6423
      max_count = 6;
6424
      min_count = 3;
6425

    
6426
    } else {
6427
      max_count = 7;
6428
      min_count = 4;
6429
    }
6430
  }
6431
}
6432

    
6433

    
6434
/* ===========================================================================
6435
 * Construct the Huffman tree for the bit lengths and return the index in
6436
 * bl_order of the last bit length code to send.
6437
 */
6438
function build_bl_tree(s) {
6439
  var max_blindex;  /* index of last bit length code of non zero freq */
6440

    
6441
  /* Determine the bit length frequencies for literal and distance trees */
6442
  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
6443
  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
6444

    
6445
  /* Build the bit length tree: */
6446
  build_tree(s, s.bl_desc);
6447
  /* opt_len now includes the length of the tree representations, except
6448
   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
6449
   */
6450

    
6451
  /* Determine the number of bit length codes to send. The pkzip format
6452
   * requires that at least 4 bit length codes be sent. (appnote.txt says
6453
   * 3 but the actual value used is 4.)
6454
   */
6455
  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
6456
    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
6457
      break;
6458
    }
6459
  }
6460
  /* Update opt_len to include the bit length tree and counts */
6461
  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
6462
  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
6463
  //        s->opt_len, s->static_len));
6464

    
6465
  return max_blindex;
6466
}
6467

    
6468

    
6469
/* ===========================================================================
6470
 * Send the header for a block using dynamic Huffman trees: the counts, the
6471
 * lengths of the bit length codes, the literal tree and the distance tree.
6472
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
6473
 */
6474
function send_all_trees(s, lcodes, dcodes, blcodes)
6475
//    deflate_state *s;
6476
//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
6477
{
6478
  var rank;                    /* index in bl_order */
6479

    
6480
  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
6481
  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
6482
  //        "too many codes");
6483
  //Tracev((stderr, "\nbl counts: "));
6484
  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
6485
  send_bits(s, dcodes - 1,   5);
6486
  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
6487
  for (rank = 0; rank < blcodes; rank++) {
6488
    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
6489
    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
6490
  }
6491
  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
6492

    
6493
  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
6494
  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
6495

    
6496
  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
6497
  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
6498
}
6499

    
6500

    
6501
/* ===========================================================================
6502
 * Check if the data type is TEXT or BINARY, using the following algorithm:
6503
 * - TEXT if the two conditions below are satisfied:
6504
 *    a) There are no non-portable control characters belonging to the
6505
 *       "black list" (0..6, 14..25, 28..31).
6506
 *    b) There is at least one printable character belonging to the
6507
 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
6508
 * - BINARY otherwise.
6509
 * - The following partially-portable control characters form a
6510
 *   "gray list" that is ignored in this detection algorithm:
6511
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
6512
 * IN assertion: the fields Freq of dyn_ltree are set.
6513
 */
6514
function detect_data_type(s) {
6515
  /* black_mask is the bit mask of black-listed bytes
6516
   * set bits 0..6, 14..25, and 28..31
6517
   * 0xf3ffc07f = binary 11110011111111111100000001111111
6518
   */
6519
  var black_mask = 0xf3ffc07f;
6520
  var n;
6521

    
6522
  /* Check for non-textual ("black-listed") bytes. */
6523
  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
6524
    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
6525
      return Z_BINARY;
6526
    }
6527
  }
6528

    
6529
  /* Check for textual ("white-listed") bytes. */
6530
  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
6531
      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
6532
    return Z_TEXT;
6533
  }
6534
  for (n = 32; n < LITERALS; n++) {
6535
    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
6536
      return Z_TEXT;
6537
    }
6538
  }
6539

    
6540
  /* There are no "black-listed" or "white-listed" bytes:
6541
   * this stream either is empty or has tolerated ("gray-listed") bytes only.
6542
   */
6543
  return Z_BINARY;
6544
}
6545

    
6546

    
6547
var static_init_done = false;
6548

    
6549
/* ===========================================================================
6550
 * Initialize the tree data structures for a new zlib stream.
6551
 */
6552
function _tr_init(s)
6553
{
6554

    
6555
  if (!static_init_done) {
6556
    tr_static_init();
6557
    static_init_done = true;
6558
  }
6559

    
6560
  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
6561
  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
6562
  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
6563

    
6564
  s.bi_buf = 0;
6565
  s.bi_valid = 0;
6566

    
6567
  /* Initialize the first block of the first file: */
6568
  init_block(s);
6569
}
6570

    
6571

    
6572
/* ===========================================================================
6573
 * Send a stored block
6574
 */
6575
function _tr_stored_block(s, buf, stored_len, last)
6576
//DeflateState *s;
6577
//charf *buf;       /* input block */
6578
//ulg stored_len;   /* length of input block */
6579
//int last;         /* one if this is the last block for a file */
6580
{
6581
  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
6582
  copy_block(s, buf, stored_len, true); /* with header */
6583
}
6584

    
6585

    
6586
/* ===========================================================================
6587
 * Send one empty static block to give enough lookahead for inflate.
6588
 * This takes 10 bits, of which 7 may remain in the bit buffer.
6589
 */
6590
function _tr_align(s) {
6591
  send_bits(s, STATIC_TREES << 1, 3);
6592
  send_code(s, END_BLOCK, static_ltree);
6593
  bi_flush(s);
6594
}
6595

    
6596

    
6597
/* ===========================================================================
6598
 * Determine the best encoding for the current block: dynamic trees, static
6599
 * trees or store, and output the encoded block to the zip file.
6600
 */
6601
function _tr_flush_block(s, buf, stored_len, last)
6602
//DeflateState *s;
6603
//charf *buf;       /* input block, or NULL if too old */
6604
//ulg stored_len;   /* length of input block */
6605
//int last;         /* one if this is the last block for a file */
6606
{
6607
  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
6608
  var max_blindex = 0;        /* index of last bit length code of non zero freq */
6609

    
6610
  /* Build the Huffman trees unless a stored block is forced */
6611
  if (s.level > 0) {
6612

    
6613
    /* Check if the file is binary or text */
6614
    if (s.strm.data_type === Z_UNKNOWN) {
6615
      s.strm.data_type = detect_data_type(s);
6616
    }
6617

    
6618
    /* Construct the literal and distance trees */
6619
    build_tree(s, s.l_desc);
6620
    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
6621
    //        s->static_len));
6622

    
6623
    build_tree(s, s.d_desc);
6624
    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
6625
    //        s->static_len));
6626
    /* At this point, opt_len and static_len are the total bit lengths of
6627
     * the compressed block data, excluding the tree representations.
6628
     */
6629

    
6630
    /* Build the bit length tree for the above two trees, and get the index
6631
     * in bl_order of the last bit length code to send.
6632
     */
6633
    max_blindex = build_bl_tree(s);
6634

    
6635
    /* Determine the best encoding. Compute the block lengths in bytes. */
6636
    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
6637
    static_lenb = (s.static_len + 3 + 7) >>> 3;
6638

    
6639
    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
6640
    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
6641
    //        s->last_lit));
6642

    
6643
    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
6644

    
6645
  } else {
6646
    // Assert(buf != (char*)0, "lost buf");
6647
    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
6648
  }
6649

    
6650
  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
6651
    /* 4: two words for the lengths */
6652

    
6653
    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
6654
     * Otherwise we can't have processed more than WSIZE input bytes since
6655
     * the last block flush, because compression would have been
6656
     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
6657
     * transform a block into a stored block.
6658
     */
6659
    _tr_stored_block(s, buf, stored_len, last);
6660

    
6661
  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
6662

    
6663
    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
6664
    compress_block(s, static_ltree, static_dtree);
6665

    
6666
  } else {
6667
    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
6668
    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
6669
    compress_block(s, s.dyn_ltree, s.dyn_dtree);
6670
  }
6671
  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
6672
  /* The above check is made mod 2^32, for files larger than 512 MB
6673
   * and uLong implemented on 32 bits.
6674
   */
6675
  init_block(s);
6676

    
6677
  if (last) {
6678
    bi_windup(s);
6679
  }
6680
  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
6681
  //       s->compressed_len-7*last));
6682
}
6683

    
6684
/* ===========================================================================
6685
 * Save the match info and tally the frequency counts. Return true if
6686
 * the current block must be flushed.
6687
 */
6688
function _tr_tally(s, dist, lc)
6689
//    deflate_state *s;
6690
//    unsigned dist;  /* distance of matched string */
6691
//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
6692
{
6693
  //var out_length, in_length, dcode;
6694

    
6695
  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
6696
  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
6697

    
6698
  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
6699
  s.last_lit++;
6700

    
6701
  if (dist === 0) {
6702
    /* lc is the unmatched char */
6703
    s.dyn_ltree[lc * 2]/*.Freq*/++;
6704
  } else {
6705
    s.matches++;
6706
    /* Here, lc is the match length - MIN_MATCH */
6707
    dist--;             /* dist = match distance - 1 */
6708
    //Assert((ush)dist < (ush)MAX_DIST(s) &&
6709
    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
6710
    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
6711

    
6712
    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
6713
    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
6714
  }
6715

    
6716
// (!) This block is disabled in zlib defaults,
6717
// don't enable it for binary compatibility
6718

    
6719
//#ifdef TRUNCATE_BLOCK
6720
//  /* Try to guess if it is profitable to stop the current block here */
6721
//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
6722
//    /* Compute an upper bound for the compressed length */
6723
//    out_length = s.last_lit*8;
6724
//    in_length = s.strstart - s.block_start;
6725
//
6726
//    for (dcode = 0; dcode < D_CODES; dcode++) {
6727
//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
6728
//    }
6729
//    out_length >>>= 3;
6730
//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
6731
//    //       s->last_lit, in_length, out_length,
6732
//    //       100L - out_length*100L/in_length));
6733
//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
6734
//      return true;
6735
//    }
6736
//  }
6737
//#endif
6738

    
6739
  return (s.last_lit === s.lit_bufsize - 1);
6740
  /* We avoid equality with lit_bufsize because of wraparound at 64K
6741
   * on 16 bit machines and because stored blocks are restricted to
6742
   * 64K-1 bytes.
6743
   */
6744
}
6745

    
6746
exports._tr_init  = _tr_init;
6747
exports._tr_stored_block = _tr_stored_block;
6748
exports._tr_flush_block  = _tr_flush_block;
6749
exports._tr_tally = _tr_tally;
6750
exports._tr_align = _tr_align;
6751

    
6752
},{"../utils/common":3}],15:[function(require,module,exports){
6753
'use strict';
6754

    
6755
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
6756
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6757
//
6758
// This software is provided 'as-is', without any express or implied
6759
// warranty. In no event will the authors be held liable for any damages
6760
// arising from the use of this software.
6761
//
6762
// Permission is granted to anyone to use this software for any purpose,
6763
// including commercial applications, and to alter it and redistribute it
6764
// freely, subject to the following restrictions:
6765
//
6766
// 1. The origin of this software must not be misrepresented; you must not
6767
//   claim that you wrote the original software. If you use this software
6768
//   in a product, an acknowledgment in the product documentation would be
6769
//   appreciated but is not required.
6770
// 2. Altered source versions must be plainly marked as such, and must not be
6771
//   misrepresented as being the original software.
6772
// 3. This notice may not be removed or altered from any source distribution.
6773

    
6774
function ZStream() {
6775
  /* next input byte */
6776
  this.input = null; // JS specific, because we have no pointers
6777
  this.next_in = 0;
6778
  /* number of bytes available at input */
6779
  this.avail_in = 0;
6780
  /* total number of input bytes read so far */
6781
  this.total_in = 0;
6782
  /* next output byte should be put there */
6783
  this.output = null; // JS specific, because we have no pointers
6784
  this.next_out = 0;
6785
  /* remaining free space at output */
6786
  this.avail_out = 0;
6787
  /* total number of bytes output so far */
6788
  this.total_out = 0;
6789
  /* last error message, NULL if no error */
6790
  this.msg = ''/*Z_NULL*/;
6791
  /* not visible by applications */
6792
  this.state = null;
6793
  /* best guess about the data type: binary or text */
6794
  this.data_type = 2/*Z_UNKNOWN*/;
6795
  /* adler32 value of the uncompressed data */
6796
  this.adler = 0;
6797
}
6798

    
6799
module.exports = ZStream;
6800

    
6801
},{}],"/":[function(require,module,exports){
6802
// Top level file is just a mixin of submodules & constants
6803
'use strict';
6804

    
6805
var assign    = require('./lib/utils/common').assign;
6806

    
6807
var deflate   = require('./lib/deflate');
6808
var inflate   = require('./lib/inflate');
6809
var constants = require('./lib/zlib/constants');
6810

    
6811
var pako = {};
6812

    
6813
assign(pako, deflate, inflate, constants);
6814

    
6815
module.exports = pako;
6816

    
6817
},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")
6818
});
(1-1/6)