Switch to unified view

a b/v3/js/libs/nifti-reader.js
1
(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.nifti = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2
// Top level file is just a mixin of submodules & constants
3
'use strict';
4
5
var assign    = require('./lib/utils/common').assign;
6
7
var deflate   = require('./lib/deflate');
8
var inflate   = require('./lib/inflate');
9
var constants = require('./lib/zlib/constants');
10
11
var pako = {};
12
13
assign(pako, deflate, inflate, constants);
14
15
module.exports = pako;
16
17
},{"./lib/deflate":2,"./lib/inflate":3,"./lib/utils/common":4,"./lib/zlib/constants":7}],2:[function(require,module,exports){
18
'use strict';
19
20
21
var zlib_deflate = require('./zlib/deflate.js');
22
var utils = require('./utils/common');
23
var strings = require('./utils/strings');
24
var msg = require('./zlib/messages');
25
var zstream = require('./zlib/zstream');
26
27
var toString = Object.prototype.toString;
28
29
/* Public constants ==========================================================*/
30
/* ===========================================================================*/
31
32
var Z_NO_FLUSH      = 0;
33
var Z_FINISH        = 4;
34
35
var Z_OK            = 0;
36
var Z_STREAM_END    = 1;
37
var Z_SYNC_FLUSH    = 2;
38
39
var Z_DEFAULT_COMPRESSION = -1;
40
41
var Z_DEFAULT_STRATEGY    = 0;
42
43
var Z_DEFLATED  = 8;
44
45
/* ===========================================================================*/
46
47
48
/**
49
 * class Deflate
50
 *
51
 * Generic JS-style wrapper for zlib calls. If you don't need
52
 * streaming behaviour - use more simple functions: [[deflate]],
53
 * [[deflateRaw]] and [[gzip]].
54
 **/
55
56
/* internal
57
 * Deflate.chunks -> Array
58
 *
59
 * Chunks of output data, if [[Deflate#onData]] not overriden.
60
 **/
61
62
/**
63
 * Deflate.result -> Uint8Array|Array
64
 *
65
 * Compressed result, generated by default [[Deflate#onData]]
66
 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
67
 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
68
 * push a chunk with explicit flush (call [[Deflate#push]] with
69
 * `Z_SYNC_FLUSH` param).
70
 **/
71
72
/**
73
 * Deflate.err -> Number
74
 *
75
 * Error code after deflate finished. 0 (Z_OK) on success.
76
 * You will not need it in real life, because deflate errors
77
 * are possible only on wrong options or bad `onData` / `onEnd`
78
 * custom handlers.
79
 **/
80
81
/**
82
 * Deflate.msg -> String
83
 *
84
 * Error message, if [[Deflate.err]] != 0
85
 **/
86
87
88
/**
89
 * new Deflate(options)
90
 * - options (Object): zlib deflate options.
91
 *
92
 * Creates new deflator instance with specified params. Throws exception
93
 * on bad params. Supported options:
94
 *
95
 * - `level`
96
 * - `windowBits`
97
 * - `memLevel`
98
 * - `strategy`
99
 *
100
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
101
 * for more information on these.
102
 *
103
 * Additional options, for internal needs:
104
 *
105
 * - `chunkSize` - size of generated data chunks (16K by default)
106
 * - `raw` (Boolean) - do raw deflate
107
 * - `gzip` (Boolean) - create gzip wrapper
108
 * - `to` (String) - if equal to 'string', then result will be "binary string"
109
 *    (each char code [0..255])
110
 * - `header` (Object) - custom header for gzip
111
 *   - `text` (Boolean) - true if compressed data believed to be text
112
 *   - `time` (Number) - modification time, unix timestamp
113
 *   - `os` (Number) - operation system code
114
 *   - `extra` (Array) - array of bytes with extra data (max 65536)
115
 *   - `name` (String) - file name (binary string)
116
 *   - `comment` (String) - comment (binary string)
117
 *   - `hcrc` (Boolean) - true if header crc should be added
118
 *
119
 * ##### Example:
120
 *
121
 * ```javascript
122
 * var pako = require('pako')
123
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
124
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
125
 *
126
 * var deflate = new pako.Deflate({ level: 3});
127
 *
128
 * deflate.push(chunk1, false);
129
 * deflate.push(chunk2, true);  // true -> last chunk
130
 *
131
 * if (deflate.err) { throw new Error(deflate.err); }
132
 *
133
 * console.log(deflate.result);
134
 * ```
135
 **/
136
var Deflate = function(options) {
137
138
  this.options = utils.assign({
139
    level: Z_DEFAULT_COMPRESSION,
140
    method: Z_DEFLATED,
141
    chunkSize: 16384,
142
    windowBits: 15,
143
    memLevel: 8,
144
    strategy: Z_DEFAULT_STRATEGY,
145
    to: ''
146
  }, options || {});
147
148
  var opt = this.options;
149
150
  if (opt.raw && (opt.windowBits > 0)) {
151
    opt.windowBits = -opt.windowBits;
152
  }
153
154
  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
155
    opt.windowBits += 16;
156
  }
157
158
  this.err    = 0;      // error code, if happens (0 = Z_OK)
159
  this.msg    = '';     // error message
160
  this.ended  = false;  // used to avoid multiple onEnd() calls
161
  this.chunks = [];     // chunks of compressed data
162
163
  this.strm = new zstream();
164
  this.strm.avail_out = 0;
165
166
  var status = zlib_deflate.deflateInit2(
167
    this.strm,
168
    opt.level,
169
    opt.method,
170
    opt.windowBits,
171
    opt.memLevel,
172
    opt.strategy
173
  );
174
175
  if (status !== Z_OK) {
176
    throw new Error(msg[status]);
177
  }
178
179
  if (opt.header) {
180
    zlib_deflate.deflateSetHeader(this.strm, opt.header);
181
  }
182
};
183
184
/**
185
 * Deflate#push(data[, mode]) -> Boolean
186
 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
187
 *   converted to utf8 byte sequence.
188
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
189
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
190
 *
191
 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
192
 * new compressed chunks. Returns `true` on success. The last data block must have
193
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
194
 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
195
 * can use mode Z_SYNC_FLUSH, keeping the compression context.
196
 *
197
 * On fail call [[Deflate#onEnd]] with error code and return false.
198
 *
199
 * We strongly recommend to use `Uint8Array` on input for best speed (output
200
 * array format is detected automatically). Also, don't skip last param and always
201
 * use the same type in your code (boolean or number). That will improve JS speed.
202
 *
203
 * For regular `Array`-s make sure all elements are [0..255].
204
 *
205
 * ##### Example
206
 *
207
 * ```javascript
208
 * push(chunk, false); // push one of data chunks
209
 * ...
210
 * push(chunk, true);  // push last chunk
211
 * ```
212
 **/
213
Deflate.prototype.push = function(data, mode) {
214
  var strm = this.strm;
215
  var chunkSize = this.options.chunkSize;
216
  var status, _mode;
217
218
  if (this.ended) { return false; }
219
220
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
221
222
  // Convert data if needed
223
  if (typeof data === 'string') {
224
    // If we need to compress text, change encoding to utf8.
225
    strm.input = strings.string2buf(data);
226
  } else if (toString.call(data) === '[object ArrayBuffer]') {
227
    strm.input = new Uint8Array(data);
228
  } else {
229
    strm.input = data;
230
  }
231
232
  strm.next_in = 0;
233
  strm.avail_in = strm.input.length;
234
235
  do {
236
    if (strm.avail_out === 0) {
237
      strm.output = new utils.Buf8(chunkSize);
238
      strm.next_out = 0;
239
      strm.avail_out = chunkSize;
240
    }
241
    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
242
243
    if (status !== Z_STREAM_END && status !== Z_OK) {
244
      this.onEnd(status);
245
      this.ended = true;
246
      return false;
247
    }
248
    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
249
      if (this.options.to === 'string') {
250
        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
251
      } else {
252
        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
253
      }
254
    }
255
  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
256
257
  // Finalize on the last chunk.
258
  if (_mode === Z_FINISH) {
259
    status = zlib_deflate.deflateEnd(this.strm);
260
    this.onEnd(status);
261
    this.ended = true;
262
    return status === Z_OK;
263
  }
264
265
  // callback interim results if Z_SYNC_FLUSH.
266
  if (_mode === Z_SYNC_FLUSH) {
267
    this.onEnd(Z_OK);
268
    strm.avail_out = 0;
269
    return true;
270
  }
271
272
  return true;
273
};
274
275
276
/**
277
 * Deflate#onData(chunk) -> Void
278
 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
279
 *   on js engine support. When string output requested, each chunk
280
 *   will be string.
281
 *
282
 * By default, stores data blocks in `chunks[]` property and glue
283
 * those in `onEnd`. Override this handler, if you need another behaviour.
284
 **/
285
Deflate.prototype.onData = function(chunk) {
286
  this.chunks.push(chunk);
287
};
288
289
290
/**
291
 * Deflate#onEnd(status) -> Void
292
 * - status (Number): deflate status. 0 (Z_OK) on success,
293
 *   other if not.
294
 *
295
 * Called once after you tell deflate that the input stream is
296
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
297
 * or if an error happened. By default - join collected chunks,
298
 * free memory and fill `results` / `err` properties.
299
 **/
300
Deflate.prototype.onEnd = function(status) {
301
  // On success - join
302
  if (status === Z_OK) {
303
    if (this.options.to === 'string') {
304
      this.result = this.chunks.join('');
305
    } else {
306
      this.result = utils.flattenChunks(this.chunks);
307
    }
308
  }
309
  this.chunks = [];
310
  this.err = status;
311
  this.msg = this.strm.msg;
312
};
313
314
315
/**
316
 * deflate(data[, options]) -> Uint8Array|Array|String
317
 * - data (Uint8Array|Array|String): input data to compress.
318
 * - options (Object): zlib deflate options.
319
 *
320
 * Compress `data` with deflate alrorythm and `options`.
321
 *
322
 * Supported options are:
323
 *
324
 * - level
325
 * - windowBits
326
 * - memLevel
327
 * - strategy
328
 *
329
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
330
 * for more information on these.
331
 *
332
 * Sugar (options):
333
 *
334
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
335
 *   negative windowBits implicitly.
336
 * - `to` (String) - if equal to 'string', then result will be "binary string"
337
 *    (each char code [0..255])
338
 *
339
 * ##### Example:
340
 *
341
 * ```javascript
342
 * var pako = require('pako')
343
 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
344
 *
345
 * console.log(pako.deflate(data));
346
 * ```
347
 **/
348
function deflate(input, options) {
349
  var deflator = new Deflate(options);
350
351
  deflator.push(input, true);
352
353
  // That will never happens, if you don't cheat with options :)
354
  if (deflator.err) { throw deflator.msg; }
355
356
  return deflator.result;
357
}
358
359
360
/**
361
 * deflateRaw(data[, options]) -> Uint8Array|Array|String
362
 * - data (Uint8Array|Array|String): input data to compress.
363
 * - options (Object): zlib deflate options.
364
 *
365
 * The same as [[deflate]], but creates raw data, without wrapper
366
 * (header and adler32 crc).
367
 **/
368
function deflateRaw(input, options) {
369
  options = options || {};
370
  options.raw = true;
371
  return deflate(input, options);
372
}
373
374
375
/**
376
 * gzip(data[, options]) -> Uint8Array|Array|String
377
 * - data (Uint8Array|Array|String): input data to compress.
378
 * - options (Object): zlib deflate options.
379
 *
380
 * The same as [[deflate]], but create gzip wrapper instead of
381
 * deflate one.
382
 **/
383
function gzip(input, options) {
384
  options = options || {};
385
  options.gzip = true;
386
  return deflate(input, options);
387
}
388
389
390
exports.Deflate = Deflate;
391
exports.deflate = deflate;
392
exports.deflateRaw = deflateRaw;
393
exports.gzip = gzip;
394
395
},{"./utils/common":4,"./utils/strings":5,"./zlib/deflate.js":9,"./zlib/messages":14,"./zlib/zstream":16}],3:[function(require,module,exports){
396
'use strict';
397
398
399
var zlib_inflate = require('./zlib/inflate.js');
400
var utils = require('./utils/common');
401
var strings = require('./utils/strings');
402
var c = require('./zlib/constants');
403
var msg = require('./zlib/messages');
404
var zstream = require('./zlib/zstream');
405
var gzheader = require('./zlib/gzheader');
406
407
var toString = Object.prototype.toString;
408
409
/**
410
 * class Inflate
411
 *
412
 * Generic JS-style wrapper for zlib calls. If you don't need
413
 * streaming behaviour - use more simple functions: [[inflate]]
414
 * and [[inflateRaw]].
415
 **/
416
417
/* internal
418
 * inflate.chunks -> Array
419
 *
420
 * Chunks of output data, if [[Inflate#onData]] not overriden.
421
 **/
422
423
/**
424
 * Inflate.result -> Uint8Array|Array|String
425
 *
426
 * Uncompressed result, generated by default [[Inflate#onData]]
427
 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
428
 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
429
 * push a chunk with explicit flush (call [[Inflate#push]] with
430
 * `Z_SYNC_FLUSH` param).
431
 **/
432
433
/**
434
 * Inflate.err -> Number
435
 *
436
 * Error code after inflate finished. 0 (Z_OK) on success.
437
 * Should be checked if broken data possible.
438
 **/
439
440
/**
441
 * Inflate.msg -> String
442
 *
443
 * Error message, if [[Inflate.err]] != 0
444
 **/
445
446
447
/**
448
 * new Inflate(options)
449
 * - options (Object): zlib inflate options.
450
 *
451
 * Creates new inflator instance with specified params. Throws exception
452
 * on bad params. Supported options:
453
 *
454
 * - `windowBits`
455
 *
456
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
457
 * for more information on these.
458
 *
459
 * Additional options, for internal needs:
460
 *
461
 * - `chunkSize` - size of generated data chunks (16K by default)
462
 * - `raw` (Boolean) - do raw inflate
463
 * - `to` (String) - if equal to 'string', then result will be converted
464
 *   from utf8 to utf16 (javascript) string. When string output requested,
465
 *   chunk length can differ from `chunkSize`, depending on content.
466
 *
467
 * By default, when no options set, autodetect deflate/gzip data format via
468
 * wrapper header.
469
 *
470
 * ##### Example:
471
 *
472
 * ```javascript
473
 * var pako = require('pako')
474
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
475
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
476
 *
477
 * var inflate = new pako.Inflate({ level: 3});
478
 *
479
 * inflate.push(chunk1, false);
480
 * inflate.push(chunk2, true);  // true -> last chunk
481
 *
482
 * if (inflate.err) { throw new Error(inflate.err); }
483
 *
484
 * console.log(inflate.result);
485
 * ```
486
 **/
487
var Inflate = function(options) {
488
489
  this.options = utils.assign({
490
    chunkSize: 16384,
491
    windowBits: 0,
492
    to: ''
493
  }, options || {});
494
495
  var opt = this.options;
496
497
  // Force window size for `raw` data, if not set directly,
498
  // because we have no header for autodetect.
499
  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
500
    opt.windowBits = -opt.windowBits;
501
    if (opt.windowBits === 0) { opt.windowBits = -15; }
502
  }
503
504
  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
505
  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
506
      !(options && options.windowBits)) {
507
    opt.windowBits += 32;
508
  }
509
510
  // Gzip header has no info about windows size, we can do autodetect only
511
  // for deflate. So, if window size not set, force it to max when gzip possible
512
  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
513
    // bit 3 (16) -> gzipped data
514
    // bit 4 (32) -> autodetect gzip/deflate
515
    if ((opt.windowBits & 15) === 0) {
516
      opt.windowBits |= 15;
517
    }
518
  }
519
520
  this.err    = 0;      // error code, if happens (0 = Z_OK)
521
  this.msg    = '';     // error message
522
  this.ended  = false;  // used to avoid multiple onEnd() calls
523
  this.chunks = [];     // chunks of compressed data
524
525
  this.strm   = new zstream();
526
  this.strm.avail_out = 0;
527
528
  var status  = zlib_inflate.inflateInit2(
529
    this.strm,
530
    opt.windowBits
531
  );
532
533
  if (status !== c.Z_OK) {
534
    throw new Error(msg[status]);
535
  }
536
537
  this.header = new gzheader();
538
539
  zlib_inflate.inflateGetHeader(this.strm, this.header);
540
};
541
542
/**
543
 * Inflate#push(data[, mode]) -> Boolean
544
 * - data (Uint8Array|Array|ArrayBuffer|String): input data
545
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
546
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
547
 *
548
 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
549
 * new output chunks. Returns `true` on success. The last data block must have
550
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
551
 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
552
 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
553
 *
554
 * On fail call [[Inflate#onEnd]] with error code and return false.
555
 *
556
 * We strongly recommend to use `Uint8Array` on input for best speed (output
557
 * format is detected automatically). Also, don't skip last param and always
558
 * use the same type in your code (boolean or number). That will improve JS speed.
559
 *
560
 * For regular `Array`-s make sure all elements are [0..255].
561
 *
562
 * ##### Example
563
 *
564
 * ```javascript
565
 * push(chunk, false); // push one of data chunks
566
 * ...
567
 * push(chunk, true);  // push last chunk
568
 * ```
569
 **/
570
Inflate.prototype.push = function(data, mode) {
571
  var strm = this.strm;
572
  var chunkSize = this.options.chunkSize;
573
  var status, _mode;
574
  var next_out_utf8, tail, utf8str;
575
576
  // Flag to properly process Z_BUF_ERROR on testing inflate call
577
  // when we check that all output data was flushed.
578
  var allowBufError = false;
579
580
  if (this.ended) { return false; }
581
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
582
583
  // Convert data if needed
584
  if (typeof data === 'string') {
585
    // Only binary strings can be decompressed on practice
586
    strm.input = strings.binstring2buf(data);
587
  } else if (toString.call(data) === '[object ArrayBuffer]') {
588
    strm.input = new Uint8Array(data);
589
  } else {
590
    strm.input = data;
591
  }
592
593
  strm.next_in = 0;
594
  strm.avail_in = strm.input.length;
595
596
  do {
597
    if (strm.avail_out === 0) {
598
      strm.output = new utils.Buf8(chunkSize);
599
      strm.next_out = 0;
600
      strm.avail_out = chunkSize;
601
    }
602
603
    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
604
605
    if (status === c.Z_BUF_ERROR && allowBufError === true) {
606
      status = c.Z_OK;
607
      allowBufError = false;
608
    }
609
610
    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
611
      this.onEnd(status);
612
      this.ended = true;
613
      return false;
614
    }
615
616
    if (strm.next_out) {
617
      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
618
619
        if (this.options.to === 'string') {
620
621
          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
622
623
          tail = strm.next_out - next_out_utf8;
624
          utf8str = strings.buf2string(strm.output, next_out_utf8);
625
626
          // move tail
627
          strm.next_out = tail;
628
          strm.avail_out = chunkSize - tail;
629
          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
630
631
          this.onData(utf8str);
632
633
        } else {
634
          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
635
        }
636
      }
637
    }
638
639
    // When no more input data, we should check that internal inflate buffers
640
    // are flushed. The only way to do it when avail_out = 0 - run one more
641
    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
642
    // Here we set flag to process this error properly.
643
    //
644
    // NOTE. Deflate does not return error in this case and does not needs such
645
    // logic.
646
    if (strm.avail_in === 0 && strm.avail_out === 0) {
647
      allowBufError = true;
648
    }
649
650
  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
651
652
  if (status === c.Z_STREAM_END) {
653
    _mode = c.Z_FINISH;
654
  }
655
656
  // Finalize on the last chunk.
657
  if (_mode === c.Z_FINISH) {
658
    status = zlib_inflate.inflateEnd(this.strm);
659
    this.onEnd(status);
660
    this.ended = true;
661
    return status === c.Z_OK;
662
  }
663
664
  // callback interim results if Z_SYNC_FLUSH.
665
  if (_mode === c.Z_SYNC_FLUSH) {
666
    this.onEnd(c.Z_OK);
667
    strm.avail_out = 0;
668
    return true;
669
  }
670
671
  return true;
672
};
673
674
675
/**
676
 * Inflate#onData(chunk) -> Void
677
 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
678
 *   on js engine support. When string output requested, each chunk
679
 *   will be string.
680
 *
681
 * By default, stores data blocks in `chunks[]` property and glue
682
 * those in `onEnd`. Override this handler, if you need another behaviour.
683
 **/
684
Inflate.prototype.onData = function(chunk) {
685
  this.chunks.push(chunk);
686
};
687
688
689
/**
690
 * Inflate#onEnd(status) -> Void
691
 * - status (Number): inflate status. 0 (Z_OK) on success,
692
 *   other if not.
693
 *
694
 * Called either after you tell inflate that the input stream is
695
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
696
 * or if an error happened. By default - join collected chunks,
697
 * free memory and fill `results` / `err` properties.
698
 **/
699
Inflate.prototype.onEnd = function(status) {
700
  // On success - join
701
  if (status === c.Z_OK) {
702
    if (this.options.to === 'string') {
703
      // Glue & convert here, until we teach pako to send
704
      // utf8 alligned strings to onData
705
      this.result = this.chunks.join('');
706
    } else {
707
      this.result = utils.flattenChunks(this.chunks);
708
    }
709
  }
710
  this.chunks = [];
711
  this.err = status;
712
  this.msg = this.strm.msg;
713
};
714
715
716
/**
717
 * inflate(data[, options]) -> Uint8Array|Array|String
718
 * - data (Uint8Array|Array|String): input data to decompress.
719
 * - options (Object): zlib inflate options.
720
 *
721
 * Decompress `data` with inflate/ungzip and `options`. Autodetect
722
 * format via wrapper header by default. That's why we don't provide
723
 * separate `ungzip` method.
724
 *
725
 * Supported options are:
726
 *
727
 * - windowBits
728
 *
729
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
730
 * for more information.
731
 *
732
 * Sugar (options):
733
 *
734
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
735
 *   negative windowBits implicitly.
736
 * - `to` (String) - if equal to 'string', then result will be converted
737
 *   from utf8 to utf16 (javascript) string. When string output requested,
738
 *   chunk length can differ from `chunkSize`, depending on content.
739
 *
740
 *
741
 * ##### Example:
742
 *
743
 * ```javascript
744
 * var pako = require('pako')
745
 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
746
 *   , output;
747
 *
748
 * try {
749
 *   output = pako.inflate(input);
750
 * } catch (err)
751
 *   console.log(err);
752
 * }
753
 * ```
754
 **/
755
function inflate(input, options) {
756
  var inflator = new Inflate(options);
757
758
  inflator.push(input, true);
759
760
  // That will never happens, if you don't cheat with options :)
761
  if (inflator.err) { throw inflator.msg; }
762
763
  return inflator.result;
764
}
765
766
767
/**
768
 * inflateRaw(data[, options]) -> Uint8Array|Array|String
769
 * - data (Uint8Array|Array|String): input data to decompress.
770
 * - options (Object): zlib inflate options.
771
 *
772
 * The same as [[inflate]], but creates raw data, without wrapper
773
 * (header and adler32 crc).
774
 **/
775
function inflateRaw(input, options) {
776
  options = options || {};
777
  options.raw = true;
778
  return inflate(input, options);
779
}
780
781
782
/**
783
 * ungzip(data[, options]) -> Uint8Array|Array|String
784
 * - data (Uint8Array|Array|String): input data to decompress.
785
 * - options (Object): zlib inflate options.
786
 *
787
 * Just shortcut to [[inflate]], because it autodetects format
788
 * by header.content. Done for convenience.
789
 **/
790
791
792
exports.Inflate = Inflate;
793
exports.inflate = inflate;
794
exports.inflateRaw = inflateRaw;
795
exports.ungzip  = inflate;
796
797
},{"./utils/common":4,"./utils/strings":5,"./zlib/constants":7,"./zlib/gzheader":10,"./zlib/inflate.js":12,"./zlib/messages":14,"./zlib/zstream":16}],4:[function(require,module,exports){
798
'use strict';
799
800
801
var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
802
                (typeof Uint16Array !== 'undefined') &&
803
                (typeof Int32Array !== 'undefined');
804
805
806
exports.assign = function (obj /*from1, from2, from3, ...*/) {
807
  var sources = Array.prototype.slice.call(arguments, 1);
808
  while (sources.length) {
809
    var source = sources.shift();
810
    if (!source) { continue; }
811
812
    if (typeof source !== 'object') {
813
      throw new TypeError(source + 'must be non-object');
814
    }
815
816
    for (var p in source) {
817
      if (source.hasOwnProperty(p)) {
818
        obj[p] = source[p];
819
      }
820
    }
821
  }
822
823
  return obj;
824
};
825
826
827
// reduce buffer size, avoiding mem copy
828
exports.shrinkBuf = function (buf, size) {
829
  if (buf.length === size) { return buf; }
830
  if (buf.subarray) { return buf.subarray(0, size); }
831
  buf.length = size;
832
  return buf;
833
};
834
835
836
var fnTyped = {
837
  arraySet: function (dest, src, src_offs, len, dest_offs) {
838
    if (src.subarray && dest.subarray) {
839
      dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
840
      return;
841
    }
842
    // Fallback to ordinary array
843
    for (var i=0; i<len; i++) {
844
      dest[dest_offs + i] = src[src_offs + i];
845
    }
846
  },
847
  // Join array of chunks to single array.
848
  flattenChunks: function(chunks) {
849
    var i, l, len, pos, chunk, result;
850
851
    // calculate data length
852
    len = 0;
853
    for (i=0, l=chunks.length; i<l; i++) {
854
      len += chunks[i].length;
855
    }
856
857
    // join chunks
858
    result = new Uint8Array(len);
859
    pos = 0;
860
    for (i=0, l=chunks.length; i<l; i++) {
861
      chunk = chunks[i];
862
      result.set(chunk, pos);
863
      pos += chunk.length;
864
    }
865
866
    return result;
867
  }
868
};
869
870
var fnUntyped = {
871
  arraySet: function (dest, src, src_offs, len, dest_offs) {
872
    for (var i=0; i<len; i++) {
873
      dest[dest_offs + i] = src[src_offs + i];
874
    }
875
  },
876
  // Join array of chunks to single array.
877
  flattenChunks: function(chunks) {
878
    return [].concat.apply([], chunks);
879
  }
880
};
881
882
883
// Enable/Disable typed arrays use, for testing
884
//
885
exports.setTyped = function (on) {
886
  if (on) {
887
    exports.Buf8  = Uint8Array;
888
    exports.Buf16 = Uint16Array;
889
    exports.Buf32 = Int32Array;
890
    exports.assign(exports, fnTyped);
891
  } else {
892
    exports.Buf8  = Array;
893
    exports.Buf16 = Array;
894
    exports.Buf32 = Array;
895
    exports.assign(exports, fnUntyped);
896
  }
897
};
898
899
exports.setTyped(TYPED_OK);
900
901
},{}],5:[function(require,module,exports){
902
// String encode/decode helpers
903
'use strict';
904
905
906
var utils = require('./common');
907
908
909
// Quick check if we can use fast array to bin string conversion
910
//
911
// - apply(Array) can fail on Android 2.2
912
// - apply(Uint8Array) can fail on iOS 5.1 Safary
913
//
914
var STR_APPLY_OK = true;
915
var STR_APPLY_UIA_OK = true;
916
917
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
918
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
919
920
921
// Table with utf8 lengths (calculated by first byte of sequence)
922
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
923
// because max possible codepoint is 0x10ffff
924
var _utf8len = new utils.Buf8(256);
925
for (var q=0; q<256; q++) {
926
  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
927
}
928
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
929
930
931
// convert string to array (typed, when possible)
932
exports.string2buf = function (str) {
933
  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
934
935
  // count binary size
936
  for (m_pos = 0; m_pos < str_len; m_pos++) {
937
    c = str.charCodeAt(m_pos);
938
    if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
939
      c2 = str.charCodeAt(m_pos+1);
940
      if ((c2 & 0xfc00) === 0xdc00) {
941
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
942
        m_pos++;
943
      }
944
    }
945
    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
946
  }
947
948
  // allocate buffer
949
  buf = new utils.Buf8(buf_len);
950
951
  // convert
952
  for (i=0, m_pos = 0; i < buf_len; m_pos++) {
953
    c = str.charCodeAt(m_pos);
954
    if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
955
      c2 = str.charCodeAt(m_pos+1);
956
      if ((c2 & 0xfc00) === 0xdc00) {
957
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
958
        m_pos++;
959
      }
960
    }
961
    if (c < 0x80) {
962
      /* one byte */
963
      buf[i++] = c;
964
    } else if (c < 0x800) {
965
      /* two bytes */
966
      buf[i++] = 0xC0 | (c >>> 6);
967
      buf[i++] = 0x80 | (c & 0x3f);
968
    } else if (c < 0x10000) {
969
      /* three bytes */
970
      buf[i++] = 0xE0 | (c >>> 12);
971
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
972
      buf[i++] = 0x80 | (c & 0x3f);
973
    } else {
974
      /* four bytes */
975
      buf[i++] = 0xf0 | (c >>> 18);
976
      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
977
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
978
      buf[i++] = 0x80 | (c & 0x3f);
979
    }
980
  }
981
982
  return buf;
983
};
984
985
// Helper (used in 2 places)
986
function buf2binstring(buf, len) {
987
  // use fallback for big arrays to avoid stack overflow
988
  if (len < 65537) {
989
    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
990
      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
991
    }
992
  }
993
994
  var result = '';
995
  for (var i=0; i < len; i++) {
996
    result += String.fromCharCode(buf[i]);
997
  }
998
  return result;
999
}
1000
1001
1002
// Convert byte array to binary string
1003
exports.buf2binstring = function(buf) {
1004
  return buf2binstring(buf, buf.length);
1005
};
1006
1007
1008
// Convert binary string (typed, when possible)
1009
exports.binstring2buf = function(str) {
1010
  var buf = new utils.Buf8(str.length);
1011
  for (var i=0, len=buf.length; i < len; i++) {
1012
    buf[i] = str.charCodeAt(i);
1013
  }
1014
  return buf;
1015
};
1016
1017
1018
// convert array to string
1019
exports.buf2string = function (buf, max) {
1020
  var i, out, c, c_len;
1021
  var len = max || buf.length;
1022
1023
  // Reserve max possible length (2 words per char)
1024
  // NB: by unknown reasons, Array is significantly faster for
1025
  //     String.fromCharCode.apply than Uint16Array.
1026
  var utf16buf = new Array(len*2);
1027
1028
  for (out=0, i=0; i<len;) {
1029
    c = buf[i++];
1030
    // quick process ascii
1031
    if (c < 0x80) { utf16buf[out++] = c; continue; }
1032
1033
    c_len = _utf8len[c];
1034
    // skip 5 & 6 byte codes
1035
    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
1036
1037
    // apply mask on first byte
1038
    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
1039
    // join the rest
1040
    while (c_len > 1 && i < len) {
1041
      c = (c << 6) | (buf[i++] & 0x3f);
1042
      c_len--;
1043
    }
1044
1045
    // terminated by end of string?
1046
    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
1047
1048
    if (c < 0x10000) {
1049
      utf16buf[out++] = c;
1050
    } else {
1051
      c -= 0x10000;
1052
      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
1053
      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
1054
    }
1055
  }
1056
1057
  return buf2binstring(utf16buf, out);
1058
};
1059
1060
1061
// Calculate max possible position in utf8 buffer,
1062
// that will not break sequence. If that's not possible
1063
// - (very small limits) return max size as is.
1064
//
1065
// buf[] - utf8 bytes array
1066
// max   - length limit (mandatory);
1067
exports.utf8border = function(buf, max) {
1068
  var pos;
1069
1070
  max = max || buf.length;
1071
  if (max > buf.length) { max = buf.length; }
1072
1073
  // go back from last position, until start of sequence found
1074
  pos = max-1;
1075
  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
1076
1077
  // Fuckup - very small and broken sequence,
1078
  // return max, because we should return something anyway.
1079
  if (pos < 0) { return max; }
1080
1081
  // If we came to start of buffer - that means vuffer is too small,
1082
  // return max too.
1083
  if (pos === 0) { return max; }
1084
1085
  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
1086
};
1087
1088
},{"./common":4}],6:[function(require,module,exports){
1089
'use strict';
1090
1091
// Note: adler32 takes 12% for level 0 and 2% for level 6.
1092
// It doesn't worth to make additional optimizationa as in original.
1093
// Small size is preferable.
1094
1095
function adler32(adler, buf, len, pos) {
1096
  var s1 = (adler & 0xffff) |0,
1097
      s2 = ((adler >>> 16) & 0xffff) |0,
1098
      n = 0;
1099
1100
  while (len !== 0) {
1101
    // Set limit ~ twice less than 5552, to keep
1102
    // s2 in 31-bits, because we force signed ints.
1103
    // in other case %= will fail.
1104
    n = len > 2000 ? 2000 : len;
1105
    len -= n;
1106
1107
    do {
1108
      s1 = (s1 + buf[pos++]) |0;
1109
      s2 = (s2 + s1) |0;
1110
    } while (--n);
1111
1112
    s1 %= 65521;
1113
    s2 %= 65521;
1114
  }
1115
1116
  return (s1 | (s2 << 16)) |0;
1117
}
1118
1119
1120
module.exports = adler32;
1121
1122
},{}],7:[function(require,module,exports){
1123
module.exports = {
1124
1125
  /* Allowed flush values; see deflate() and inflate() below for details */
1126
  Z_NO_FLUSH:         0,
1127
  Z_PARTIAL_FLUSH:    1,
1128
  Z_SYNC_FLUSH:       2,
1129
  Z_FULL_FLUSH:       3,
1130
  Z_FINISH:           4,
1131
  Z_BLOCK:            5,
1132
  Z_TREES:            6,
1133
1134
  /* Return codes for the compression/decompression functions. Negative values
1135
  * are errors, positive values are used for special but normal events.
1136
  */
1137
  Z_OK:               0,
1138
  Z_STREAM_END:       1,
1139
  Z_NEED_DICT:        2,
1140
  Z_ERRNO:           -1,
1141
  Z_STREAM_ERROR:    -2,
1142
  Z_DATA_ERROR:      -3,
1143
  //Z_MEM_ERROR:     -4,
1144
  Z_BUF_ERROR:       -5,
1145
  //Z_VERSION_ERROR: -6,
1146
1147
  /* compression levels */
1148
  Z_NO_COMPRESSION:         0,
1149
  Z_BEST_SPEED:             1,
1150
  Z_BEST_COMPRESSION:       9,
1151
  Z_DEFAULT_COMPRESSION:   -1,
1152
1153
1154
  Z_FILTERED:               1,
1155
  Z_HUFFMAN_ONLY:           2,
1156
  Z_RLE:                    3,
1157
  Z_FIXED:                  4,
1158
  Z_DEFAULT_STRATEGY:       0,
1159
1160
  /* Possible values of the data_type field (though see inflate()) */
1161
  Z_BINARY:                 0,
1162
  Z_TEXT:                   1,
1163
  //Z_ASCII:                1, // = Z_TEXT (deprecated)
1164
  Z_UNKNOWN:                2,
1165
1166
  /* The deflate compression method */
1167
  Z_DEFLATED:               8
1168
  //Z_NULL:                 null // Use -1 or null inline, depending on var type
1169
};
1170
1171
},{}],8:[function(require,module,exports){
1172
'use strict';
1173
1174
// Note: we can't get significant speed boost here.
1175
// So write code to minimize size - no pregenerated tables
1176
// and array tools dependencies.
1177
1178
1179
// Use ordinary array, since untyped makes no boost here
1180
function makeTable() {
1181
  var c, table = [];
1182
1183
  for (var n =0; n < 256; n++) {
1184
    c = n;
1185
    for (var k =0; k < 8; k++) {
1186
      c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
1187
    }
1188
    table[n] = c;
1189
  }
1190
1191
  return table;
1192
}
1193
1194
// Create table on load. Just 255 signed longs. Not a problem.
1195
var crcTable = makeTable();
1196
1197
1198
function crc32(crc, buf, len, pos) {
1199
  var t = crcTable,
1200
      end = pos + len;
1201
1202
  crc = crc ^ (-1);
1203
1204
  for (var i = pos; i < end; i++) {
1205
    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
1206
  }
1207
1208
  return (crc ^ (-1)); // >>> 0;
1209
}
1210
1211
1212
module.exports = crc32;
1213
1214
},{}],9:[function(require,module,exports){
1215
'use strict';
1216
1217
var utils   = require('../utils/common');
1218
var trees   = require('./trees');
1219
var adler32 = require('./adler32');
1220
var crc32   = require('./crc32');
1221
var msg   = require('./messages');
1222
1223
/* Public constants ==========================================================*/
1224
/* ===========================================================================*/
1225
1226
1227
/* Allowed flush values; see deflate() and inflate() below for details */
1228
var Z_NO_FLUSH      = 0;
1229
var Z_PARTIAL_FLUSH = 1;
1230
//var Z_SYNC_FLUSH    = 2;
1231
var Z_FULL_FLUSH    = 3;
1232
var Z_FINISH        = 4;
1233
var Z_BLOCK         = 5;
1234
//var Z_TREES         = 6;
1235
1236
1237
/* Return codes for the compression/decompression functions. Negative values
1238
 * are errors, positive values are used for special but normal events.
1239
 */
1240
var Z_OK            = 0;
1241
var Z_STREAM_END    = 1;
1242
//var Z_NEED_DICT     = 2;
1243
//var Z_ERRNO         = -1;
1244
var Z_STREAM_ERROR  = -2;
1245
var Z_DATA_ERROR    = -3;
1246
//var Z_MEM_ERROR     = -4;
1247
var Z_BUF_ERROR     = -5;
1248
//var Z_VERSION_ERROR = -6;
1249
1250
1251
/* compression levels */
1252
//var Z_NO_COMPRESSION      = 0;
1253
//var Z_BEST_SPEED          = 1;
1254
//var Z_BEST_COMPRESSION    = 9;
1255
var Z_DEFAULT_COMPRESSION = -1;
1256
1257
1258
var Z_FILTERED            = 1;
1259
var Z_HUFFMAN_ONLY        = 2;
1260
var Z_RLE                 = 3;
1261
var Z_FIXED               = 4;
1262
var Z_DEFAULT_STRATEGY    = 0;
1263
1264
/* Possible values of the data_type field (though see inflate()) */
1265
//var Z_BINARY              = 0;
1266
//var Z_TEXT                = 1;
1267
//var Z_ASCII               = 1; // = Z_TEXT
1268
var Z_UNKNOWN             = 2;
1269
1270
1271
/* The deflate compression method */
1272
var Z_DEFLATED  = 8;
1273
1274
/*============================================================================*/
1275
1276
1277
var MAX_MEM_LEVEL = 9;
1278
/* Maximum value for memLevel in deflateInit2 */
1279
var MAX_WBITS = 15;
1280
/* 32K LZ77 window */
1281
var DEF_MEM_LEVEL = 8;
1282
1283
1284
var LENGTH_CODES  = 29;
1285
/* number of length codes, not counting the special END_BLOCK code */
1286
var LITERALS      = 256;
1287
/* number of literal bytes 0..255 */
1288
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
1289
/* number of Literal or Length codes, including the END_BLOCK code */
1290
var D_CODES       = 30;
1291
/* number of distance codes */
1292
var BL_CODES      = 19;
1293
/* number of codes used to transfer the bit lengths */
1294
var HEAP_SIZE     = 2*L_CODES + 1;
1295
/* maximum heap size */
1296
var MAX_BITS  = 15;
1297
/* All codes must not exceed MAX_BITS bits */
1298
1299
var MIN_MATCH = 3;
1300
var MAX_MATCH = 258;
1301
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
1302
1303
var PRESET_DICT = 0x20;
1304
1305
var INIT_STATE = 42;
1306
var EXTRA_STATE = 69;
1307
var NAME_STATE = 73;
1308
var COMMENT_STATE = 91;
1309
var HCRC_STATE = 103;
1310
var BUSY_STATE = 113;
1311
var FINISH_STATE = 666;
1312
1313
var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
1314
var BS_BLOCK_DONE     = 2; /* block flush performed */
1315
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
1316
var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
1317
1318
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
1319
1320
function err(strm, errorCode) {
1321
  strm.msg = msg[errorCode];
1322
  return errorCode;
1323
}
1324
1325
function rank(f) {
1326
  return ((f) << 1) - ((f) > 4 ? 9 : 0);
1327
}
1328
1329
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
1330
1331
1332
/* =========================================================================
1333
 * Flush as much pending output as possible. All deflate() output goes
1334
 * through this function so some applications may wish to modify it
1335
 * to avoid allocating a large strm->output buffer and copying into it.
1336
 * (See also read_buf()).
1337
 */
1338
function flush_pending(strm) {
1339
  var s = strm.state;
1340
1341
  //_tr_flush_bits(s);
1342
  var len = s.pending;
1343
  if (len > strm.avail_out) {
1344
    len = strm.avail_out;
1345
  }
1346
  if (len === 0) { return; }
1347
1348
  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
1349
  strm.next_out += len;
1350
  s.pending_out += len;
1351
  strm.total_out += len;
1352
  strm.avail_out -= len;
1353
  s.pending -= len;
1354
  if (s.pending === 0) {
1355
    s.pending_out = 0;
1356
  }
1357
}
1358
1359
1360
function flush_block_only (s, last) {
1361
  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
1362
  s.block_start = s.strstart;
1363
  flush_pending(s.strm);
1364
}
1365
1366
1367
function put_byte(s, b) {
1368
  s.pending_buf[s.pending++] = b;
1369
}
1370
1371
1372
/* =========================================================================
1373
 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
1374
 * IN assertion: the stream state is correct and there is enough room in
1375
 * pending_buf.
1376
 */
1377
function putShortMSB(s, b) {
1378
//  put_byte(s, (Byte)(b >> 8));
1379
//  put_byte(s, (Byte)(b & 0xff));
1380
  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
1381
  s.pending_buf[s.pending++] = b & 0xff;
1382
}
1383
1384
1385
/* ===========================================================================
1386
 * Read a new buffer from the current input stream, update the adler32
1387
 * and total number of bytes read.  All deflate() input goes through
1388
 * this function so some applications may wish to modify it to avoid
1389
 * allocating a large strm->input buffer and copying from it.
1390
 * (See also flush_pending()).
1391
 */
1392
function read_buf(strm, buf, start, size) {
1393
  var len = strm.avail_in;
1394
1395
  if (len > size) { len = size; }
1396
  if (len === 0) { return 0; }
1397
1398
  strm.avail_in -= len;
1399
1400
  utils.arraySet(buf, strm.input, strm.next_in, len, start);
1401
  if (strm.state.wrap === 1) {
1402
    strm.adler = adler32(strm.adler, buf, len, start);
1403
  }
1404
1405
  else if (strm.state.wrap === 2) {
1406
    strm.adler = crc32(strm.adler, buf, len, start);
1407
  }
1408
1409
  strm.next_in += len;
1410
  strm.total_in += len;
1411
1412
  return len;
1413
}
1414
1415
1416
/* ===========================================================================
1417
 * Set match_start to the longest match starting at the given string and
1418
 * return its length. Matches shorter or equal to prev_length are discarded,
1419
 * in which case the result is equal to prev_length and match_start is
1420
 * garbage.
1421
 * IN assertions: cur_match is the head of the hash chain for the current
1422
 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1423
 * OUT assertion: the match length is not greater than s->lookahead.
1424
 */
1425
function longest_match(s, cur_match) {
1426
  var chain_length = s.max_chain_length;      /* max hash chain length */
1427
  var scan = s.strstart; /* current string */
1428
  var match;                       /* matched string */
1429
  var len;                           /* length of current match */
1430
  var best_len = s.prev_length;              /* best match length so far */
1431
  var nice_match = s.nice_match;             /* stop if match long enough */
1432
  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
1433
      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
1434
1435
  var _win = s.window; // shortcut
1436
1437
  var wmask = s.w_mask;
1438
  var prev  = s.prev;
1439
1440
  /* Stop when cur_match becomes <= limit. To simplify the code,
1441
   * we prevent matches with the string of window index 0.
1442
   */
1443
1444
  var strend = s.strstart + MAX_MATCH;
1445
  var scan_end1  = _win[scan + best_len - 1];
1446
  var scan_end   = _win[scan + best_len];
1447
1448
  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1449
   * It is easy to get rid of this optimization if necessary.
1450
   */
1451
  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1452
1453
  /* Do not waste too much time if we already have a good match: */
1454
  if (s.prev_length >= s.good_match) {
1455
    chain_length >>= 2;
1456
  }
1457
  /* Do not look for matches beyond the end of the input. This is necessary
1458
   * to make deflate deterministic.
1459
   */
1460
  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
1461
1462
  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1463
1464
  do {
1465
    // Assert(cur_match < s->strstart, "no future");
1466
    match = cur_match;
1467
1468
    /* Skip to next match if the match length cannot increase
1469
     * or if the match length is less than 2.  Note that the checks below
1470
     * for insufficient lookahead only occur occasionally for performance
1471
     * reasons.  Therefore uninitialized memory will be accessed, and
1472
     * conditional jumps will be made that depend on those values.
1473
     * However the length of the match is limited to the lookahead, so
1474
     * the output of deflate is not affected by the uninitialized values.
1475
     */
1476
1477
    if (_win[match + best_len]     !== scan_end  ||
1478
        _win[match + best_len - 1] !== scan_end1 ||
1479
        _win[match]                !== _win[scan] ||
1480
        _win[++match]              !== _win[scan + 1]) {
1481
      continue;
1482
    }
1483
1484
    /* The check at best_len-1 can be removed because it will be made
1485
     * again later. (This heuristic is not always a win.)
1486
     * It is not necessary to compare scan[2] and match[2] since they
1487
     * are always equal when the other bytes match, given that
1488
     * the hash keys are equal and that HASH_BITS >= 8.
1489
     */
1490
    scan += 2;
1491
    match++;
1492
    // Assert(*scan == *match, "match[2]?");
1493
1494
    /* We check for insufficient lookahead only every 8th comparison;
1495
     * the 256th check will be made at strstart+258.
1496
     */
1497
    do {
1498
      /*jshint noempty:false*/
1499
    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1500
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1501
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1502
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
1503
             scan < strend);
1504
1505
    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1506
1507
    len = MAX_MATCH - (strend - scan);
1508
    scan = strend - MAX_MATCH;
1509
1510
    if (len > best_len) {
1511
      s.match_start = cur_match;
1512
      best_len = len;
1513
      if (len >= nice_match) {
1514
        break;
1515
      }
1516
      scan_end1  = _win[scan + best_len - 1];
1517
      scan_end   = _win[scan + best_len];
1518
    }
1519
  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
1520
1521
  if (best_len <= s.lookahead) {
1522
    return best_len;
1523
  }
1524
  return s.lookahead;
1525
}
1526
1527
1528
/* ===========================================================================
1529
 * Fill the window when the lookahead becomes insufficient.
1530
 * Updates strstart and lookahead.
1531
 *
1532
 * IN assertion: lookahead < MIN_LOOKAHEAD
1533
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1534
 *    At least one byte has been read, or avail_in == 0; reads are
1535
 *    performed for at least two bytes (required for the zip translate_eol
1536
 *    option -- not supported here).
1537
 */
1538
function fill_window(s) {
1539
  var _w_size = s.w_size;
1540
  var p, n, m, more, str;
1541
1542
  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1543
1544
  do {
1545
    more = s.window_size - s.lookahead - s.strstart;
1546
1547
    // JS ints have 32 bit, block below not needed
1548
    /* Deal with !@#$% 64K limit: */
1549
    //if (sizeof(int) <= 2) {
1550
    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1551
    //        more = wsize;
1552
    //
1553
    //  } else if (more == (unsigned)(-1)) {
1554
    //        /* Very unlikely, but possible on 16 bit machine if
1555
    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
1556
    //         */
1557
    //        more--;
1558
    //    }
1559
    //}
1560
1561
1562
    /* If the window is almost full and there is insufficient lookahead,
1563
     * move the upper half to the lower one to make room in the upper half.
1564
     */
1565
    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
1566
1567
      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
1568
      s.match_start -= _w_size;
1569
      s.strstart -= _w_size;
1570
      /* we now have strstart >= MAX_DIST */
1571
      s.block_start -= _w_size;
1572
1573
      /* Slide the hash table (could be avoided with 32 bit values
1574
       at the expense of memory usage). We slide even when level == 0
1575
       to keep the hash table consistent if we switch back to level > 0
1576
       later. (Using level 0 permanently is not an optimal usage of
1577
       zlib, so we don't care about this pathological case.)
1578
       */
1579
1580
      n = s.hash_size;
1581
      p = n;
1582
      do {
1583
        m = s.head[--p];
1584
        s.head[p] = (m >= _w_size ? m - _w_size : 0);
1585
      } while (--n);
1586
1587
      n = _w_size;
1588
      p = n;
1589
      do {
1590
        m = s.prev[--p];
1591
        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
1592
        /* If n is not on any hash chain, prev[n] is garbage but
1593
         * its value will never be used.
1594
         */
1595
      } while (--n);
1596
1597
      more += _w_size;
1598
    }
1599
    if (s.strm.avail_in === 0) {
1600
      break;
1601
    }
1602
1603
    /* If there was no sliding:
1604
     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1605
     *    more == window_size - lookahead - strstart
1606
     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1607
     * => more >= window_size - 2*WSIZE + 2
1608
     * In the BIG_MEM or MMAP case (not yet supported),
1609
     *   window_size == input_size + MIN_LOOKAHEAD  &&
1610
     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1611
     * Otherwise, window_size == 2*WSIZE so more >= 2.
1612
     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1613
     */
1614
    //Assert(more >= 2, "more < 2");
1615
    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
1616
    s.lookahead += n;
1617
1618
    /* Initialize the hash value now that we have some input: */
1619
    if (s.lookahead + s.insert >= MIN_MATCH) {
1620
      str = s.strstart - s.insert;
1621
      s.ins_h = s.window[str];
1622
1623
      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
1624
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
1625
//#if MIN_MATCH != 3
1626
//        Call update_hash() MIN_MATCH-3 more times
1627
//#endif
1628
      while (s.insert) {
1629
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
1630
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
1631
1632
        s.prev[str & s.w_mask] = s.head[s.ins_h];
1633
        s.head[s.ins_h] = str;
1634
        str++;
1635
        s.insert--;
1636
        if (s.lookahead + s.insert < MIN_MATCH) {
1637
          break;
1638
        }
1639
      }
1640
    }
1641
    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1642
     * but this is not important since only literal bytes will be emitted.
1643
     */
1644
1645
  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
1646
1647
  /* If the WIN_INIT bytes after the end of the current data have never been
1648
   * written, then zero those bytes in order to avoid memory check reports of
1649
   * the use of uninitialized (or uninitialised as Julian writes) bytes by
1650
   * the longest match routines.  Update the high water mark for the next
1651
   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1652
   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1653
   */
1654
//  if (s.high_water < s.window_size) {
1655
//    var curr = s.strstart + s.lookahead;
1656
//    var init = 0;
1657
//
1658
//    if (s.high_water < curr) {
1659
//      /* Previous high water mark below current data -- zero WIN_INIT
1660
//       * bytes or up to end of window, whichever is less.
1661
//       */
1662
//      init = s.window_size - curr;
1663
//      if (init > WIN_INIT)
1664
//        init = WIN_INIT;
1665
//      zmemzero(s->window + curr, (unsigned)init);
1666
//      s->high_water = curr + init;
1667
//    }
1668
//    else if (s->high_water < (ulg)curr + WIN_INIT) {
1669
//      /* High water mark at or above current data, but below current data
1670
//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1671
//       * to end of window, whichever is less.
1672
//       */
1673
//      init = (ulg)curr + WIN_INIT - s->high_water;
1674
//      if (init > s->window_size - s->high_water)
1675
//        init = s->window_size - s->high_water;
1676
//      zmemzero(s->window + s->high_water, (unsigned)init);
1677
//      s->high_water += init;
1678
//    }
1679
//  }
1680
//
1681
//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1682
//    "not enough room for search");
1683
}
1684
1685
/* ===========================================================================
1686
 * Copy without compression as much as possible from the input stream, return
1687
 * the current block state.
1688
 * This function does not insert new strings in the dictionary since
1689
 * uncompressible data is probably not useful. This function is used
1690
 * only for the level=0 compression option.
1691
 * NOTE: this function should be optimized to avoid extra copying from
1692
 * window to pending_buf.
1693
 */
1694
function deflate_stored(s, flush) {
1695
  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1696
   * to pending_buf_size, and each stored block has a 5 byte header:
1697
   */
1698
  var max_block_size = 0xffff;
1699
1700
  if (max_block_size > s.pending_buf_size - 5) {
1701
    max_block_size = s.pending_buf_size - 5;
1702
  }
1703
1704
  /* Copy as much as possible from input to output: */
1705
  for (;;) {
1706
    /* Fill the window as much as possible: */
1707
    if (s.lookahead <= 1) {
1708
1709
      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1710
      //  s->block_start >= (long)s->w_size, "slide too late");
1711
//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
1712
//        s.block_start >= s.w_size)) {
1713
//        throw  new Error("slide too late");
1714
//      }
1715
1716
      fill_window(s);
1717
      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
1718
        return BS_NEED_MORE;
1719
      }
1720
1721
      if (s.lookahead === 0) {
1722
        break;
1723
      }
1724
      /* flush the current block */
1725
    }
1726
    //Assert(s->block_start >= 0L, "block gone");
1727
//    if (s.block_start < 0) throw new Error("block gone");
1728
1729
    s.strstart += s.lookahead;
1730
    s.lookahead = 0;
1731
1732
    /* Emit a stored block if pending_buf will be full: */
1733
    var max_start = s.block_start + max_block_size;
1734
1735
    if (s.strstart === 0 || s.strstart >= max_start) {
1736
      /* strstart == 0 is possible when wraparound on 16-bit machine */
1737
      s.lookahead = s.strstart - max_start;
1738
      s.strstart = max_start;
1739
      /*** FLUSH_BLOCK(s, 0); ***/
1740
      flush_block_only(s, false);
1741
      if (s.strm.avail_out === 0) {
1742
        return BS_NEED_MORE;
1743
      }
1744
      /***/
1745
1746
1747
    }
1748
    /* Flush if we may have to slide, otherwise block_start may become
1749
     * negative and the data will be gone:
1750
     */
1751
    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
1752
      /*** FLUSH_BLOCK(s, 0); ***/
1753
      flush_block_only(s, false);
1754
      if (s.strm.avail_out === 0) {
1755
        return BS_NEED_MORE;
1756
      }
1757
      /***/
1758
    }
1759
  }
1760
1761
  s.insert = 0;
1762
1763
  if (flush === Z_FINISH) {
1764
    /*** FLUSH_BLOCK(s, 1); ***/
1765
    flush_block_only(s, true);
1766
    if (s.strm.avail_out === 0) {
1767
      return BS_FINISH_STARTED;
1768
    }
1769
    /***/
1770
    return BS_FINISH_DONE;
1771
  }
1772
1773
  if (s.strstart > s.block_start) {
1774
    /*** FLUSH_BLOCK(s, 0); ***/
1775
    flush_block_only(s, false);
1776
    if (s.strm.avail_out === 0) {
1777
      return BS_NEED_MORE;
1778
    }
1779
    /***/
1780
  }
1781
1782
  return BS_NEED_MORE;
1783
}
1784
1785
/* ===========================================================================
1786
 * Compress as much as possible from the input stream, return the current
1787
 * block state.
1788
 * This function does not perform lazy evaluation of matches and inserts
1789
 * new strings in the dictionary only for unmatched strings or for short
1790
 * matches. It is used only for the fast compression options.
1791
 */
1792
function deflate_fast(s, flush) {
1793
  var hash_head;        /* head of the hash chain */
1794
  var bflush;           /* set if current block must be flushed */
1795
1796
  for (;;) {
1797
    /* Make sure that we always have enough lookahead, except
1798
     * at the end of the input file. We need MAX_MATCH bytes
1799
     * for the next match, plus MIN_MATCH bytes to insert the
1800
     * string following the next match.
1801
     */
1802
    if (s.lookahead < MIN_LOOKAHEAD) {
1803
      fill_window(s);
1804
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
1805
        return BS_NEED_MORE;
1806
      }
1807
      if (s.lookahead === 0) {
1808
        break; /* flush the current block */
1809
      }
1810
    }
1811
1812
    /* Insert the string window[strstart .. strstart+2] in the
1813
     * dictionary, and set hash_head to the head of the hash chain:
1814
     */
1815
    hash_head = 0/*NIL*/;
1816
    if (s.lookahead >= MIN_MATCH) {
1817
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1818
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1819
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1820
      s.head[s.ins_h] = s.strstart;
1821
      /***/
1822
    }
1823
1824
    /* Find the longest match, discarding those <= prev_length.
1825
     * At this point we have always match_length < MIN_MATCH
1826
     */
1827
    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
1828
      /* To simplify the code, we prevent matches with the string
1829
       * of window index 0 (in particular we have to avoid a match
1830
       * of the string with itself at the start of the input file).
1831
       */
1832
      s.match_length = longest_match(s, hash_head);
1833
      /* longest_match() sets match_start */
1834
    }
1835
    if (s.match_length >= MIN_MATCH) {
1836
      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
1837
1838
      /*** _tr_tally_dist(s, s.strstart - s.match_start,
1839
                     s.match_length - MIN_MATCH, bflush); ***/
1840
      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
1841
1842
      s.lookahead -= s.match_length;
1843
1844
      /* Insert new strings in the hash table only if the match length
1845
       * is not too large. This saves time but degrades compression.
1846
       */
1847
      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
1848
        s.match_length--; /* string at strstart already in table */
1849
        do {
1850
          s.strstart++;
1851
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1852
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1853
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1854
          s.head[s.ins_h] = s.strstart;
1855
          /***/
1856
          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1857
           * always MIN_MATCH bytes ahead.
1858
           */
1859
        } while (--s.match_length !== 0);
1860
        s.strstart++;
1861
      } else
1862
      {
1863
        s.strstart += s.match_length;
1864
        s.match_length = 0;
1865
        s.ins_h = s.window[s.strstart];
1866
        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
1867
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
1868
1869
//#if MIN_MATCH != 3
1870
//                Call UPDATE_HASH() MIN_MATCH-3 more times
1871
//#endif
1872
        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1873
         * matter since it will be recomputed at next deflate call.
1874
         */
1875
      }
1876
    } else {
1877
      /* No match, output a literal byte */
1878
      //Tracevv((stderr,"%c", s.window[s.strstart]));
1879
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
1880
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
1881
1882
      s.lookahead--;
1883
      s.strstart++;
1884
    }
1885
    if (bflush) {
1886
      /*** FLUSH_BLOCK(s, 0); ***/
1887
      flush_block_only(s, false);
1888
      if (s.strm.avail_out === 0) {
1889
        return BS_NEED_MORE;
1890
      }
1891
      /***/
1892
    }
1893
  }
1894
  s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
1895
  if (flush === Z_FINISH) {
1896
    /*** FLUSH_BLOCK(s, 1); ***/
1897
    flush_block_only(s, true);
1898
    if (s.strm.avail_out === 0) {
1899
      return BS_FINISH_STARTED;
1900
    }
1901
    /***/
1902
    return BS_FINISH_DONE;
1903
  }
1904
  if (s.last_lit) {
1905
    /*** FLUSH_BLOCK(s, 0); ***/
1906
    flush_block_only(s, false);
1907
    if (s.strm.avail_out === 0) {
1908
      return BS_NEED_MORE;
1909
    }
1910
    /***/
1911
  }
1912
  return BS_BLOCK_DONE;
1913
}
1914
1915
/* ===========================================================================
1916
 * Same as above, but achieves better compression. We use a lazy
1917
 * evaluation for matches: a match is finally adopted only if there is
1918
 * no better match at the next window position.
1919
 */
1920
function deflate_slow(s, flush) {
1921
  var hash_head;          /* head of hash chain */
1922
  var bflush;              /* set if current block must be flushed */
1923
1924
  var max_insert;
1925
1926
  /* Process the input block. */
1927
  for (;;) {
1928
    /* Make sure that we always have enough lookahead, except
1929
     * at the end of the input file. We need MAX_MATCH bytes
1930
     * for the next match, plus MIN_MATCH bytes to insert the
1931
     * string following the next match.
1932
     */
1933
    if (s.lookahead < MIN_LOOKAHEAD) {
1934
      fill_window(s);
1935
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
1936
        return BS_NEED_MORE;
1937
      }
1938
      if (s.lookahead === 0) { break; } /* flush the current block */
1939
    }
1940
1941
    /* Insert the string window[strstart .. strstart+2] in the
1942
     * dictionary, and set hash_head to the head of the hash chain:
1943
     */
1944
    hash_head = 0/*NIL*/;
1945
    if (s.lookahead >= MIN_MATCH) {
1946
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1947
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
1948
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
1949
      s.head[s.ins_h] = s.strstart;
1950
      /***/
1951
    }
1952
1953
    /* Find the longest match, discarding those <= prev_length.
1954
     */
1955
    s.prev_length = s.match_length;
1956
    s.prev_match = s.match_start;
1957
    s.match_length = MIN_MATCH-1;
1958
1959
    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
1960
        s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
1961
      /* To simplify the code, we prevent matches with the string
1962
       * of window index 0 (in particular we have to avoid a match
1963
       * of the string with itself at the start of the input file).
1964
       */
1965
      s.match_length = longest_match(s, hash_head);
1966
      /* longest_match() sets match_start */
1967
1968
      if (s.match_length <= 5 &&
1969
         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
1970
1971
        /* If prev_match is also MIN_MATCH, match_start is garbage
1972
         * but we will ignore the current match anyway.
1973
         */
1974
        s.match_length = MIN_MATCH-1;
1975
      }
1976
    }
1977
    /* If there was a match at the previous step and the current
1978
     * match is not better, output the previous match:
1979
     */
1980
    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
1981
      max_insert = s.strstart + s.lookahead - MIN_MATCH;
1982
      /* Do not insert strings in hash table beyond this. */
1983
1984
      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
1985
1986
      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
1987
                     s.prev_length - MIN_MATCH, bflush);***/
1988
      bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
1989
      /* Insert in hash table all strings up to the end of the match.
1990
       * strstart-1 and strstart are already inserted. If there is not
1991
       * enough lookahead, the last two strings are not inserted in
1992
       * the hash table.
1993
       */
1994
      s.lookahead -= s.prev_length-1;
1995
      s.prev_length -= 2;
1996
      do {
1997
        if (++s.strstart <= max_insert) {
1998
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
1999
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
2000
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
2001
          s.head[s.ins_h] = s.strstart;
2002
          /***/
2003
        }
2004
      } while (--s.prev_length !== 0);
2005
      s.match_available = 0;
2006
      s.match_length = MIN_MATCH-1;
2007
      s.strstart++;
2008
2009
      if (bflush) {
2010
        /*** FLUSH_BLOCK(s, 0); ***/
2011
        flush_block_only(s, false);
2012
        if (s.strm.avail_out === 0) {
2013
          return BS_NEED_MORE;
2014
        }
2015
        /***/
2016
      }
2017
2018
    } else if (s.match_available) {
2019
      /* If there was no match at the previous position, output a
2020
       * single literal. If there was a match but the current match
2021
       * is longer, truncate the previous match to a single literal.
2022
       */
2023
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
2024
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
2025
      bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
2026
2027
      if (bflush) {
2028
        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
2029
        flush_block_only(s, false);
2030
        /***/
2031
      }
2032
      s.strstart++;
2033
      s.lookahead--;
2034
      if (s.strm.avail_out === 0) {
2035
        return BS_NEED_MORE;
2036
      }
2037
    } else {
2038
      /* There is no previous match to compare with, wait for
2039
       * the next step to decide.
2040
       */
2041
      s.match_available = 1;
2042
      s.strstart++;
2043
      s.lookahead--;
2044
    }
2045
  }
2046
  //Assert (flush != Z_NO_FLUSH, "no flush?");
2047
  if (s.match_available) {
2048
    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
2049
    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
2050
    bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
2051
2052
    s.match_available = 0;
2053
  }
2054
  s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
2055
  if (flush === Z_FINISH) {
2056
    /*** FLUSH_BLOCK(s, 1); ***/
2057
    flush_block_only(s, true);
2058
    if (s.strm.avail_out === 0) {
2059
      return BS_FINISH_STARTED;
2060
    }
2061
    /***/
2062
    return BS_FINISH_DONE;
2063
  }
2064
  if (s.last_lit) {
2065
    /*** FLUSH_BLOCK(s, 0); ***/
2066
    flush_block_only(s, false);
2067
    if (s.strm.avail_out === 0) {
2068
      return BS_NEED_MORE;
2069
    }
2070
    /***/
2071
  }
2072
2073
  return BS_BLOCK_DONE;
2074
}
2075
2076
2077
/* ===========================================================================
2078
 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2079
 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2080
 * deflate switches away from Z_RLE.)
2081
 */
2082
function deflate_rle(s, flush) {
2083
  var bflush;            /* set if current block must be flushed */
2084
  var prev;              /* byte at distance one to match */
2085
  var scan, strend;      /* scan goes up to strend for length of run */
2086
2087
  var _win = s.window;
2088
2089
  for (;;) {
2090
    /* Make sure that we always have enough lookahead, except
2091
     * at the end of the input file. We need MAX_MATCH bytes
2092
     * for the longest run, plus one for the unrolled loop.
2093
     */
2094
    if (s.lookahead <= MAX_MATCH) {
2095
      fill_window(s);
2096
      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
2097
        return BS_NEED_MORE;
2098
      }
2099
      if (s.lookahead === 0) { break; } /* flush the current block */
2100
    }
2101
2102
    /* See how many times the previous byte repeats */
2103
    s.match_length = 0;
2104
    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
2105
      scan = s.strstart - 1;
2106
      prev = _win[scan];
2107
      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
2108
        strend = s.strstart + MAX_MATCH;
2109
        do {
2110
          /*jshint noempty:false*/
2111
        } while (prev === _win[++scan] && prev === _win[++scan] &&
2112
                 prev === _win[++scan] && prev === _win[++scan] &&
2113
                 prev === _win[++scan] && prev === _win[++scan] &&
2114
                 prev === _win[++scan] && prev === _win[++scan] &&
2115
                 scan < strend);
2116
        s.match_length = MAX_MATCH - (strend - scan);
2117
        if (s.match_length > s.lookahead) {
2118
          s.match_length = s.lookahead;
2119
        }
2120
      }
2121
      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2122
    }
2123
2124
    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2125
    if (s.match_length >= MIN_MATCH) {
2126
      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
2127
2128
      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
2129
      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
2130
2131
      s.lookahead -= s.match_length;
2132
      s.strstart += s.match_length;
2133
      s.match_length = 0;
2134
    } else {
2135
      /* No match, output a literal byte */
2136
      //Tracevv((stderr,"%c", s->window[s->strstart]));
2137
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2138
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2139
2140
      s.lookahead--;
2141
      s.strstart++;
2142
    }
2143
    if (bflush) {
2144
      /*** FLUSH_BLOCK(s, 0); ***/
2145
      flush_block_only(s, false);
2146
      if (s.strm.avail_out === 0) {
2147
        return BS_NEED_MORE;
2148
      }
2149
      /***/
2150
    }
2151
  }
2152
  s.insert = 0;
2153
  if (flush === Z_FINISH) {
2154
    /*** FLUSH_BLOCK(s, 1); ***/
2155
    flush_block_only(s, true);
2156
    if (s.strm.avail_out === 0) {
2157
      return BS_FINISH_STARTED;
2158
    }
2159
    /***/
2160
    return BS_FINISH_DONE;
2161
  }
2162
  if (s.last_lit) {
2163
    /*** FLUSH_BLOCK(s, 0); ***/
2164
    flush_block_only(s, false);
2165
    if (s.strm.avail_out === 0) {
2166
      return BS_NEED_MORE;
2167
    }
2168
    /***/
2169
  }
2170
  return BS_BLOCK_DONE;
2171
}
2172
2173
/* ===========================================================================
2174
 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2175
 * (It will be regenerated if this run of deflate switches away from Huffman.)
2176
 */
2177
function deflate_huff(s, flush) {
2178
  var bflush;             /* set if current block must be flushed */
2179
2180
  for (;;) {
2181
    /* Make sure that we have a literal to write. */
2182
    if (s.lookahead === 0) {
2183
      fill_window(s);
2184
      if (s.lookahead === 0) {
2185
        if (flush === Z_NO_FLUSH) {
2186
          return BS_NEED_MORE;
2187
        }
2188
        break;      /* flush the current block */
2189
      }
2190
    }
2191
2192
    /* Output a literal byte */
2193
    s.match_length = 0;
2194
    //Tracevv((stderr,"%c", s->window[s->strstart]));
2195
    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
2196
    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
2197
    s.lookahead--;
2198
    s.strstart++;
2199
    if (bflush) {
2200
      /*** FLUSH_BLOCK(s, 0); ***/
2201
      flush_block_only(s, false);
2202
      if (s.strm.avail_out === 0) {
2203
        return BS_NEED_MORE;
2204
      }
2205
      /***/
2206
    }
2207
  }
2208
  s.insert = 0;
2209
  if (flush === Z_FINISH) {
2210
    /*** FLUSH_BLOCK(s, 1); ***/
2211
    flush_block_only(s, true);
2212
    if (s.strm.avail_out === 0) {
2213
      return BS_FINISH_STARTED;
2214
    }
2215
    /***/
2216
    return BS_FINISH_DONE;
2217
  }
2218
  if (s.last_lit) {
2219
    /*** FLUSH_BLOCK(s, 0); ***/
2220
    flush_block_only(s, false);
2221
    if (s.strm.avail_out === 0) {
2222
      return BS_NEED_MORE;
2223
    }
2224
    /***/
2225
  }
2226
  return BS_BLOCK_DONE;
2227
}
2228
2229
/* Values for max_lazy_match, good_match and max_chain_length, depending on
2230
 * the desired pack level (0..9). The values given below have been tuned to
2231
 * exclude worst case performance for pathological files. Better values may be
2232
 * found for specific files.
2233
 */
2234
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
2235
  this.good_length = good_length;
2236
  this.max_lazy = max_lazy;
2237
  this.nice_length = nice_length;
2238
  this.max_chain = max_chain;
2239
  this.func = func;
2240
};
2241
2242
var configuration_table;
2243
2244
configuration_table = [
2245
  /*      good lazy nice chain */
2246
  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
2247
  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
2248
  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
2249
  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
2250
2251
  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
2252
  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
2253
  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
2254
  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
2255
  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
2256
  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
2257
];
2258
2259
2260
/* ===========================================================================
2261
 * Initialize the "longest match" routines for a new zlib stream
2262
 */
2263
function lm_init(s) {
2264
  s.window_size = 2 * s.w_size;
2265
2266
  /*** CLEAR_HASH(s); ***/
2267
  zero(s.head); // Fill with NIL (= 0);
2268
2269
  /* Set the default configuration parameters:
2270
   */
2271
  s.max_lazy_match = configuration_table[s.level].max_lazy;
2272
  s.good_match = configuration_table[s.level].good_length;
2273
  s.nice_match = configuration_table[s.level].nice_length;
2274
  s.max_chain_length = configuration_table[s.level].max_chain;
2275
2276
  s.strstart = 0;
2277
  s.block_start = 0;
2278
  s.lookahead = 0;
2279
  s.insert = 0;
2280
  s.match_length = s.prev_length = MIN_MATCH - 1;
2281
  s.match_available = 0;
2282
  s.ins_h = 0;
2283
}
2284
2285
2286
function DeflateState() {
2287
  this.strm = null;            /* pointer back to this zlib stream */
2288
  this.status = 0;            /* as the name implies */
2289
  this.pending_buf = null;      /* output still pending */
2290
  this.pending_buf_size = 0;  /* size of pending_buf */
2291
  this.pending_out = 0;       /* next pending byte to output to the stream */
2292
  this.pending = 0;           /* nb of bytes in the pending buffer */
2293
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
2294
  this.gzhead = null;         /* gzip header information to write */
2295
  this.gzindex = 0;           /* where in extra, name, or comment */
2296
  this.method = Z_DEFLATED; /* can only be DEFLATED */
2297
  this.last_flush = -1;   /* value of flush param for previous deflate call */
2298
2299
  this.w_size = 0;  /* LZ77 window size (32K by default) */
2300
  this.w_bits = 0;  /* log2(w_size)  (8..16) */
2301
  this.w_mask = 0;  /* w_size - 1 */
2302
2303
  this.window = null;
2304
  /* Sliding window. Input bytes are read into the second half of the window,
2305
   * and move to the first half later to keep a dictionary of at least wSize
2306
   * bytes. With this organization, matches are limited to a distance of
2307
   * wSize-MAX_MATCH bytes, but this ensures that IO is always
2308
   * performed with a length multiple of the block size.
2309
   */
2310
2311
  this.window_size = 0;
2312
  /* Actual size of window: 2*wSize, except when the user input buffer
2313
   * is directly used as sliding window.
2314
   */
2315
2316
  this.prev = null;
2317
  /* Link to older string with same hash index. To limit the size of this
2318
   * array to 64K, this link is maintained only for the last 32K strings.
2319
   * An index in this array is thus a window index modulo 32K.
2320
   */
2321
2322
  this.head = null;   /* Heads of the hash chains or NIL. */
2323
2324
  this.ins_h = 0;       /* hash index of string to be inserted */
2325
  this.hash_size = 0;   /* number of elements in hash table */
2326
  this.hash_bits = 0;   /* log2(hash_size) */
2327
  this.hash_mask = 0;   /* hash_size-1 */
2328
2329
  this.hash_shift = 0;
2330
  /* Number of bits by which ins_h must be shifted at each input
2331
   * step. It must be such that after MIN_MATCH steps, the oldest
2332
   * byte no longer takes part in the hash key, that is:
2333
   *   hash_shift * MIN_MATCH >= hash_bits
2334
   */
2335
2336
  this.block_start = 0;
2337
  /* Window position at the beginning of the current output block. Gets
2338
   * negative when the window is moved backwards.
2339
   */
2340
2341
  this.match_length = 0;      /* length of best match */
2342
  this.prev_match = 0;        /* previous match */
2343
  this.match_available = 0;   /* set if previous match exists */
2344
  this.strstart = 0;          /* start of string to insert */
2345
  this.match_start = 0;       /* start of matching string */
2346
  this.lookahead = 0;         /* number of valid bytes ahead in window */
2347
2348
  this.prev_length = 0;
2349
  /* Length of the best match at previous step. Matches not greater than this
2350
   * are discarded. This is used in the lazy match evaluation.
2351
   */
2352
2353
  this.max_chain_length = 0;
2354
  /* To speed up deflation, hash chains are never searched beyond this
2355
   * length.  A higher limit improves compression ratio but degrades the
2356
   * speed.
2357
   */
2358
2359
  this.max_lazy_match = 0;
2360
  /* Attempt to find a better match only when the current match is strictly
2361
   * smaller than this value. This mechanism is used only for compression
2362
   * levels >= 4.
2363
   */
2364
  // That's alias to max_lazy_match, don't use directly
2365
  //this.max_insert_length = 0;
2366
  /* Insert new strings in the hash table only if the match length is not
2367
   * greater than this length. This saves time but degrades compression.
2368
   * max_insert_length is used only for compression levels <= 3.
2369
   */
2370
2371
  this.level = 0;     /* compression level (1..9) */
2372
  this.strategy = 0;  /* favor or force Huffman coding*/
2373
2374
  this.good_match = 0;
2375
  /* Use a faster search when the previous match is longer than this */
2376
2377
  this.nice_match = 0; /* Stop searching when current match exceeds this */
2378
2379
              /* used by trees.c: */
2380
2381
  /* Didn't use ct_data typedef below to suppress compiler warning */
2382
2383
  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
2384
  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
2385
  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
2386
2387
  // Use flat array of DOUBLE size, with interleaved fata,
2388
  // because JS does not support effective
2389
  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
2390
  this.dyn_dtree  = new utils.Buf16((2*D_CODES+1) * 2);
2391
  this.bl_tree    = new utils.Buf16((2*BL_CODES+1) * 2);
2392
  zero(this.dyn_ltree);
2393
  zero(this.dyn_dtree);
2394
  zero(this.bl_tree);
2395
2396
  this.l_desc   = null;         /* desc. for literal tree */
2397
  this.d_desc   = null;         /* desc. for distance tree */
2398
  this.bl_desc  = null;         /* desc. for bit length tree */
2399
2400
  //ush bl_count[MAX_BITS+1];
2401
  this.bl_count = new utils.Buf16(MAX_BITS+1);
2402
  /* number of codes at each bit length for an optimal tree */
2403
2404
  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
2405
  this.heap = new utils.Buf16(2*L_CODES+1);  /* heap used to build the Huffman trees */
2406
  zero(this.heap);
2407
2408
  this.heap_len = 0;               /* number of elements in the heap */
2409
  this.heap_max = 0;               /* element of largest frequency */
2410
  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2411
   * The same heap array is used to build all trees.
2412
   */
2413
2414
  this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
2415
  zero(this.depth);
2416
  /* Depth of each subtree used as tie breaker for trees of equal frequency
2417
   */
2418
2419
  this.l_buf = 0;          /* buffer index for literals or lengths */
2420
2421
  this.lit_bufsize = 0;
2422
  /* Size of match buffer for literals/lengths.  There are 4 reasons for
2423
   * limiting lit_bufsize to 64K:
2424
   *   - frequencies can be kept in 16 bit counters
2425
   *   - if compression is not successful for the first block, all input
2426
   *     data is still in the window so we can still emit a stored block even
2427
   *     when input comes from standard input.  (This can also be done for
2428
   *     all blocks if lit_bufsize is not greater than 32K.)
2429
   *   - if compression is not successful for a file smaller than 64K, we can
2430
   *     even emit a stored file instead of a stored block (saving 5 bytes).
2431
   *     This is applicable only for zip (not gzip or zlib).
2432
   *   - creating new Huffman trees less frequently may not provide fast
2433
   *     adaptation to changes in the input data statistics. (Take for
2434
   *     example a binary file with poorly compressible code followed by
2435
   *     a highly compressible string table.) Smaller buffer sizes give
2436
   *     fast adaptation but have of course the overhead of transmitting
2437
   *     trees more frequently.
2438
   *   - I can't count above 4
2439
   */
2440
2441
  this.last_lit = 0;      /* running index in l_buf */
2442
2443
  this.d_buf = 0;
2444
  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
2445
   * the same number of elements. To use different lengths, an extra flag
2446
   * array would be necessary.
2447
   */
2448
2449
  this.opt_len = 0;       /* bit length of current block with optimal trees */
2450
  this.static_len = 0;    /* bit length of current block with static trees */
2451
  this.matches = 0;       /* number of string matches in current block */
2452
  this.insert = 0;        /* bytes at end of window left to insert */
2453
2454
2455
  this.bi_buf = 0;
2456
  /* Output buffer. bits are inserted starting at the bottom (least
2457
   * significant bits).
2458
   */
2459
  this.bi_valid = 0;
2460
  /* Number of valid bits in bi_buf.  All bits above the last valid bit
2461
   * are always zero.
2462
   */
2463
2464
  // Used for window memory init. We safely ignore it for JS. That makes
2465
  // sense only for pointers and memory check tools.
2466
  //this.high_water = 0;
2467
  /* High water mark offset in window for initialized bytes -- bytes above
2468
   * this are set to zero in order to avoid memory check warnings when
2469
   * longest match routines access bytes past the input.  This is then
2470
   * updated to the new high water mark.
2471
   */
2472
}
2473
2474
2475
function deflateResetKeep(strm) {
2476
  var s;
2477
2478
  if (!strm || !strm.state) {
2479
    return err(strm, Z_STREAM_ERROR);
2480
  }
2481
2482
  strm.total_in = strm.total_out = 0;
2483
  strm.data_type = Z_UNKNOWN;
2484
2485
  s = strm.state;
2486
  s.pending = 0;
2487
  s.pending_out = 0;
2488
2489
  if (s.wrap < 0) {
2490
    s.wrap = -s.wrap;
2491
    /* was made negative by deflate(..., Z_FINISH); */
2492
  }
2493
  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
2494
  strm.adler = (s.wrap === 2) ?
2495
    0  // crc32(0, Z_NULL, 0)
2496
  :
2497
    1; // adler32(0, Z_NULL, 0)
2498
  s.last_flush = Z_NO_FLUSH;
2499
  trees._tr_init(s);
2500
  return Z_OK;
2501
}
2502
2503
2504
function deflateReset(strm) {
2505
  var ret = deflateResetKeep(strm);
2506
  if (ret === Z_OK) {
2507
    lm_init(strm.state);
2508
  }
2509
  return ret;
2510
}
2511
2512
2513
function deflateSetHeader(strm, head) {
2514
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
2515
  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
2516
  strm.state.gzhead = head;
2517
  return Z_OK;
2518
}
2519
2520
2521
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
2522
  if (!strm) { // === Z_NULL
2523
    return Z_STREAM_ERROR;
2524
  }
2525
  var wrap = 1;
2526
2527
  if (level === Z_DEFAULT_COMPRESSION) {
2528
    level = 6;
2529
  }
2530
2531
  if (windowBits < 0) { /* suppress zlib wrapper */
2532
    wrap = 0;
2533
    windowBits = -windowBits;
2534
  }
2535
2536
  else if (windowBits > 15) {
2537
    wrap = 2;           /* write gzip wrapper instead */
2538
    windowBits -= 16;
2539
  }
2540
2541
2542
  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
2543
    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
2544
    strategy < 0 || strategy > Z_FIXED) {
2545
    return err(strm, Z_STREAM_ERROR);
2546
  }
2547
2548
2549
  if (windowBits === 8) {
2550
    windowBits = 9;
2551
  }
2552
  /* until 256-byte window bug fixed */
2553
2554
  var s = new DeflateState();
2555
2556
  strm.state = s;
2557
  s.strm = strm;
2558
2559
  s.wrap = wrap;
2560
  s.gzhead = null;
2561
  s.w_bits = windowBits;
2562
  s.w_size = 1 << s.w_bits;
2563
  s.w_mask = s.w_size - 1;
2564
2565
  s.hash_bits = memLevel + 7;
2566
  s.hash_size = 1 << s.hash_bits;
2567
  s.hash_mask = s.hash_size - 1;
2568
  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
2569
2570
  s.window = new utils.Buf8(s.w_size * 2);
2571
  s.head = new utils.Buf16(s.hash_size);
2572
  s.prev = new utils.Buf16(s.w_size);
2573
2574
  // Don't need mem init magic for JS.
2575
  //s.high_water = 0;  /* nothing written to s->window yet */
2576
2577
  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
2578
2579
  s.pending_buf_size = s.lit_bufsize * 4;
2580
  s.pending_buf = new utils.Buf8(s.pending_buf_size);
2581
2582
  s.d_buf = s.lit_bufsize >> 1;
2583
  s.l_buf = (1 + 2) * s.lit_bufsize;
2584
2585
  s.level = level;
2586
  s.strategy = strategy;
2587
  s.method = method;
2588
2589
  return deflateReset(strm);
2590
}
2591
2592
function deflateInit(strm, level) {
2593
  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2594
}
2595
2596
2597
function deflate(strm, flush) {
2598
  var old_flush, s;
2599
  var beg, val; // for gzip header write only
2600
2601
  if (!strm || !strm.state ||
2602
    flush > Z_BLOCK || flush < 0) {
2603
    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
2604
  }
2605
2606
  s = strm.state;
2607
2608
  if (!strm.output ||
2609
      (!strm.input && strm.avail_in !== 0) ||
2610
      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
2611
    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
2612
  }
2613
2614
  s.strm = strm; /* just in case */
2615
  old_flush = s.last_flush;
2616
  s.last_flush = flush;
2617
2618
  /* Write the header */
2619
  if (s.status === INIT_STATE) {
2620
2621
    if (s.wrap === 2) { // GZIP header
2622
      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
2623
      put_byte(s, 31);
2624
      put_byte(s, 139);
2625
      put_byte(s, 8);
2626
      if (!s.gzhead) { // s->gzhead == Z_NULL
2627
        put_byte(s, 0);
2628
        put_byte(s, 0);
2629
        put_byte(s, 0);
2630
        put_byte(s, 0);
2631
        put_byte(s, 0);
2632
        put_byte(s, s.level === 9 ? 2 :
2633
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2634
                     4 : 0));
2635
        put_byte(s, OS_CODE);
2636
        s.status = BUSY_STATE;
2637
      }
2638
      else {
2639
        put_byte(s, (s.gzhead.text ? 1 : 0) +
2640
                    (s.gzhead.hcrc ? 2 : 0) +
2641
                    (!s.gzhead.extra ? 0 : 4) +
2642
                    (!s.gzhead.name ? 0 : 8) +
2643
                    (!s.gzhead.comment ? 0 : 16)
2644
                );
2645
        put_byte(s, s.gzhead.time & 0xff);
2646
        put_byte(s, (s.gzhead.time >> 8) & 0xff);
2647
        put_byte(s, (s.gzhead.time >> 16) & 0xff);
2648
        put_byte(s, (s.gzhead.time >> 24) & 0xff);
2649
        put_byte(s, s.level === 9 ? 2 :
2650
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
2651
                     4 : 0));
2652
        put_byte(s, s.gzhead.os & 0xff);
2653
        if (s.gzhead.extra && s.gzhead.extra.length) {
2654
          put_byte(s, s.gzhead.extra.length & 0xff);
2655
          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
2656
        }
2657
        if (s.gzhead.hcrc) {
2658
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
2659
        }
2660
        s.gzindex = 0;
2661
        s.status = EXTRA_STATE;
2662
      }
2663
    }
2664
    else // DEFLATE header
2665
    {
2666
      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
2667
      var level_flags = -1;
2668
2669
      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
2670
        level_flags = 0;
2671
      } else if (s.level < 6) {
2672
        level_flags = 1;
2673
      } else if (s.level === 6) {
2674
        level_flags = 2;
2675
      } else {
2676
        level_flags = 3;
2677
      }
2678
      header |= (level_flags << 6);
2679
      if (s.strstart !== 0) { header |= PRESET_DICT; }
2680
      header += 31 - (header % 31);
2681
2682
      s.status = BUSY_STATE;
2683
      putShortMSB(s, header);
2684
2685
      /* Save the adler32 of the preset dictionary: */
2686
      if (s.strstart !== 0) {
2687
        putShortMSB(s, strm.adler >>> 16);
2688
        putShortMSB(s, strm.adler & 0xffff);
2689
      }
2690
      strm.adler = 1; // adler32(0L, Z_NULL, 0);
2691
    }
2692
  }
2693
2694
//#ifdef GZIP
2695
  if (s.status === EXTRA_STATE) {
2696
    if (s.gzhead.extra/* != Z_NULL*/) {
2697
      beg = s.pending;  /* start of bytes to update crc */
2698
2699
      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
2700
        if (s.pending === s.pending_buf_size) {
2701
          if (s.gzhead.hcrc && s.pending > beg) {
2702
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2703
          }
2704
          flush_pending(strm);
2705
          beg = s.pending;
2706
          if (s.pending === s.pending_buf_size) {
2707
            break;
2708
          }
2709
        }
2710
        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
2711
        s.gzindex++;
2712
      }
2713
      if (s.gzhead.hcrc && s.pending > beg) {
2714
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2715
      }
2716
      if (s.gzindex === s.gzhead.extra.length) {
2717
        s.gzindex = 0;
2718
        s.status = NAME_STATE;
2719
      }
2720
    }
2721
    else {
2722
      s.status = NAME_STATE;
2723
    }
2724
  }
2725
  if (s.status === NAME_STATE) {
2726
    if (s.gzhead.name/* != Z_NULL*/) {
2727
      beg = s.pending;  /* start of bytes to update crc */
2728
      //int val;
2729
2730
      do {
2731
        if (s.pending === s.pending_buf_size) {
2732
          if (s.gzhead.hcrc && s.pending > beg) {
2733
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2734
          }
2735
          flush_pending(strm);
2736
          beg = s.pending;
2737
          if (s.pending === s.pending_buf_size) {
2738
            val = 1;
2739
            break;
2740
          }
2741
        }
2742
        // JS specific: little magic to add zero terminator to end of string
2743
        if (s.gzindex < s.gzhead.name.length) {
2744
          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
2745
        } else {
2746
          val = 0;
2747
        }
2748
        put_byte(s, val);
2749
      } while (val !== 0);
2750
2751
      if (s.gzhead.hcrc && s.pending > beg) {
2752
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2753
      }
2754
      if (val === 0) {
2755
        s.gzindex = 0;
2756
        s.status = COMMENT_STATE;
2757
      }
2758
    }
2759
    else {
2760
      s.status = COMMENT_STATE;
2761
    }
2762
  }
2763
  if (s.status === COMMENT_STATE) {
2764
    if (s.gzhead.comment/* != Z_NULL*/) {
2765
      beg = s.pending;  /* start of bytes to update crc */
2766
      //int val;
2767
2768
      do {
2769
        if (s.pending === s.pending_buf_size) {
2770
          if (s.gzhead.hcrc && s.pending > beg) {
2771
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2772
          }
2773
          flush_pending(strm);
2774
          beg = s.pending;
2775
          if (s.pending === s.pending_buf_size) {
2776
            val = 1;
2777
            break;
2778
          }
2779
        }
2780
        // JS specific: little magic to add zero terminator to end of string
2781
        if (s.gzindex < s.gzhead.comment.length) {
2782
          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
2783
        } else {
2784
          val = 0;
2785
        }
2786
        put_byte(s, val);
2787
      } while (val !== 0);
2788
2789
      if (s.gzhead.hcrc && s.pending > beg) {
2790
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
2791
      }
2792
      if (val === 0) {
2793
        s.status = HCRC_STATE;
2794
      }
2795
    }
2796
    else {
2797
      s.status = HCRC_STATE;
2798
    }
2799
  }
2800
  if (s.status === HCRC_STATE) {
2801
    if (s.gzhead.hcrc) {
2802
      if (s.pending + 2 > s.pending_buf_size) {
2803
        flush_pending(strm);
2804
      }
2805
      if (s.pending + 2 <= s.pending_buf_size) {
2806
        put_byte(s, strm.adler & 0xff);
2807
        put_byte(s, (strm.adler >> 8) & 0xff);
2808
        strm.adler = 0; //crc32(0L, Z_NULL, 0);
2809
        s.status = BUSY_STATE;
2810
      }
2811
    }
2812
    else {
2813
      s.status = BUSY_STATE;
2814
    }
2815
  }
2816
//#endif
2817
2818
  /* Flush as much pending output as possible */
2819
  if (s.pending !== 0) {
2820
    flush_pending(strm);
2821
    if (strm.avail_out === 0) {
2822
      /* Since avail_out is 0, deflate will be called again with
2823
       * more output space, but possibly with both pending and
2824
       * avail_in equal to zero. There won't be anything to do,
2825
       * but this is not an error situation so make sure we
2826
       * return OK instead of BUF_ERROR at next call of deflate:
2827
       */
2828
      s.last_flush = -1;
2829
      return Z_OK;
2830
    }
2831
2832
    /* Make sure there is something to do and avoid duplicate consecutive
2833
     * flushes. For repeated and useless calls with Z_FINISH, we keep
2834
     * returning Z_STREAM_END instead of Z_BUF_ERROR.
2835
     */
2836
  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
2837
    flush !== Z_FINISH) {
2838
    return err(strm, Z_BUF_ERROR);
2839
  }
2840
2841
  /* User must not provide more input after the first FINISH: */
2842
  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
2843
    return err(strm, Z_BUF_ERROR);
2844
  }
2845
2846
  /* Start a new block or continue the current one.
2847
   */
2848
  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
2849
    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
2850
    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
2851
      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
2852
        configuration_table[s.level].func(s, flush));
2853
2854
    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
2855
      s.status = FINISH_STATE;
2856
    }
2857
    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
2858
      if (strm.avail_out === 0) {
2859
        s.last_flush = -1;
2860
        /* avoid BUF_ERROR next call, see above */
2861
      }
2862
      return Z_OK;
2863
      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
2864
       * of deflate should use the same flush parameter to make sure
2865
       * that the flush is complete. So we don't have to output an
2866
       * empty block here, this will be done at next call. This also
2867
       * ensures that for a very small output buffer, we emit at most
2868
       * one empty block.
2869
       */
2870
    }
2871
    if (bstate === BS_BLOCK_DONE) {
2872
      if (flush === Z_PARTIAL_FLUSH) {
2873
        trees._tr_align(s);
2874
      }
2875
      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
2876
2877
        trees._tr_stored_block(s, 0, 0, false);
2878
        /* For a full flush, this empty block will be recognized
2879
         * as a special marker by inflate_sync().
2880
         */
2881
        if (flush === Z_FULL_FLUSH) {
2882
          /*** CLEAR_HASH(s); ***/             /* forget history */
2883
          zero(s.head); // Fill with NIL (= 0);
2884
2885
          if (s.lookahead === 0) {
2886
            s.strstart = 0;
2887
            s.block_start = 0;
2888
            s.insert = 0;
2889
          }
2890
        }
2891
      }
2892
      flush_pending(strm);
2893
      if (strm.avail_out === 0) {
2894
        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
2895
        return Z_OK;
2896
      }
2897
    }
2898
  }
2899
  //Assert(strm->avail_out > 0, "bug2");
2900
  //if (strm.avail_out <= 0) { throw new Error("bug2");}
2901
2902
  if (flush !== Z_FINISH) { return Z_OK; }
2903
  if (s.wrap <= 0) { return Z_STREAM_END; }
2904
2905
  /* Write the trailer */
2906
  if (s.wrap === 2) {
2907
    put_byte(s, strm.adler & 0xff);
2908
    put_byte(s, (strm.adler >> 8) & 0xff);
2909
    put_byte(s, (strm.adler >> 16) & 0xff);
2910
    put_byte(s, (strm.adler >> 24) & 0xff);
2911
    put_byte(s, strm.total_in & 0xff);
2912
    put_byte(s, (strm.total_in >> 8) & 0xff);
2913
    put_byte(s, (strm.total_in >> 16) & 0xff);
2914
    put_byte(s, (strm.total_in >> 24) & 0xff);
2915
  }
2916
  else
2917
  {
2918
    putShortMSB(s, strm.adler >>> 16);
2919
    putShortMSB(s, strm.adler & 0xffff);
2920
  }
2921
2922
  flush_pending(strm);
2923
  /* If avail_out is zero, the application will call deflate again
2924
   * to flush the rest.
2925
   */
2926
  if (s.wrap > 0) { s.wrap = -s.wrap; }
2927
  /* write the trailer only once! */
2928
  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
2929
}
2930
2931
function deflateEnd(strm) {
2932
  var status;
2933
2934
  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
2935
    return Z_STREAM_ERROR;
2936
  }
2937
2938
  status = strm.state.status;
2939
  if (status !== INIT_STATE &&
2940
    status !== EXTRA_STATE &&
2941
    status !== NAME_STATE &&
2942
    status !== COMMENT_STATE &&
2943
    status !== HCRC_STATE &&
2944
    status !== BUSY_STATE &&
2945
    status !== FINISH_STATE
2946
  ) {
2947
    return err(strm, Z_STREAM_ERROR);
2948
  }
2949
2950
  strm.state = null;
2951
2952
  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
2953
}
2954
2955
/* =========================================================================
2956
 * Copy the source state to the destination state
2957
 */
2958
//function deflateCopy(dest, source) {
2959
//
2960
//}
2961
2962
exports.deflateInit = deflateInit;
2963
exports.deflateInit2 = deflateInit2;
2964
exports.deflateReset = deflateReset;
2965
exports.deflateResetKeep = deflateResetKeep;
2966
exports.deflateSetHeader = deflateSetHeader;
2967
exports.deflate = deflate;
2968
exports.deflateEnd = deflateEnd;
2969
exports.deflateInfo = 'pako deflate (from Nodeca project)';
2970
2971
/* Not implemented
2972
exports.deflateBound = deflateBound;
2973
exports.deflateCopy = deflateCopy;
2974
exports.deflateSetDictionary = deflateSetDictionary;
2975
exports.deflateParams = deflateParams;
2976
exports.deflatePending = deflatePending;
2977
exports.deflatePrime = deflatePrime;
2978
exports.deflateTune = deflateTune;
2979
*/
2980
2981
},{"../utils/common":4,"./adler32":6,"./crc32":8,"./messages":14,"./trees":15}],10:[function(require,module,exports){
2982
'use strict';
2983
2984
2985
function GZheader() {
2986
  /* true if compressed data believed to be text */
2987
  this.text       = 0;
2988
  /* modification time */
2989
  this.time       = 0;
2990
  /* extra flags (not used when writing a gzip file) */
2991
  this.xflags     = 0;
2992
  /* operating system */
2993
  this.os         = 0;
2994
  /* pointer to extra field or Z_NULL if none */
2995
  this.extra      = null;
2996
  /* extra field length (valid if extra != Z_NULL) */
2997
  this.extra_len  = 0; // Actually, we don't need it in JS,
2998
                       // but leave for few code modifications
2999
3000
  //
3001
  // Setup limits is not necessary because in js we should not preallocate memory
3002
  // for inflate use constant limit in 65536 bytes
3003
  //
3004
3005
  /* space at extra (only when reading header) */
3006
  // this.extra_max  = 0;
3007
  /* pointer to zero-terminated file name or Z_NULL */
3008
  this.name       = '';
3009
  /* space at name (only when reading header) */
3010
  // this.name_max   = 0;
3011
  /* pointer to zero-terminated comment or Z_NULL */
3012
  this.comment    = '';
3013
  /* space at comment (only when reading header) */
3014
  // this.comm_max   = 0;
3015
  /* true if there was or will be a header crc */
3016
  this.hcrc       = 0;
3017
  /* true when done reading gzip header (not used when writing a gzip file) */
3018
  this.done       = false;
3019
}
3020
3021
module.exports = GZheader;
3022
3023
},{}],11:[function(require,module,exports){
3024
'use strict';
3025
3026
// See state defs from inflate.js
3027
var BAD = 30;       /* got a data error -- remain here until reset */
3028
var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
3029
3030
/*
3031
   Decode literal, length, and distance codes and write out the resulting
3032
   literal and match bytes until either not enough input or output is
3033
   available, an end-of-block is encountered, or a data error is encountered.
3034
   When large enough input and output buffers are supplied to inflate(), for
3035
   example, a 16K input buffer and a 64K output buffer, more than 95% of the
3036
   inflate execution time is spent in this routine.
3037
3038
   Entry assumptions:
3039
3040
        state.mode === LEN
3041
        strm.avail_in >= 6
3042
        strm.avail_out >= 258
3043
        start >= strm.avail_out
3044
        state.bits < 8
3045
3046
   On return, state.mode is one of:
3047
3048
        LEN -- ran out of enough output space or enough available input
3049
        TYPE -- reached end of block code, inflate() to interpret next block
3050
        BAD -- error in block data
3051
3052
   Notes:
3053
3054
    - The maximum input bits used by a length/distance pair is 15 bits for the
3055
      length code, 5 bits for the length extra, 15 bits for the distance code,
3056
      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
3057
      Therefore if strm.avail_in >= 6, then there is enough input to avoid
3058
      checking for available input while decoding.
3059
3060
    - The maximum bytes that a single length/distance pair can output is 258
3061
      bytes, which is the maximum length that can be coded.  inflate_fast()
3062
      requires strm.avail_out >= 258 for each loop to avoid checking for
3063
      output space.
3064
 */
3065
module.exports = function inflate_fast(strm, start) {
3066
  var state;
3067
  var _in;                    /* local strm.input */
3068
  var last;                   /* have enough input while in < last */
3069
  var _out;                   /* local strm.output */
3070
  var beg;                    /* inflate()'s initial strm.output */
3071
  var end;                    /* while out < end, enough space available */
3072
//#ifdef INFLATE_STRICT
3073
  var dmax;                   /* maximum distance from zlib header */
3074
//#endif
3075
  var wsize;                  /* window size or zero if not using window */
3076
  var whave;                  /* valid bytes in the window */
3077
  var wnext;                  /* window write index */
3078
  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
3079
  var s_window;               /* allocated sliding window, if wsize != 0 */
3080
  var hold;                   /* local strm.hold */
3081
  var bits;                   /* local strm.bits */
3082
  var lcode;                  /* local strm.lencode */
3083
  var dcode;                  /* local strm.distcode */
3084
  var lmask;                  /* mask for first level of length codes */
3085
  var dmask;                  /* mask for first level of distance codes */
3086
  var here;                   /* retrieved table entry */
3087
  var op;                     /* code bits, operation, extra bits, or */
3088
                              /*  window position, window bytes to copy */
3089
  var len;                    /* match length, unused bytes */
3090
  var dist;                   /* match distance */
3091
  var from;                   /* where to copy match from */
3092
  var from_source;
3093
3094
3095
  var input, output; // JS specific, because we have no pointers
3096
3097
  /* copy state to local variables */
3098
  state = strm.state;
3099
  //here = state.here;
3100
  _in = strm.next_in;
3101
  input = strm.input;
3102
  last = _in + (strm.avail_in - 5);
3103
  _out = strm.next_out;
3104
  output = strm.output;
3105
  beg = _out - (start - strm.avail_out);
3106
  end = _out + (strm.avail_out - 257);
3107
//#ifdef INFLATE_STRICT
3108
  dmax = state.dmax;
3109
//#endif
3110
  wsize = state.wsize;
3111
  whave = state.whave;
3112
  wnext = state.wnext;
3113
  s_window = state.window;
3114
  hold = state.hold;
3115
  bits = state.bits;
3116
  lcode = state.lencode;
3117
  dcode = state.distcode;
3118
  lmask = (1 << state.lenbits) - 1;
3119
  dmask = (1 << state.distbits) - 1;
3120
3121
3122
  /* decode literals and length/distances until end-of-block or not enough
3123
     input data or output space */
3124
3125
  top:
3126
  do {
3127
    if (bits < 15) {
3128
      hold += input[_in++] << bits;
3129
      bits += 8;
3130
      hold += input[_in++] << bits;
3131
      bits += 8;
3132
    }
3133
3134
    here = lcode[hold & lmask];
3135
3136
    dolen:
3137
    for (;;) { // Goto emulation
3138
      op = here >>> 24/*here.bits*/;
3139
      hold >>>= op;
3140
      bits -= op;
3141
      op = (here >>> 16) & 0xff/*here.op*/;
3142
      if (op === 0) {                          /* literal */
3143
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
3144
        //        "inflate:         literal '%c'\n" :
3145
        //        "inflate:         literal 0x%02x\n", here.val));
3146
        output[_out++] = here & 0xffff/*here.val*/;
3147
      }
3148
      else if (op & 16) {                     /* length base */
3149
        len = here & 0xffff/*here.val*/;
3150
        op &= 15;                           /* number of extra bits */
3151
        if (op) {
3152
          if (bits < op) {
3153
            hold += input[_in++] << bits;
3154
            bits += 8;
3155
          }
3156
          len += hold & ((1 << op) - 1);
3157
          hold >>>= op;
3158
          bits -= op;
3159
        }
3160
        //Tracevv((stderr, "inflate:         length %u\n", len));
3161
        if (bits < 15) {
3162
          hold += input[_in++] << bits;
3163
          bits += 8;
3164
          hold += input[_in++] << bits;
3165
          bits += 8;
3166
        }
3167
        here = dcode[hold & dmask];
3168
3169
        dodist:
3170
        for (;;) { // goto emulation
3171
          op = here >>> 24/*here.bits*/;
3172
          hold >>>= op;
3173
          bits -= op;
3174
          op = (here >>> 16) & 0xff/*here.op*/;
3175
3176
          if (op & 16) {                      /* distance base */
3177
            dist = here & 0xffff/*here.val*/;
3178
            op &= 15;                       /* number of extra bits */
3179
            if (bits < op) {
3180
              hold += input[_in++] << bits;
3181
              bits += 8;
3182
              if (bits < op) {
3183
                hold += input[_in++] << bits;
3184
                bits += 8;
3185
              }
3186
            }
3187
            dist += hold & ((1 << op) - 1);
3188
//#ifdef INFLATE_STRICT
3189
            if (dist > dmax) {
3190
              strm.msg = 'invalid distance too far back';
3191
              state.mode = BAD;
3192
              break top;
3193
            }
3194
//#endif
3195
            hold >>>= op;
3196
            bits -= op;
3197
            //Tracevv((stderr, "inflate:         distance %u\n", dist));
3198
            op = _out - beg;                /* max distance in output */
3199
            if (dist > op) {                /* see if copy from window */
3200
              op = dist - op;               /* distance back in window */
3201
              if (op > whave) {
3202
                if (state.sane) {
3203
                  strm.msg = 'invalid distance too far back';
3204
                  state.mode = BAD;
3205
                  break top;
3206
                }
3207
3208
// (!) This block is disabled in zlib defailts,
3209
// don't enable it for binary compatibility
3210
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
3211
//                if (len <= op - whave) {
3212
//                  do {
3213
//                    output[_out++] = 0;
3214
//                  } while (--len);
3215
//                  continue top;
3216
//                }
3217
//                len -= op - whave;
3218
//                do {
3219
//                  output[_out++] = 0;
3220
//                } while (--op > whave);
3221
//                if (op === 0) {
3222
//                  from = _out - dist;
3223
//                  do {
3224
//                    output[_out++] = output[from++];
3225
//                  } while (--len);
3226
//                  continue top;
3227
//                }
3228
//#endif
3229
              }
3230
              from = 0; // window index
3231
              from_source = s_window;
3232
              if (wnext === 0) {           /* very common case */
3233
                from += wsize - op;
3234
                if (op < len) {         /* some from window */
3235
                  len -= op;
3236
                  do {
3237
                    output[_out++] = s_window[from++];
3238
                  } while (--op);
3239
                  from = _out - dist;  /* rest from output */
3240
                  from_source = output;
3241
                }
3242
              }
3243
              else if (wnext < op) {      /* wrap around window */
3244
                from += wsize + wnext - op;
3245
                op -= wnext;
3246
                if (op < len) {         /* some from end of window */
3247
                  len -= op;
3248
                  do {
3249
                    output[_out++] = s_window[from++];
3250
                  } while (--op);
3251
                  from = 0;
3252
                  if (wnext < len) {  /* some from start of window */
3253
                    op = wnext;
3254
                    len -= op;
3255
                    do {
3256
                      output[_out++] = s_window[from++];
3257
                    } while (--op);
3258
                    from = _out - dist;      /* rest from output */
3259
                    from_source = output;
3260
                  }
3261
                }
3262
              }
3263
              else {                      /* contiguous in window */
3264
                from += wnext - op;
3265
                if (op < len) {         /* some from window */
3266
                  len -= op;
3267
                  do {
3268
                    output[_out++] = s_window[from++];
3269
                  } while (--op);
3270
                  from = _out - dist;  /* rest from output */
3271
                  from_source = output;
3272
                }
3273
              }
3274
              while (len > 2) {
3275
                output[_out++] = from_source[from++];
3276
                output[_out++] = from_source[from++];
3277
                output[_out++] = from_source[from++];
3278
                len -= 3;
3279
              }
3280
              if (len) {
3281
                output[_out++] = from_source[from++];
3282
                if (len > 1) {
3283
                  output[_out++] = from_source[from++];
3284
                }
3285
              }
3286
            }
3287
            else {
3288
              from = _out - dist;          /* copy direct from output */
3289
              do {                        /* minimum length is three */
3290
                output[_out++] = output[from++];
3291
                output[_out++] = output[from++];
3292
                output[_out++] = output[from++];
3293
                len -= 3;
3294
              } while (len > 2);
3295
              if (len) {
3296
                output[_out++] = output[from++];
3297
                if (len > 1) {
3298
                  output[_out++] = output[from++];
3299
                }
3300
              }
3301
            }
3302
          }
3303
          else if ((op & 64) === 0) {          /* 2nd level distance code */
3304
            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3305
            continue dodist;
3306
          }
3307
          else {
3308
            strm.msg = 'invalid distance code';
3309
            state.mode = BAD;
3310
            break top;
3311
          }
3312
3313
          break; // need to emulate goto via "continue"
3314
        }
3315
      }
3316
      else if ((op & 64) === 0) {              /* 2nd level length code */
3317
        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
3318
        continue dolen;
3319
      }
3320
      else if (op & 32) {                     /* end-of-block */
3321
        //Tracevv((stderr, "inflate:         end of block\n"));
3322
        state.mode = TYPE;
3323
        break top;
3324
      }
3325
      else {
3326
        strm.msg = 'invalid literal/length code';
3327
        state.mode = BAD;
3328
        break top;
3329
      }
3330
3331
      break; // need to emulate goto via "continue"
3332
    }
3333
  } while (_in < last && _out < end);
3334
3335
  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
3336
  len = bits >> 3;
3337
  _in -= len;
3338
  bits -= len << 3;
3339
  hold &= (1 << bits) - 1;
3340
3341
  /* update state and return */
3342
  strm.next_in = _in;
3343
  strm.next_out = _out;
3344
  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
3345
  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
3346
  state.hold = hold;
3347
  state.bits = bits;
3348
  return;
3349
};
3350
3351
},{}],12:[function(require,module,exports){
3352
'use strict';
3353
3354
3355
var utils = require('../utils/common');
3356
var adler32 = require('./adler32');
3357
var crc32   = require('./crc32');
3358
var inflate_fast = require('./inffast');
3359
var inflate_table = require('./inftrees');
3360
3361
var CODES = 0;
3362
var LENS = 1;
3363
var DISTS = 2;
3364
3365
/* Public constants ==========================================================*/
3366
/* ===========================================================================*/
3367
3368
3369
/* Allowed flush values; see deflate() and inflate() below for details */
3370
//var Z_NO_FLUSH      = 0;
3371
//var Z_PARTIAL_FLUSH = 1;
3372
//var Z_SYNC_FLUSH    = 2;
3373
//var Z_FULL_FLUSH    = 3;
3374
var Z_FINISH        = 4;
3375
var Z_BLOCK         = 5;
3376
var Z_TREES         = 6;
3377
3378
3379
/* Return codes for the compression/decompression functions. Negative values
3380
 * are errors, positive values are used for special but normal events.
3381
 */
3382
var Z_OK            = 0;
3383
var Z_STREAM_END    = 1;
3384
var Z_NEED_DICT     = 2;
3385
//var Z_ERRNO         = -1;
3386
var Z_STREAM_ERROR  = -2;
3387
var Z_DATA_ERROR    = -3;
3388
var Z_MEM_ERROR     = -4;
3389
var Z_BUF_ERROR     = -5;
3390
//var Z_VERSION_ERROR = -6;
3391
3392
/* The deflate compression method */
3393
var Z_DEFLATED  = 8;
3394
3395
3396
/* STATES ====================================================================*/
3397
/* ===========================================================================*/
3398
3399
3400
var    HEAD = 1;       /* i: waiting for magic header */
3401
var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
3402
var    TIME = 3;       /* i: waiting for modification time (gzip) */
3403
var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
3404
var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
3405
var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
3406
var    NAME = 7;       /* i: waiting for end of file name (gzip) */
3407
var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
3408
var    HCRC = 9;       /* i: waiting for header crc (gzip) */
3409
var    DICTID = 10;    /* i: waiting for dictionary check value */
3410
var    DICT = 11;      /* waiting for inflateSetDictionary() call */
3411
var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
3412
var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
3413
var        STORED = 14;    /* i: waiting for stored size (length and complement) */
3414
var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
3415
var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
3416
var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
3417
var        LENLENS = 18;   /* i: waiting for code length code lengths */
3418
var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
3419
var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
3420
var            LEN = 21;       /* i: waiting for length/lit/eob code */
3421
var            LENEXT = 22;    /* i: waiting for length extra bits */
3422
var            DIST = 23;      /* i: waiting for distance code */
3423
var            DISTEXT = 24;   /* i: waiting for distance extra bits */
3424
var            MATCH = 25;     /* o: waiting for output space to copy string */
3425
var            LIT = 26;       /* o: waiting for output space to write literal */
3426
var    CHECK = 27;     /* i: waiting for 32-bit check value */
3427
var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
3428
var    DONE = 29;      /* finished check, done -- remain here until reset */
3429
var    BAD = 30;       /* got a data error -- remain here until reset */
3430
var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
3431
var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
3432
3433
/* ===========================================================================*/
3434
3435
3436
3437
var ENOUGH_LENS = 852;
3438
var ENOUGH_DISTS = 592;
3439
//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
3440
3441
var MAX_WBITS = 15;
3442
/* 32K LZ77 window */
3443
var DEF_WBITS = MAX_WBITS;
3444
3445
3446
function ZSWAP32(q) {
3447
  return  (((q >>> 24) & 0xff) +
3448
          ((q >>> 8) & 0xff00) +
3449
          ((q & 0xff00) << 8) +
3450
          ((q & 0xff) << 24));
3451
}
3452
3453
3454
function InflateState() {
3455
  this.mode = 0;             /* current inflate mode */
3456
  this.last = false;          /* true if processing last block */
3457
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
3458
  this.havedict = false;      /* true if dictionary provided */
3459
  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
3460
  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
3461
  this.check = 0;             /* protected copy of check value */
3462
  this.total = 0;             /* protected copy of output count */
3463
  // TODO: may be {}
3464
  this.head = null;           /* where to save gzip header information */
3465
3466
  /* sliding window */
3467
  this.wbits = 0;             /* log base 2 of requested window size */
3468
  this.wsize = 0;             /* window size or zero if not using window */
3469
  this.whave = 0;             /* valid bytes in the window */
3470
  this.wnext = 0;             /* window write index */
3471
  this.window = null;         /* allocated sliding window, if needed */
3472
3473
  /* bit accumulator */
3474
  this.hold = 0;              /* input bit accumulator */
3475
  this.bits = 0;              /* number of bits in "in" */
3476
3477
  /* for string and stored block copying */
3478
  this.length = 0;            /* literal or length of data to copy */
3479
  this.offset = 0;            /* distance back to copy string from */
3480
3481
  /* for table and code decoding */
3482
  this.extra = 0;             /* extra bits needed */
3483
3484
  /* fixed and dynamic code tables */
3485
  this.lencode = null;          /* starting table for length/literal codes */
3486
  this.distcode = null;         /* starting table for distance codes */
3487
  this.lenbits = 0;           /* index bits for lencode */
3488
  this.distbits = 0;          /* index bits for distcode */
3489
3490
  /* dynamic table building */
3491
  this.ncode = 0;             /* number of code length code lengths */
3492
  this.nlen = 0;              /* number of length code lengths */
3493
  this.ndist = 0;             /* number of distance code lengths */
3494
  this.have = 0;              /* number of code lengths in lens[] */
3495
  this.next = null;              /* next available space in codes[] */
3496
3497
  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
3498
  this.work = new utils.Buf16(288); /* work area for code table building */
3499
3500
  /*
3501
   because we don't have pointers in js, we use lencode and distcode directly
3502
   as buffers so we don't need codes
3503
  */
3504
  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
3505
  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
3506
  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
3507
  this.sane = 0;                   /* if false, allow invalid distance too far */
3508
  this.back = 0;                   /* bits back of last unprocessed length/lit */
3509
  this.was = 0;                    /* initial length of match */
3510
}
3511
3512
function inflateResetKeep(strm) {
3513
  var state;
3514
3515
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3516
  state = strm.state;
3517
  strm.total_in = strm.total_out = state.total = 0;
3518
  strm.msg = ''; /*Z_NULL*/
3519
  if (state.wrap) {       /* to support ill-conceived Java test suite */
3520
    strm.adler = state.wrap & 1;
3521
  }
3522
  state.mode = HEAD;
3523
  state.last = 0;
3524
  state.havedict = 0;
3525
  state.dmax = 32768;
3526
  state.head = null/*Z_NULL*/;
3527
  state.hold = 0;
3528
  state.bits = 0;
3529
  //state.lencode = state.distcode = state.next = state.codes;
3530
  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
3531
  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
3532
3533
  state.sane = 1;
3534
  state.back = -1;
3535
  //Tracev((stderr, "inflate: reset\n"));
3536
  return Z_OK;
3537
}
3538
3539
function inflateReset(strm) {
3540
  var state;
3541
3542
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3543
  state = strm.state;
3544
  state.wsize = 0;
3545
  state.whave = 0;
3546
  state.wnext = 0;
3547
  return inflateResetKeep(strm);
3548
3549
}
3550
3551
function inflateReset2(strm, windowBits) {
3552
  var wrap;
3553
  var state;
3554
3555
  /* get the state */
3556
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
3557
  state = strm.state;
3558
3559
  /* extract wrap request from windowBits parameter */
3560
  if (windowBits < 0) {
3561
    wrap = 0;
3562
    windowBits = -windowBits;
3563
  }
3564
  else {
3565
    wrap = (windowBits >> 4) + 1;
3566
    if (windowBits < 48) {
3567
      windowBits &= 15;
3568
    }
3569
  }
3570
3571
  /* set number of window bits, free window if different */
3572
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
3573
    return Z_STREAM_ERROR;
3574
  }
3575
  if (state.window !== null && state.wbits !== windowBits) {
3576
    state.window = null;
3577
  }
3578
3579
  /* update state and reset the rest of it */
3580
  state.wrap = wrap;
3581
  state.wbits = windowBits;
3582
  return inflateReset(strm);
3583
}
3584
3585
function inflateInit2(strm, windowBits) {
3586
  var ret;
3587
  var state;
3588
3589
  if (!strm) { return Z_STREAM_ERROR; }
3590
  //strm.msg = Z_NULL;                 /* in case we return an error */
3591
3592
  state = new InflateState();
3593
3594
  //if (state === Z_NULL) return Z_MEM_ERROR;
3595
  //Tracev((stderr, "inflate: allocated\n"));
3596
  strm.state = state;
3597
  state.window = null/*Z_NULL*/;
3598
  ret = inflateReset2(strm, windowBits);
3599
  if (ret !== Z_OK) {
3600
    strm.state = null/*Z_NULL*/;
3601
  }
3602
  return ret;
3603
}
3604
3605
function inflateInit(strm) {
3606
  return inflateInit2(strm, DEF_WBITS);
3607
}
3608
3609
3610
/*
3611
 Return state with length and distance decoding tables and index sizes set to
3612
 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
3613
 If BUILDFIXED is defined, then instead this routine builds the tables the
3614
 first time it's called, and returns those tables the first time and
3615
 thereafter.  This reduces the size of the code by about 2K bytes, in
3616
 exchange for a little execution time.  However, BUILDFIXED should not be
3617
 used for threaded applications, since the rewriting of the tables and virgin
3618
 may not be thread-safe.
3619
 */
3620
var virgin = true;
3621
3622
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
3623
3624
function fixedtables(state) {
3625
  /* build fixed huffman tables if first call (may not be thread safe) */
3626
  if (virgin) {
3627
    var sym;
3628
3629
    lenfix = new utils.Buf32(512);
3630
    distfix = new utils.Buf32(32);
3631
3632
    /* literal/length table */
3633
    sym = 0;
3634
    while (sym < 144) { state.lens[sym++] = 8; }
3635
    while (sym < 256) { state.lens[sym++] = 9; }
3636
    while (sym < 280) { state.lens[sym++] = 7; }
3637
    while (sym < 288) { state.lens[sym++] = 8; }
3638
3639
    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, {bits: 9});
3640
3641
    /* distance table */
3642
    sym = 0;
3643
    while (sym < 32) { state.lens[sym++] = 5; }
3644
3645
    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, {bits: 5});
3646
3647
    /* do this just once */
3648
    virgin = false;
3649
  }
3650
3651
  state.lencode = lenfix;
3652
  state.lenbits = 9;
3653
  state.distcode = distfix;
3654
  state.distbits = 5;
3655
}
3656
3657
3658
/*
3659
 Update the window with the last wsize (normally 32K) bytes written before
3660
 returning.  If window does not exist yet, create it.  This is only called
3661
 when a window is already in use, or when output has been written during this
3662
 inflate call, but the end of the deflate stream has not been reached yet.
3663
 It is also called to create a window for dictionary data when a dictionary
3664
 is loaded.
3665
3666
 Providing output buffers larger than 32K to inflate() should provide a speed
3667
 advantage, since only the last 32K of output is copied to the sliding window
3668
 upon return from inflate(), and since all distances after the first 32K of
3669
 output will fall in the output data, making match copies simpler and faster.
3670
 The advantage may be dependent on the size of the processor's data caches.
3671
 */
3672
function updatewindow(strm, src, end, copy) {
3673
  var dist;
3674
  var state = strm.state;
3675
3676
  /* if it hasn't been done already, allocate space for the window */
3677
  if (state.window === null) {
3678
    state.wsize = 1 << state.wbits;
3679
    state.wnext = 0;
3680
    state.whave = 0;
3681
3682
    state.window = new utils.Buf8(state.wsize);
3683
  }
3684
3685
  /* copy state->wsize or less output bytes into the circular window */
3686
  if (copy >= state.wsize) {
3687
    utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
3688
    state.wnext = 0;
3689
    state.whave = state.wsize;
3690
  }
3691
  else {
3692
    dist = state.wsize - state.wnext;
3693
    if (dist > copy) {
3694
      dist = copy;
3695
    }
3696
    //zmemcpy(state->window + state->wnext, end - copy, dist);
3697
    utils.arraySet(state.window,src, end - copy, dist, state.wnext);
3698
    copy -= dist;
3699
    if (copy) {
3700
      //zmemcpy(state->window, end - copy, copy);
3701
      utils.arraySet(state.window,src, end - copy, copy, 0);
3702
      state.wnext = copy;
3703
      state.whave = state.wsize;
3704
    }
3705
    else {
3706
      state.wnext += dist;
3707
      if (state.wnext === state.wsize) { state.wnext = 0; }
3708
      if (state.whave < state.wsize) { state.whave += dist; }
3709
    }
3710
  }
3711
  return 0;
3712
}
3713
3714
function inflate(strm, flush) {
3715
  var state;
3716
  var input, output;          // input/output buffers
3717
  var next;                   /* next input INDEX */
3718
  var put;                    /* next output INDEX */
3719
  var have, left;             /* available input and output */
3720
  var hold;                   /* bit buffer */
3721
  var bits;                   /* bits in bit buffer */
3722
  var _in, _out;              /* save starting available input and output */
3723
  var copy;                   /* number of stored or match bytes to copy */
3724
  var from;                   /* where to copy match bytes from */
3725
  var from_source;
3726
  var here = 0;               /* current decoding table entry */
3727
  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
3728
  //var last;                   /* parent table entry */
3729
  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
3730
  var len;                    /* length to copy for repeats, bits to drop */
3731
  var ret;                    /* return code */
3732
  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
3733
  var opts;
3734
3735
  var n; // temporary var for NEED_BITS
3736
3737
  var order = /* permutation of code lengths */
3738
    [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
3739
3740
3741
  if (!strm || !strm.state || !strm.output ||
3742
      (!strm.input && strm.avail_in !== 0)) {
3743
    return Z_STREAM_ERROR;
3744
  }
3745
3746
  state = strm.state;
3747
  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
3748
3749
3750
  //--- LOAD() ---
3751
  put = strm.next_out;
3752
  output = strm.output;
3753
  left = strm.avail_out;
3754
  next = strm.next_in;
3755
  input = strm.input;
3756
  have = strm.avail_in;
3757
  hold = state.hold;
3758
  bits = state.bits;
3759
  //---
3760
3761
  _in = have;
3762
  _out = left;
3763
  ret = Z_OK;
3764
3765
  inf_leave: // goto emulation
3766
  for (;;) {
3767
    switch (state.mode) {
3768
    case HEAD:
3769
      if (state.wrap === 0) {
3770
        state.mode = TYPEDO;
3771
        break;
3772
      }
3773
      //=== NEEDBITS(16);
3774
      while (bits < 16) {
3775
        if (have === 0) { break inf_leave; }
3776
        have--;
3777
        hold += input[next++] << bits;
3778
        bits += 8;
3779
      }
3780
      //===//
3781
      if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
3782
        state.check = 0/*crc32(0L, Z_NULL, 0)*/;
3783
        //=== CRC2(state.check, hold);
3784
        hbuf[0] = hold & 0xff;
3785
        hbuf[1] = (hold >>> 8) & 0xff;
3786
        state.check = crc32(state.check, hbuf, 2, 0);
3787
        //===//
3788
3789
        //=== INITBITS();
3790
        hold = 0;
3791
        bits = 0;
3792
        //===//
3793
        state.mode = FLAGS;
3794
        break;
3795
      }
3796
      state.flags = 0;           /* expect zlib header */
3797
      if (state.head) {
3798
        state.head.done = false;
3799
      }
3800
      if (!(state.wrap & 1) ||   /* check if zlib header allowed */
3801
        (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
3802
        strm.msg = 'incorrect header check';
3803
        state.mode = BAD;
3804
        break;
3805
      }
3806
      if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
3807
        strm.msg = 'unknown compression method';
3808
        state.mode = BAD;
3809
        break;
3810
      }
3811
      //--- DROPBITS(4) ---//
3812
      hold >>>= 4;
3813
      bits -= 4;
3814
      //---//
3815
      len = (hold & 0x0f)/*BITS(4)*/ + 8;
3816
      if (state.wbits === 0) {
3817
        state.wbits = len;
3818
      }
3819
      else if (len > state.wbits) {
3820
        strm.msg = 'invalid window size';
3821
        state.mode = BAD;
3822
        break;
3823
      }
3824
      state.dmax = 1 << len;
3825
      //Tracev((stderr, "inflate:   zlib header ok\n"));
3826
      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
3827
      state.mode = hold & 0x200 ? DICTID : TYPE;
3828
      //=== INITBITS();
3829
      hold = 0;
3830
      bits = 0;
3831
      //===//
3832
      break;
3833
    case FLAGS:
3834
      //=== NEEDBITS(16); */
3835
      while (bits < 16) {
3836
        if (have === 0) { break inf_leave; }
3837
        have--;
3838
        hold += input[next++] << bits;
3839
        bits += 8;
3840
      }
3841
      //===//
3842
      state.flags = hold;
3843
      if ((state.flags & 0xff) !== Z_DEFLATED) {
3844
        strm.msg = 'unknown compression method';
3845
        state.mode = BAD;
3846
        break;
3847
      }
3848
      if (state.flags & 0xe000) {
3849
        strm.msg = 'unknown header flags set';
3850
        state.mode = BAD;
3851
        break;
3852
      }
3853
      if (state.head) {
3854
        state.head.text = ((hold >> 8) & 1);
3855
      }
3856
      if (state.flags & 0x0200) {
3857
        //=== CRC2(state.check, hold);
3858
        hbuf[0] = hold & 0xff;
3859
        hbuf[1] = (hold >>> 8) & 0xff;
3860
        state.check = crc32(state.check, hbuf, 2, 0);
3861
        //===//
3862
      }
3863
      //=== INITBITS();
3864
      hold = 0;
3865
      bits = 0;
3866
      //===//
3867
      state.mode = TIME;
3868
      /* falls through */
3869
    case TIME:
3870
      //=== NEEDBITS(32); */
3871
      while (bits < 32) {
3872
        if (have === 0) { break inf_leave; }
3873
        have--;
3874
        hold += input[next++] << bits;
3875
        bits += 8;
3876
      }
3877
      //===//
3878
      if (state.head) {
3879
        state.head.time = hold;
3880
      }
3881
      if (state.flags & 0x0200) {
3882
        //=== CRC4(state.check, hold)
3883
        hbuf[0] = hold & 0xff;
3884
        hbuf[1] = (hold >>> 8) & 0xff;
3885
        hbuf[2] = (hold >>> 16) & 0xff;
3886
        hbuf[3] = (hold >>> 24) & 0xff;
3887
        state.check = crc32(state.check, hbuf, 4, 0);
3888
        //===
3889
      }
3890
      //=== INITBITS();
3891
      hold = 0;
3892
      bits = 0;
3893
      //===//
3894
      state.mode = OS;
3895
      /* falls through */
3896
    case OS:
3897
      //=== NEEDBITS(16); */
3898
      while (bits < 16) {
3899
        if (have === 0) { break inf_leave; }
3900
        have--;
3901
        hold += input[next++] << bits;
3902
        bits += 8;
3903
      }
3904
      //===//
3905
      if (state.head) {
3906
        state.head.xflags = (hold & 0xff);
3907
        state.head.os = (hold >> 8);
3908
      }
3909
      if (state.flags & 0x0200) {
3910
        //=== CRC2(state.check, hold);
3911
        hbuf[0] = hold & 0xff;
3912
        hbuf[1] = (hold >>> 8) & 0xff;
3913
        state.check = crc32(state.check, hbuf, 2, 0);
3914
        //===//
3915
      }
3916
      //=== INITBITS();
3917
      hold = 0;
3918
      bits = 0;
3919
      //===//
3920
      state.mode = EXLEN;
3921
      /* falls through */
3922
    case EXLEN:
3923
      if (state.flags & 0x0400) {
3924
        //=== NEEDBITS(16); */
3925
        while (bits < 16) {
3926
          if (have === 0) { break inf_leave; }
3927
          have--;
3928
          hold += input[next++] << bits;
3929
          bits += 8;
3930
        }
3931
        //===//
3932
        state.length = hold;
3933
        if (state.head) {
3934
          state.head.extra_len = hold;
3935
        }
3936
        if (state.flags & 0x0200) {
3937
          //=== CRC2(state.check, hold);
3938
          hbuf[0] = hold & 0xff;
3939
          hbuf[1] = (hold >>> 8) & 0xff;
3940
          state.check = crc32(state.check, hbuf, 2, 0);
3941
          //===//
3942
        }
3943
        //=== INITBITS();
3944
        hold = 0;
3945
        bits = 0;
3946
        //===//
3947
      }
3948
      else if (state.head) {
3949
        state.head.extra = null/*Z_NULL*/;
3950
      }
3951
      state.mode = EXTRA;
3952
      /* falls through */
3953
    case EXTRA:
3954
      if (state.flags & 0x0400) {
3955
        copy = state.length;
3956
        if (copy > have) { copy = have; }
3957
        if (copy) {
3958
          if (state.head) {
3959
            len = state.head.extra_len - state.length;
3960
            if (!state.head.extra) {
3961
              // Use untyped array for more conveniend processing later
3962
              state.head.extra = new Array(state.head.extra_len);
3963
            }
3964
            utils.arraySet(
3965
              state.head.extra,
3966
              input,
3967
              next,
3968
              // extra field is limited to 65536 bytes
3969
              // - no need for additional size check
3970
              copy,
3971
              /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
3972
              len
3973
            );
3974
            //zmemcpy(state.head.extra + len, next,
3975
            //        len + copy > state.head.extra_max ?
3976
            //        state.head.extra_max - len : copy);
3977
          }
3978
          if (state.flags & 0x0200) {
3979
            state.check = crc32(state.check, input, copy, next);
3980
          }
3981
          have -= copy;
3982
          next += copy;
3983
          state.length -= copy;
3984
        }
3985
        if (state.length) { break inf_leave; }
3986
      }
3987
      state.length = 0;
3988
      state.mode = NAME;
3989
      /* falls through */
3990
    case NAME:
3991
      if (state.flags & 0x0800) {
3992
        if (have === 0) { break inf_leave; }
3993
        copy = 0;
3994
        do {
3995
          // TODO: 2 or 1 bytes?
3996
          len = input[next + copy++];
3997
          /* use constant limit because in js we should not preallocate memory */
3998
          if (state.head && len &&
3999
              (state.length < 65536 /*state.head.name_max*/)) {
4000
            state.head.name += String.fromCharCode(len);
4001
          }
4002
        } while (len && copy < have);
4003
4004
        if (state.flags & 0x0200) {
4005
          state.check = crc32(state.check, input, copy, next);
4006
        }
4007
        have -= copy;
4008
        next += copy;
4009
        if (len) { break inf_leave; }
4010
      }
4011
      else if (state.head) {
4012
        state.head.name = null;
4013
      }
4014
      state.length = 0;
4015
      state.mode = COMMENT;
4016
      /* falls through */
4017
    case COMMENT:
4018
      if (state.flags & 0x1000) {
4019
        if (have === 0) { break inf_leave; }
4020
        copy = 0;
4021
        do {
4022
          len = input[next + copy++];
4023
          /* use constant limit because in js we should not preallocate memory */
4024
          if (state.head && len &&
4025
              (state.length < 65536 /*state.head.comm_max*/)) {
4026
            state.head.comment += String.fromCharCode(len);
4027
          }
4028
        } while (len && copy < have);
4029
        if (state.flags & 0x0200) {
4030
          state.check = crc32(state.check, input, copy, next);
4031
        }
4032
        have -= copy;
4033
        next += copy;
4034
        if (len) { break inf_leave; }
4035
      }
4036
      else if (state.head) {
4037
        state.head.comment = null;
4038
      }
4039
      state.mode = HCRC;
4040
      /* falls through */
4041
    case HCRC:
4042
      if (state.flags & 0x0200) {
4043
        //=== NEEDBITS(16); */
4044
        while (bits < 16) {
4045
          if (have === 0) { break inf_leave; }
4046
          have--;
4047
          hold += input[next++] << bits;
4048
          bits += 8;
4049
        }
4050
        //===//
4051
        if (hold !== (state.check & 0xffff)) {
4052
          strm.msg = 'header crc mismatch';
4053
          state.mode = BAD;
4054
          break;
4055
        }
4056
        //=== INITBITS();
4057
        hold = 0;
4058
        bits = 0;
4059
        //===//
4060
      }
4061
      if (state.head) {
4062
        state.head.hcrc = ((state.flags >> 9) & 1);
4063
        state.head.done = true;
4064
      }
4065
      strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
4066
      state.mode = TYPE;
4067
      break;
4068
    case DICTID:
4069
      //=== NEEDBITS(32); */
4070
      while (bits < 32) {
4071
        if (have === 0) { break inf_leave; }
4072
        have--;
4073
        hold += input[next++] << bits;
4074
        bits += 8;
4075
      }
4076
      //===//
4077
      strm.adler = state.check = ZSWAP32(hold);
4078
      //=== INITBITS();
4079
      hold = 0;
4080
      bits = 0;
4081
      //===//
4082
      state.mode = DICT;
4083
      /* falls through */
4084
    case DICT:
4085
      if (state.havedict === 0) {
4086
        //--- RESTORE() ---
4087
        strm.next_out = put;
4088
        strm.avail_out = left;
4089
        strm.next_in = next;
4090
        strm.avail_in = have;
4091
        state.hold = hold;
4092
        state.bits = bits;
4093
        //---
4094
        return Z_NEED_DICT;
4095
      }
4096
      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
4097
      state.mode = TYPE;
4098
      /* falls through */
4099
    case TYPE:
4100
      if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
4101
      /* falls through */
4102
    case TYPEDO:
4103
      if (state.last) {
4104
        //--- BYTEBITS() ---//
4105
        hold >>>= bits & 7;
4106
        bits -= bits & 7;
4107
        //---//
4108
        state.mode = CHECK;
4109
        break;
4110
      }
4111
      //=== NEEDBITS(3); */
4112
      while (bits < 3) {
4113
        if (have === 0) { break inf_leave; }
4114
        have--;
4115
        hold += input[next++] << bits;
4116
        bits += 8;
4117
      }
4118
      //===//
4119
      state.last = (hold & 0x01)/*BITS(1)*/;
4120
      //--- DROPBITS(1) ---//
4121
      hold >>>= 1;
4122
      bits -= 1;
4123
      //---//
4124
4125
      switch ((hold & 0x03)/*BITS(2)*/) {
4126
      case 0:                             /* stored block */
4127
        //Tracev((stderr, "inflate:     stored block%s\n",
4128
        //        state.last ? " (last)" : ""));
4129
        state.mode = STORED;
4130
        break;
4131
      case 1:                             /* fixed block */
4132
        fixedtables(state);
4133
        //Tracev((stderr, "inflate:     fixed codes block%s\n",
4134
        //        state.last ? " (last)" : ""));
4135
        state.mode = LEN_;             /* decode codes */
4136
        if (flush === Z_TREES) {
4137
          //--- DROPBITS(2) ---//
4138
          hold >>>= 2;
4139
          bits -= 2;
4140
          //---//
4141
          break inf_leave;
4142
        }
4143
        break;
4144
      case 2:                             /* dynamic block */
4145
        //Tracev((stderr, "inflate:     dynamic codes block%s\n",
4146
        //        state.last ? " (last)" : ""));
4147
        state.mode = TABLE;
4148
        break;
4149
      case 3:
4150
        strm.msg = 'invalid block type';
4151
        state.mode = BAD;
4152
      }
4153
      //--- DROPBITS(2) ---//
4154
      hold >>>= 2;
4155
      bits -= 2;
4156
      //---//
4157
      break;
4158
    case STORED:
4159
      //--- BYTEBITS() ---// /* go to byte boundary */
4160
      hold >>>= bits & 7;
4161
      bits -= bits & 7;
4162
      //---//
4163
      //=== NEEDBITS(32); */
4164
      while (bits < 32) {
4165
        if (have === 0) { break inf_leave; }
4166
        have--;
4167
        hold += input[next++] << bits;
4168
        bits += 8;
4169
      }
4170
      //===//
4171
      if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
4172
        strm.msg = 'invalid stored block lengths';
4173
        state.mode = BAD;
4174
        break;
4175
      }
4176
      state.length = hold & 0xffff;
4177
      //Tracev((stderr, "inflate:       stored length %u\n",
4178
      //        state.length));
4179
      //=== INITBITS();
4180
      hold = 0;
4181
      bits = 0;
4182
      //===//
4183
      state.mode = COPY_;
4184
      if (flush === Z_TREES) { break inf_leave; }
4185
      /* falls through */
4186
    case COPY_:
4187
      state.mode = COPY;
4188
      /* falls through */
4189
    case COPY:
4190
      copy = state.length;
4191
      if (copy) {
4192
        if (copy > have) { copy = have; }
4193
        if (copy > left) { copy = left; }
4194
        if (copy === 0) { break inf_leave; }
4195
        //--- zmemcpy(put, next, copy); ---
4196
        utils.arraySet(output, input, next, copy, put);
4197
        //---//
4198
        have -= copy;
4199
        next += copy;
4200
        left -= copy;
4201
        put += copy;
4202
        state.length -= copy;
4203
        break;
4204
      }
4205
      //Tracev((stderr, "inflate:       stored end\n"));
4206
      state.mode = TYPE;
4207
      break;
4208
    case TABLE:
4209
      //=== NEEDBITS(14); */
4210
      while (bits < 14) {
4211
        if (have === 0) { break inf_leave; }
4212
        have--;
4213
        hold += input[next++] << bits;
4214
        bits += 8;
4215
      }
4216
      //===//
4217
      state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
4218
      //--- DROPBITS(5) ---//
4219
      hold >>>= 5;
4220
      bits -= 5;
4221
      //---//
4222
      state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
4223
      //--- DROPBITS(5) ---//
4224
      hold >>>= 5;
4225
      bits -= 5;
4226
      //---//
4227
      state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
4228
      //--- DROPBITS(4) ---//
4229
      hold >>>= 4;
4230
      bits -= 4;
4231
      //---//
4232
//#ifndef PKZIP_BUG_WORKAROUND
4233
      if (state.nlen > 286 || state.ndist > 30) {
4234
        strm.msg = 'too many length or distance symbols';
4235
        state.mode = BAD;
4236
        break;
4237
      }
4238
//#endif
4239
      //Tracev((stderr, "inflate:       table sizes ok\n"));
4240
      state.have = 0;
4241
      state.mode = LENLENS;
4242
      /* falls through */
4243
    case LENLENS:
4244
      while (state.have < state.ncode) {
4245
        //=== NEEDBITS(3);
4246
        while (bits < 3) {
4247
          if (have === 0) { break inf_leave; }
4248
          have--;
4249
          hold += input[next++] << bits;
4250
          bits += 8;
4251
        }
4252
        //===//
4253
        state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
4254
        //--- DROPBITS(3) ---//
4255
        hold >>>= 3;
4256
        bits -= 3;
4257
        //---//
4258
      }
4259
      while (state.have < 19) {
4260
        state.lens[order[state.have++]] = 0;
4261
      }
4262
      // We have separate tables & no pointers. 2 commented lines below not needed.
4263
      //state.next = state.codes;
4264
      //state.lencode = state.next;
4265
      // Switch to use dynamic table
4266
      state.lencode = state.lendyn;
4267
      state.lenbits = 7;
4268
4269
      opts = {bits: state.lenbits};
4270
      ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
4271
      state.lenbits = opts.bits;
4272
4273
      if (ret) {
4274
        strm.msg = 'invalid code lengths set';
4275
        state.mode = BAD;
4276
        break;
4277
      }
4278
      //Tracev((stderr, "inflate:       code lengths ok\n"));
4279
      state.have = 0;
4280
      state.mode = CODELENS;
4281
      /* falls through */
4282
    case CODELENS:
4283
      while (state.have < state.nlen + state.ndist) {
4284
        for (;;) {
4285
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
4286
          here_bits = here >>> 24;
4287
          here_op = (here >>> 16) & 0xff;
4288
          here_val = here & 0xffff;
4289
4290
          if ((here_bits) <= bits) { break; }
4291
          //--- PULLBYTE() ---//
4292
          if (have === 0) { break inf_leave; }
4293
          have--;
4294
          hold += input[next++] << bits;
4295
          bits += 8;
4296
          //---//
4297
        }
4298
        if (here_val < 16) {
4299
          //--- DROPBITS(here.bits) ---//
4300
          hold >>>= here_bits;
4301
          bits -= here_bits;
4302
          //---//
4303
          state.lens[state.have++] = here_val;
4304
        }
4305
        else {
4306
          if (here_val === 16) {
4307
            //=== NEEDBITS(here.bits + 2);
4308
            n = here_bits + 2;
4309
            while (bits < n) {
4310
              if (have === 0) { break inf_leave; }
4311
              have--;
4312
              hold += input[next++] << bits;
4313
              bits += 8;
4314
            }
4315
            //===//
4316
            //--- DROPBITS(here.bits) ---//
4317
            hold >>>= here_bits;
4318
            bits -= here_bits;
4319
            //---//
4320
            if (state.have === 0) {
4321
              strm.msg = 'invalid bit length repeat';
4322
              state.mode = BAD;
4323
              break;
4324
            }
4325
            len = state.lens[state.have - 1];
4326
            copy = 3 + (hold & 0x03);//BITS(2);
4327
            //--- DROPBITS(2) ---//
4328
            hold >>>= 2;
4329
            bits -= 2;
4330
            //---//
4331
          }
4332
          else if (here_val === 17) {
4333
            //=== NEEDBITS(here.bits + 3);
4334
            n = here_bits + 3;
4335
            while (bits < n) {
4336
              if (have === 0) { break inf_leave; }
4337
              have--;
4338
              hold += input[next++] << bits;
4339
              bits += 8;
4340
            }
4341
            //===//
4342
            //--- DROPBITS(here.bits) ---//
4343
            hold >>>= here_bits;
4344
            bits -= here_bits;
4345
            //---//
4346
            len = 0;
4347
            copy = 3 + (hold & 0x07);//BITS(3);
4348
            //--- DROPBITS(3) ---//
4349
            hold >>>= 3;
4350
            bits -= 3;
4351
            //---//
4352
          }
4353
          else {
4354
            //=== NEEDBITS(here.bits + 7);
4355
            n = here_bits + 7;
4356
            while (bits < n) {
4357
              if (have === 0) { break inf_leave; }
4358
              have--;
4359
              hold += input[next++] << bits;
4360
              bits += 8;
4361
            }
4362
            //===//
4363
            //--- DROPBITS(here.bits) ---//
4364
            hold >>>= here_bits;
4365
            bits -= here_bits;
4366
            //---//
4367
            len = 0;
4368
            copy = 11 + (hold & 0x7f);//BITS(7);
4369
            //--- DROPBITS(7) ---//
4370
            hold >>>= 7;
4371
            bits -= 7;
4372
            //---//
4373
          }
4374
          if (state.have + copy > state.nlen + state.ndist) {
4375
            strm.msg = 'invalid bit length repeat';
4376
            state.mode = BAD;
4377
            break;
4378
          }
4379
          while (copy--) {
4380
            state.lens[state.have++] = len;
4381
          }
4382
        }
4383
      }
4384
4385
      /* handle error breaks in while */
4386
      if (state.mode === BAD) { break; }
4387
4388
      /* check for end-of-block code (better have one) */
4389
      if (state.lens[256] === 0) {
4390
        strm.msg = 'invalid code -- missing end-of-block';
4391
        state.mode = BAD;
4392
        break;
4393
      }
4394
4395
      /* build code tables -- note: do not change the lenbits or distbits
4396
         values here (9 and 6) without reading the comments in inftrees.h
4397
         concerning the ENOUGH constants, which depend on those values */
4398
      state.lenbits = 9;
4399
4400
      opts = {bits: state.lenbits};
4401
      ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
4402
      // We have separate tables & no pointers. 2 commented lines below not needed.
4403
      // state.next_index = opts.table_index;
4404
      state.lenbits = opts.bits;
4405
      // state.lencode = state.next;
4406
4407
      if (ret) {
4408
        strm.msg = 'invalid literal/lengths set';
4409
        state.mode = BAD;
4410
        break;
4411
      }
4412
4413
      state.distbits = 6;
4414
      //state.distcode.copy(state.codes);
4415
      // Switch to use dynamic table
4416
      state.distcode = state.distdyn;
4417
      opts = {bits: state.distbits};
4418
      ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
4419
      // We have separate tables & no pointers. 2 commented lines below not needed.
4420
      // state.next_index = opts.table_index;
4421
      state.distbits = opts.bits;
4422
      // state.distcode = state.next;
4423
4424
      if (ret) {
4425
        strm.msg = 'invalid distances set';
4426
        state.mode = BAD;
4427
        break;
4428
      }
4429
      //Tracev((stderr, 'inflate:       codes ok\n'));
4430
      state.mode = LEN_;
4431
      if (flush === Z_TREES) { break inf_leave; }
4432
      /* falls through */
4433
    case LEN_:
4434
      state.mode = LEN;
4435
      /* falls through */
4436
    case LEN:
4437
      if (have >= 6 && left >= 258) {
4438
        //--- RESTORE() ---
4439
        strm.next_out = put;
4440
        strm.avail_out = left;
4441
        strm.next_in = next;
4442
        strm.avail_in = have;
4443
        state.hold = hold;
4444
        state.bits = bits;
4445
        //---
4446
        inflate_fast(strm, _out);
4447
        //--- LOAD() ---
4448
        put = strm.next_out;
4449
        output = strm.output;
4450
        left = strm.avail_out;
4451
        next = strm.next_in;
4452
        input = strm.input;
4453
        have = strm.avail_in;
4454
        hold = state.hold;
4455
        bits = state.bits;
4456
        //---
4457
4458
        if (state.mode === TYPE) {
4459
          state.back = -1;
4460
        }
4461
        break;
4462
      }
4463
      state.back = 0;
4464
      for (;;) {
4465
        here = state.lencode[hold & ((1 << state.lenbits) -1)];  /*BITS(state.lenbits)*/
4466
        here_bits = here >>> 24;
4467
        here_op = (here >>> 16) & 0xff;
4468
        here_val = here & 0xffff;
4469
4470
        if (here_bits <= bits) { break; }
4471
        //--- PULLBYTE() ---//
4472
        if (have === 0) { break inf_leave; }
4473
        have--;
4474
        hold += input[next++] << bits;
4475
        bits += 8;
4476
        //---//
4477
      }
4478
      if (here_op && (here_op & 0xf0) === 0) {
4479
        last_bits = here_bits;
4480
        last_op = here_op;
4481
        last_val = here_val;
4482
        for (;;) {
4483
          here = state.lencode[last_val +
4484
                  ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4485
          here_bits = here >>> 24;
4486
          here_op = (here >>> 16) & 0xff;
4487
          here_val = here & 0xffff;
4488
4489
          if ((last_bits + here_bits) <= bits) { break; }
4490
          //--- PULLBYTE() ---//
4491
          if (have === 0) { break inf_leave; }
4492
          have--;
4493
          hold += input[next++] << bits;
4494
          bits += 8;
4495
          //---//
4496
        }
4497
        //--- DROPBITS(last.bits) ---//
4498
        hold >>>= last_bits;
4499
        bits -= last_bits;
4500
        //---//
4501
        state.back += last_bits;
4502
      }
4503
      //--- DROPBITS(here.bits) ---//
4504
      hold >>>= here_bits;
4505
      bits -= here_bits;
4506
      //---//
4507
      state.back += here_bits;
4508
      state.length = here_val;
4509
      if (here_op === 0) {
4510
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
4511
        //        "inflate:         literal '%c'\n" :
4512
        //        "inflate:         literal 0x%02x\n", here.val));
4513
        state.mode = LIT;
4514
        break;
4515
      }
4516
      if (here_op & 32) {
4517
        //Tracevv((stderr, "inflate:         end of block\n"));
4518
        state.back = -1;
4519
        state.mode = TYPE;
4520
        break;
4521
      }
4522
      if (here_op & 64) {
4523
        strm.msg = 'invalid literal/length code';
4524
        state.mode = BAD;
4525
        break;
4526
      }
4527
      state.extra = here_op & 15;
4528
      state.mode = LENEXT;
4529
      /* falls through */
4530
    case LENEXT:
4531
      if (state.extra) {
4532
        //=== NEEDBITS(state.extra);
4533
        n = state.extra;
4534
        while (bits < n) {
4535
          if (have === 0) { break inf_leave; }
4536
          have--;
4537
          hold += input[next++] << bits;
4538
          bits += 8;
4539
        }
4540
        //===//
4541
        state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
4542
        //--- DROPBITS(state.extra) ---//
4543
        hold >>>= state.extra;
4544
        bits -= state.extra;
4545
        //---//
4546
        state.back += state.extra;
4547
      }
4548
      //Tracevv((stderr, "inflate:         length %u\n", state.length));
4549
      state.was = state.length;
4550
      state.mode = DIST;
4551
      /* falls through */
4552
    case DIST:
4553
      for (;;) {
4554
        here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
4555
        here_bits = here >>> 24;
4556
        here_op = (here >>> 16) & 0xff;
4557
        here_val = here & 0xffff;
4558
4559
        if ((here_bits) <= bits) { break; }
4560
        //--- PULLBYTE() ---//
4561
        if (have === 0) { break inf_leave; }
4562
        have--;
4563
        hold += input[next++] << bits;
4564
        bits += 8;
4565
        //---//
4566
      }
4567
      if ((here_op & 0xf0) === 0) {
4568
        last_bits = here_bits;
4569
        last_op = here_op;
4570
        last_val = here_val;
4571
        for (;;) {
4572
          here = state.distcode[last_val +
4573
                  ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
4574
          here_bits = here >>> 24;
4575
          here_op = (here >>> 16) & 0xff;
4576
          here_val = here & 0xffff;
4577
4578
          if ((last_bits + here_bits) <= bits) { break; }
4579
          //--- PULLBYTE() ---//
4580
          if (have === 0) { break inf_leave; }
4581
          have--;
4582
          hold += input[next++] << bits;
4583
          bits += 8;
4584
          //---//
4585
        }
4586
        //--- DROPBITS(last.bits) ---//
4587
        hold >>>= last_bits;
4588
        bits -= last_bits;
4589
        //---//
4590
        state.back += last_bits;
4591
      }
4592
      //--- DROPBITS(here.bits) ---//
4593
      hold >>>= here_bits;
4594
      bits -= here_bits;
4595
      //---//
4596
      state.back += here_bits;
4597
      if (here_op & 64) {
4598
        strm.msg = 'invalid distance code';
4599
        state.mode = BAD;
4600
        break;
4601
      }
4602
      state.offset = here_val;
4603
      state.extra = (here_op) & 15;
4604
      state.mode = DISTEXT;
4605
      /* falls through */
4606
    case DISTEXT:
4607
      if (state.extra) {
4608
        //=== NEEDBITS(state.extra);
4609
        n = state.extra;
4610
        while (bits < n) {
4611
          if (have === 0) { break inf_leave; }
4612
          have--;
4613
          hold += input[next++] << bits;
4614
          bits += 8;
4615
        }
4616
        //===//
4617
        state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
4618
        //--- DROPBITS(state.extra) ---//
4619
        hold >>>= state.extra;
4620
        bits -= state.extra;
4621
        //---//
4622
        state.back += state.extra;
4623
      }
4624
//#ifdef INFLATE_STRICT
4625
      if (state.offset > state.dmax) {
4626
        strm.msg = 'invalid distance too far back';
4627
        state.mode = BAD;
4628
        break;
4629
      }
4630
//#endif
4631
      //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
4632
      state.mode = MATCH;
4633
      /* falls through */
4634
    case MATCH:
4635
      if (left === 0) { break inf_leave; }
4636
      copy = _out - left;
4637
      if (state.offset > copy) {         /* copy from window */
4638
        copy = state.offset - copy;
4639
        if (copy > state.whave) {
4640
          if (state.sane) {
4641
            strm.msg = 'invalid distance too far back';
4642
            state.mode = BAD;
4643
            break;
4644
          }
4645
// (!) This block is disabled in zlib defailts,
4646
// don't enable it for binary compatibility
4647
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
4648
//          Trace((stderr, "inflate.c too far\n"));
4649
//          copy -= state.whave;
4650
//          if (copy > state.length) { copy = state.length; }
4651
//          if (copy > left) { copy = left; }
4652
//          left -= copy;
4653
//          state.length -= copy;
4654
//          do {
4655
//            output[put++] = 0;
4656
//          } while (--copy);
4657
//          if (state.length === 0) { state.mode = LEN; }
4658
//          break;
4659
//#endif
4660
        }
4661
        if (copy > state.wnext) {
4662
          copy -= state.wnext;
4663
          from = state.wsize - copy;
4664
        }
4665
        else {
4666
          from = state.wnext - copy;
4667
        }
4668
        if (copy > state.length) { copy = state.length; }
4669
        from_source = state.window;
4670
      }
4671
      else {                              /* copy from output */
4672
        from_source = output;
4673
        from = put - state.offset;
4674
        copy = state.length;
4675
      }
4676
      if (copy > left) { copy = left; }
4677
      left -= copy;
4678
      state.length -= copy;
4679
      do {
4680
        output[put++] = from_source[from++];
4681
      } while (--copy);
4682
      if (state.length === 0) { state.mode = LEN; }
4683
      break;
4684
    case LIT:
4685
      if (left === 0) { break inf_leave; }
4686
      output[put++] = state.length;
4687
      left--;
4688
      state.mode = LEN;
4689
      break;
4690
    case CHECK:
4691
      if (state.wrap) {
4692
        //=== NEEDBITS(32);
4693
        while (bits < 32) {
4694
          if (have === 0) { break inf_leave; }
4695
          have--;
4696
          // Use '|' insdead of '+' to make sure that result is signed
4697
          hold |= input[next++] << bits;
4698
          bits += 8;
4699
        }
4700
        //===//
4701
        _out -= left;
4702
        strm.total_out += _out;
4703
        state.total += _out;
4704
        if (_out) {
4705
          strm.adler = state.check =
4706
              /*UPDATE(state.check, put - _out, _out);*/
4707
              (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
4708
4709
        }
4710
        _out = left;
4711
        // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
4712
        if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
4713
          strm.msg = 'incorrect data check';
4714
          state.mode = BAD;
4715
          break;
4716
        }
4717
        //=== INITBITS();
4718
        hold = 0;
4719
        bits = 0;
4720
        //===//
4721
        //Tracev((stderr, "inflate:   check matches trailer\n"));
4722
      }
4723
      state.mode = LENGTH;
4724
      /* falls through */
4725
    case LENGTH:
4726
      if (state.wrap && state.flags) {
4727
        //=== NEEDBITS(32);
4728
        while (bits < 32) {
4729
          if (have === 0) { break inf_leave; }
4730
          have--;
4731
          hold += input[next++] << bits;
4732
          bits += 8;
4733
        }
4734
        //===//
4735
        if (hold !== (state.total & 0xffffffff)) {
4736
          strm.msg = 'incorrect length check';
4737
          state.mode = BAD;
4738
          break;
4739
        }
4740
        //=== INITBITS();
4741
        hold = 0;
4742
        bits = 0;
4743
        //===//
4744
        //Tracev((stderr, "inflate:   length matches trailer\n"));
4745
      }
4746
      state.mode = DONE;
4747
      /* falls through */
4748
    case DONE:
4749
      ret = Z_STREAM_END;
4750
      break inf_leave;
4751
    case BAD:
4752
      ret = Z_DATA_ERROR;
4753
      break inf_leave;
4754
    case MEM:
4755
      return Z_MEM_ERROR;
4756
    case SYNC:
4757
      /* falls through */
4758
    default:
4759
      return Z_STREAM_ERROR;
4760
    }
4761
  }
4762
4763
  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
4764
4765
  /*
4766
     Return from inflate(), updating the total counts and the check value.
4767
     If there was no progress during the inflate() call, return a buffer
4768
     error.  Call updatewindow() to create and/or update the window state.
4769
     Note: a memory error from inflate() is non-recoverable.
4770
   */
4771
4772
  //--- RESTORE() ---
4773
  strm.next_out = put;
4774
  strm.avail_out = left;
4775
  strm.next_in = next;
4776
  strm.avail_in = have;
4777
  state.hold = hold;
4778
  state.bits = bits;
4779
  //---
4780
4781
  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
4782
                      (state.mode < CHECK || flush !== Z_FINISH))) {
4783
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
4784
      state.mode = MEM;
4785
      return Z_MEM_ERROR;
4786
    }
4787
  }
4788
  _in -= strm.avail_in;
4789
  _out -= strm.avail_out;
4790
  strm.total_in += _in;
4791
  strm.total_out += _out;
4792
  state.total += _out;
4793
  if (state.wrap && _out) {
4794
    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
4795
      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
4796
  }
4797
  strm.data_type = state.bits + (state.last ? 64 : 0) +
4798
                    (state.mode === TYPE ? 128 : 0) +
4799
                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
4800
  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
4801
    ret = Z_BUF_ERROR;
4802
  }
4803
  return ret;
4804
}
4805
4806
function inflateEnd(strm) {
4807
4808
  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
4809
    return Z_STREAM_ERROR;
4810
  }
4811
4812
  var state = strm.state;
4813
  if (state.window) {
4814
    state.window = null;
4815
  }
4816
  strm.state = null;
4817
  return Z_OK;
4818
}
4819
4820
function inflateGetHeader(strm, head) {
4821
  var state;
4822
4823
  /* check state */
4824
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
4825
  state = strm.state;
4826
  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
4827
4828
  /* save header structure */
4829
  state.head = head;
4830
  head.done = false;
4831
  return Z_OK;
4832
}
4833
4834
4835
exports.inflateReset = inflateReset;
4836
exports.inflateReset2 = inflateReset2;
4837
exports.inflateResetKeep = inflateResetKeep;
4838
exports.inflateInit = inflateInit;
4839
exports.inflateInit2 = inflateInit2;
4840
exports.inflate = inflate;
4841
exports.inflateEnd = inflateEnd;
4842
exports.inflateGetHeader = inflateGetHeader;
4843
exports.inflateInfo = 'pako inflate (from Nodeca project)';
4844
4845
/* Not implemented
4846
exports.inflateCopy = inflateCopy;
4847
exports.inflateGetDictionary = inflateGetDictionary;
4848
exports.inflateMark = inflateMark;
4849
exports.inflatePrime = inflatePrime;
4850
exports.inflateSetDictionary = inflateSetDictionary;
4851
exports.inflateSync = inflateSync;
4852
exports.inflateSyncPoint = inflateSyncPoint;
4853
exports.inflateUndermine = inflateUndermine;
4854
*/
4855
4856
},{"../utils/common":4,"./adler32":6,"./crc32":8,"./inffast":11,"./inftrees":13}],13:[function(require,module,exports){
4857
'use strict';
4858
4859
4860
var utils = require('../utils/common');
4861
4862
var MAXBITS = 15;
4863
var ENOUGH_LENS = 852;
4864
var ENOUGH_DISTS = 592;
4865
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
4866
4867
var CODES = 0;
4868
var LENS = 1;
4869
var DISTS = 2;
4870
4871
var lbase = [ /* Length codes 257..285 base */
4872
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
4873
  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
4874
];
4875
4876
var lext = [ /* Length codes 257..285 extra */
4877
  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
4878
  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
4879
];
4880
4881
var dbase = [ /* Distance codes 0..29 base */
4882
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
4883
  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
4884
  8193, 12289, 16385, 24577, 0, 0
4885
];
4886
4887
var dext = [ /* Distance codes 0..29 extra */
4888
  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
4889
  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
4890
  28, 28, 29, 29, 64, 64
4891
];
4892
4893
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
4894
{
4895
  var bits = opts.bits;
4896
      //here = opts.here; /* table entry for duplication */
4897
4898
  var len = 0;               /* a code's length in bits */
4899
  var sym = 0;               /* index of code symbols */
4900
  var min = 0, max = 0;          /* minimum and maximum code lengths */
4901
  var root = 0;              /* number of index bits for root table */
4902
  var curr = 0;              /* number of index bits for current table */
4903
  var drop = 0;              /* code bits to drop for sub-table */
4904
  var left = 0;                   /* number of prefix codes available */
4905
  var used = 0;              /* code entries in table used */
4906
  var huff = 0;              /* Huffman code */
4907
  var incr;              /* for incrementing code, index */
4908
  var fill;              /* index for replicating entries */
4909
  var low;               /* low bits for current root entry */
4910
  var mask;              /* mask for low root bits */
4911
  var next;             /* next available space in table */
4912
  var base = null;     /* base value table to use */
4913
  var base_index = 0;
4914
//  var shoextra;    /* extra bits table to use */
4915
  var end;                    /* use base and extra for symbol > end */
4916
  var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1];    /* number of codes of each length */
4917
  var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1];     /* offsets in table for each length */
4918
  var extra = null;
4919
  var extra_index = 0;
4920
4921
  var here_bits, here_op, here_val;
4922
4923
  /*
4924
   Process a set of code lengths to create a canonical Huffman code.  The
4925
   code lengths are lens[0..codes-1].  Each length corresponds to the
4926
   symbols 0..codes-1.  The Huffman code is generated by first sorting the
4927
   symbols by length from short to long, and retaining the symbol order
4928
   for codes with equal lengths.  Then the code starts with all zero bits
4929
   for the first code of the shortest length, and the codes are integer
4930
   increments for the same length, and zeros are appended as the length
4931
   increases.  For the deflate format, these bits are stored backwards
4932
   from their more natural integer increment ordering, and so when the
4933
   decoding tables are built in the large loop below, the integer codes
4934
   are incremented backwards.
4935
4936
   This routine assumes, but does not check, that all of the entries in
4937
   lens[] are in the range 0..MAXBITS.  The caller must assure this.
4938
   1..MAXBITS is interpreted as that code length.  zero means that that
4939
   symbol does not occur in this code.
4940
4941
   The codes are sorted by computing a count of codes for each length,
4942
   creating from that a table of starting indices for each length in the
4943
   sorted table, and then entering the symbols in order in the sorted
4944
   table.  The sorted table is work[], with that space being provided by
4945
   the caller.
4946
4947
   The length counts are used for other purposes as well, i.e. finding
4948
   the minimum and maximum length codes, determining if there are any
4949
   codes at all, checking for a valid set of lengths, and looking ahead
4950
   at length counts to determine sub-table sizes when building the
4951
   decoding tables.
4952
   */
4953
4954
  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
4955
  for (len = 0; len <= MAXBITS; len++) {
4956
    count[len] = 0;
4957
  }
4958
  for (sym = 0; sym < codes; sym++) {
4959
    count[lens[lens_index + sym]]++;
4960
  }
4961
4962
  /* bound code lengths, force root to be within code lengths */
4963
  root = bits;
4964
  for (max = MAXBITS; max >= 1; max--) {
4965
    if (count[max] !== 0) { break; }
4966
  }
4967
  if (root > max) {
4968
    root = max;
4969
  }
4970
  if (max === 0) {                     /* no symbols to code at all */
4971
    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
4972
    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
4973
    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
4974
    table[table_index++] = (1 << 24) | (64 << 16) | 0;
4975
4976
4977
    //table.op[opts.table_index] = 64;
4978
    //table.bits[opts.table_index] = 1;
4979
    //table.val[opts.table_index++] = 0;
4980
    table[table_index++] = (1 << 24) | (64 << 16) | 0;
4981
4982
    opts.bits = 1;
4983
    return 0;     /* no symbols, but wait for decoding to report error */
4984
  }
4985
  for (min = 1; min < max; min++) {
4986
    if (count[min] !== 0) { break; }
4987
  }
4988
  if (root < min) {
4989
    root = min;
4990
  }
4991
4992
  /* check for an over-subscribed or incomplete set of lengths */
4993
  left = 1;
4994
  for (len = 1; len <= MAXBITS; len++) {
4995
    left <<= 1;
4996
    left -= count[len];
4997
    if (left < 0) {
4998
      return -1;
4999
    }        /* over-subscribed */
5000
  }
5001
  if (left > 0 && (type === CODES || max !== 1)) {
5002
    return -1;                      /* incomplete set */
5003
  }
5004
5005
  /* generate offsets into symbol table for each length for sorting */
5006
  offs[1] = 0;
5007
  for (len = 1; len < MAXBITS; len++) {
5008
    offs[len + 1] = offs[len] + count[len];
5009
  }
5010
5011
  /* sort symbols by length, by symbol order within each length */
5012
  for (sym = 0; sym < codes; sym++) {
5013
    if (lens[lens_index + sym] !== 0) {
5014
      work[offs[lens[lens_index + sym]]++] = sym;
5015
    }
5016
  }
5017
5018
  /*
5019
   Create and fill in decoding tables.  In this loop, the table being
5020
   filled is at next and has curr index bits.  The code being used is huff
5021
   with length len.  That code is converted to an index by dropping drop
5022
   bits off of the bottom.  For codes where len is less than drop + curr,
5023
   those top drop + curr - len bits are incremented through all values to
5024
   fill the table with replicated entries.
5025
5026
   root is the number of index bits for the root table.  When len exceeds
5027
   root, sub-tables are created pointed to by the root entry with an index
5028
   of the low root bits of huff.  This is saved in low to check for when a
5029
   new sub-table should be started.  drop is zero when the root table is
5030
   being filled, and drop is root when sub-tables are being filled.
5031
5032
   When a new sub-table is needed, it is necessary to look ahead in the
5033
   code lengths to determine what size sub-table is needed.  The length
5034
   counts are used for this, and so count[] is decremented as codes are
5035
   entered in the tables.
5036
5037
   used keeps track of how many table entries have been allocated from the
5038
   provided *table space.  It is checked for LENS and DIST tables against
5039
   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
5040
   the initial root table size constants.  See the comments in inftrees.h
5041
   for more information.
5042
5043
   sym increments through all symbols, and the loop terminates when
5044
   all codes of length max, i.e. all codes, have been processed.  This
5045
   routine permits incomplete codes, so another loop after this one fills
5046
   in the rest of the decoding tables with invalid code markers.
5047
   */
5048
5049
  /* set up for code type */
5050
  // poor man optimization - use if-else instead of switch,
5051
  // to avoid deopts in old v8
5052
  if (type === CODES) {
5053
    base = extra = work;    /* dummy value--not used */
5054
    end = 19;
5055
5056
  } else if (type === LENS) {
5057
    base = lbase;
5058
    base_index -= 257;
5059
    extra = lext;
5060
    extra_index -= 257;
5061
    end = 256;
5062
5063
  } else {                    /* DISTS */
5064
    base = dbase;
5065
    extra = dext;
5066
    end = -1;
5067
  }
5068
5069
  /* initialize opts for loop */
5070
  huff = 0;                   /* starting code */
5071
  sym = 0;                    /* starting code symbol */
5072
  len = min;                  /* starting code length */
5073
  next = table_index;              /* current table to fill in */
5074
  curr = root;                /* current table index bits */
5075
  drop = 0;                   /* current bits to drop from code for index */
5076
  low = -1;                   /* trigger new sub-table when len > root */
5077
  used = 1 << root;          /* use root table entries */
5078
  mask = used - 1;            /* mask for comparing low */
5079
5080
  /* check available table space */
5081
  if ((type === LENS && used > ENOUGH_LENS) ||
5082
    (type === DISTS && used > ENOUGH_DISTS)) {
5083
    return 1;
5084
  }
5085
5086
  var i=0;
5087
  /* process all codes and make table entries */
5088
  for (;;) {
5089
    i++;
5090
    /* create table entry */
5091
    here_bits = len - drop;
5092
    if (work[sym] < end) {
5093
      here_op = 0;
5094
      here_val = work[sym];
5095
    }
5096
    else if (work[sym] > end) {
5097
      here_op = extra[extra_index + work[sym]];
5098
      here_val = base[base_index + work[sym]];
5099
    }
5100
    else {
5101
      here_op = 32 + 64;         /* end of block */
5102
      here_val = 0;
5103
    }
5104
5105
    /* replicate for those indices with low len bits equal to huff */
5106
    incr = 1 << (len - drop);
5107
    fill = 1 << curr;
5108
    min = fill;                 /* save offset to next table */
5109
    do {
5110
      fill -= incr;
5111
      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
5112
    } while (fill !== 0);
5113
5114
    /* backwards increment the len-bit code huff */
5115
    incr = 1 << (len - 1);
5116
    while (huff & incr) {
5117
      incr >>= 1;
5118
    }
5119
    if (incr !== 0) {
5120
      huff &= incr - 1;
5121
      huff += incr;
5122
    } else {
5123
      huff = 0;
5124
    }
5125
5126
    /* go to next symbol, update count, len */
5127
    sym++;
5128
    if (--count[len] === 0) {
5129
      if (len === max) { break; }
5130
      len = lens[lens_index + work[sym]];
5131
    }
5132
5133
    /* create new sub-table if needed */
5134
    if (len > root && (huff & mask) !== low) {
5135
      /* if first time, transition to sub-tables */
5136
      if (drop === 0) {
5137
        drop = root;
5138
      }
5139
5140
      /* increment past last table */
5141
      next += min;            /* here min is 1 << curr */
5142
5143
      /* determine length of next table */
5144
      curr = len - drop;
5145
      left = 1 << curr;
5146
      while (curr + drop < max) {
5147
        left -= count[curr + drop];
5148
        if (left <= 0) { break; }
5149
        curr++;
5150
        left <<= 1;
5151
      }
5152
5153
      /* check for enough space */
5154
      used += 1 << curr;
5155
      if ((type === LENS && used > ENOUGH_LENS) ||
5156
        (type === DISTS && used > ENOUGH_DISTS)) {
5157
        return 1;
5158
      }
5159
5160
      /* point entry in root table to sub-table */
5161
      low = huff & mask;
5162
      /*table.op[low] = curr;
5163
      table.bits[low] = root;
5164
      table.val[low] = next - opts.table_index;*/
5165
      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
5166
    }
5167
  }
5168
5169
  /* fill in remaining table entry if code is incomplete (guaranteed to have
5170
   at most one remaining entry, since if the code is incomplete, the
5171
   maximum code length that was allowed to get this far is one bit) */
5172
  if (huff !== 0) {
5173
    //table.op[next + huff] = 64;            /* invalid code marker */
5174
    //table.bits[next + huff] = len - drop;
5175
    //table.val[next + huff] = 0;
5176
    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
5177
  }
5178
5179
  /* set return parameters */
5180
  //opts.table_index += used;
5181
  opts.bits = root;
5182
  return 0;
5183
};
5184
5185
},{"../utils/common":4}],14:[function(require,module,exports){
5186
'use strict';
5187
5188
module.exports = {
5189
  '2':    'need dictionary',     /* Z_NEED_DICT       2  */
5190
  '1':    'stream end',          /* Z_STREAM_END      1  */
5191
  '0':    '',                    /* Z_OK              0  */
5192
  '-1':   'file error',          /* Z_ERRNO         (-1) */
5193
  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
5194
  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
5195
  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
5196
  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
5197
  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
5198
};
5199
5200
},{}],15:[function(require,module,exports){
5201
'use strict';
5202
5203
5204
var utils = require('../utils/common');
5205
5206
/* Public constants ==========================================================*/
5207
/* ===========================================================================*/
5208
5209
5210
//var Z_FILTERED          = 1;
5211
//var Z_HUFFMAN_ONLY      = 2;
5212
//var Z_RLE               = 3;
5213
var Z_FIXED               = 4;
5214
//var Z_DEFAULT_STRATEGY  = 0;
5215
5216
/* Possible values of the data_type field (though see inflate()) */
5217
var Z_BINARY              = 0;
5218
var Z_TEXT                = 1;
5219
//var Z_ASCII             = 1; // = Z_TEXT
5220
var Z_UNKNOWN             = 2;
5221
5222
/*============================================================================*/
5223
5224
5225
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
5226
5227
// From zutil.h
5228
5229
var STORED_BLOCK = 0;
5230
var STATIC_TREES = 1;
5231
var DYN_TREES    = 2;
5232
/* The three kinds of block type */
5233
5234
var MIN_MATCH    = 3;
5235
var MAX_MATCH    = 258;
5236
/* The minimum and maximum match lengths */
5237
5238
// From deflate.h
5239
/* ===========================================================================
5240
 * Internal compression state.
5241
 */
5242
5243
var LENGTH_CODES  = 29;
5244
/* number of length codes, not counting the special END_BLOCK code */
5245
5246
var LITERALS      = 256;
5247
/* number of literal bytes 0..255 */
5248
5249
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
5250
/* number of Literal or Length codes, including the END_BLOCK code */
5251
5252
var D_CODES       = 30;
5253
/* number of distance codes */
5254
5255
var BL_CODES      = 19;
5256
/* number of codes used to transfer the bit lengths */
5257
5258
var HEAP_SIZE     = 2*L_CODES + 1;
5259
/* maximum heap size */
5260
5261
var MAX_BITS      = 15;
5262
/* All codes must not exceed MAX_BITS bits */
5263
5264
var Buf_size      = 16;
5265
/* size of bit buffer in bi_buf */
5266
5267
5268
/* ===========================================================================
5269
 * Constants
5270
 */
5271
5272
var MAX_BL_BITS = 7;
5273
/* Bit length codes must not exceed MAX_BL_BITS bits */
5274
5275
var END_BLOCK   = 256;
5276
/* end of block literal code */
5277
5278
var REP_3_6     = 16;
5279
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
5280
5281
var REPZ_3_10   = 17;
5282
/* repeat a zero length 3-10 times  (3 bits of repeat count) */
5283
5284
var REPZ_11_138 = 18;
5285
/* repeat a zero length 11-138 times  (7 bits of repeat count) */
5286
5287
var extra_lbits =   /* extra bits for each length code */
5288
  [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];
5289
5290
var extra_dbits =   /* extra bits for each distance code */
5291
  [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];
5292
5293
var extra_blbits =  /* extra bits for each bit length code */
5294
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
5295
5296
var bl_order =
5297
  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
5298
/* The lengths of the bit length codes are sent in order of decreasing
5299
 * probability, to avoid transmitting the lengths for unused bit length codes.
5300
 */
5301
5302
/* ===========================================================================
5303
 * Local data. These are initialized only once.
5304
 */
5305
5306
// We pre-fill arrays with 0 to avoid uninitialized gaps
5307
5308
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
5309
5310
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
5311
var static_ltree  = new Array((L_CODES+2) * 2);
5312
zero(static_ltree);
5313
/* The static literal tree. Since the bit lengths are imposed, there is no
5314
 * need for the L_CODES extra codes used during heap construction. However
5315
 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
5316
 * below).
5317
 */
5318
5319
var static_dtree  = new Array(D_CODES * 2);
5320
zero(static_dtree);
5321
/* The static distance tree. (Actually a trivial tree since all codes use
5322
 * 5 bits.)
5323
 */
5324
5325
var _dist_code    = new Array(DIST_CODE_LEN);
5326
zero(_dist_code);
5327
/* Distance codes. The first 256 values correspond to the distances
5328
 * 3 .. 258, the last 256 values correspond to the top 8 bits of
5329
 * the 15 bit distances.
5330
 */
5331
5332
var _length_code  = new Array(MAX_MATCH-MIN_MATCH+1);
5333
zero(_length_code);
5334
/* length code for each normalized match length (0 == MIN_MATCH) */
5335
5336
var base_length   = new Array(LENGTH_CODES);
5337
zero(base_length);
5338
/* First normalized length for each code (0 = MIN_MATCH) */
5339
5340
var base_dist     = new Array(D_CODES);
5341
zero(base_dist);
5342
/* First normalized distance for each code (0 = distance of 1) */
5343
5344
5345
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
5346
5347
  this.static_tree  = static_tree;  /* static tree or NULL */
5348
  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
5349
  this.extra_base   = extra_base;   /* base index for extra_bits */
5350
  this.elems        = elems;        /* max number of elements in the tree */
5351
  this.max_length   = max_length;   /* max bit length for the codes */
5352
5353
  // show if `static_tree` has data or dummy - needed for monomorphic objects
5354
  this.has_stree    = static_tree && static_tree.length;
5355
};
5356
5357
5358
var static_l_desc;
5359
var static_d_desc;
5360
var static_bl_desc;
5361
5362
5363
var TreeDesc = function(dyn_tree, stat_desc) {
5364
  this.dyn_tree = dyn_tree;     /* the dynamic tree */
5365
  this.max_code = 0;            /* largest code with non zero frequency */
5366
  this.stat_desc = stat_desc;   /* the corresponding static tree */
5367
};
5368
5369
5370
5371
function d_code(dist) {
5372
  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
5373
}
5374
5375
5376
/* ===========================================================================
5377
 * Output a short LSB first on the stream.
5378
 * IN assertion: there is enough room in pendingBuf.
5379
 */
5380
function put_short (s, w) {
5381
//    put_byte(s, (uch)((w) & 0xff));
5382
//    put_byte(s, (uch)((ush)(w) >> 8));
5383
  s.pending_buf[s.pending++] = (w) & 0xff;
5384
  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
5385
}
5386
5387
5388
/* ===========================================================================
5389
 * Send a value on a given number of bits.
5390
 * IN assertion: length <= 16 and value fits in length bits.
5391
 */
5392
function send_bits(s, value, length) {
5393
  if (s.bi_valid > (Buf_size - length)) {
5394
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
5395
    put_short(s, s.bi_buf);
5396
    s.bi_buf = value >> (Buf_size - s.bi_valid);
5397
    s.bi_valid += length - Buf_size;
5398
  } else {
5399
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
5400
    s.bi_valid += length;
5401
  }
5402
}
5403
5404
5405
function send_code(s, c, tree) {
5406
  send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
5407
}
5408
5409
5410
/* ===========================================================================
5411
 * Reverse the first len bits of a code, using straightforward code (a faster
5412
 * method would use a table)
5413
 * IN assertion: 1 <= len <= 15
5414
 */
5415
function bi_reverse(code, len) {
5416
  var res = 0;
5417
  do {
5418
    res |= code & 1;
5419
    code >>>= 1;
5420
    res <<= 1;
5421
  } while (--len > 0);
5422
  return res >>> 1;
5423
}
5424
5425
5426
/* ===========================================================================
5427
 * Flush the bit buffer, keeping at most 7 bits in it.
5428
 */
5429
function bi_flush(s) {
5430
  if (s.bi_valid === 16) {
5431
    put_short(s, s.bi_buf);
5432
    s.bi_buf = 0;
5433
    s.bi_valid = 0;
5434
5435
  } else if (s.bi_valid >= 8) {
5436
    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
5437
    s.bi_buf >>= 8;
5438
    s.bi_valid -= 8;
5439
  }
5440
}
5441
5442
5443
/* ===========================================================================
5444
 * Compute the optimal bit lengths for a tree and update the total bit length
5445
 * for the current block.
5446
 * IN assertion: the fields freq and dad are set, heap[heap_max] and
5447
 *    above are the tree nodes sorted by increasing frequency.
5448
 * OUT assertions: the field len is set to the optimal bit length, the
5449
 *     array bl_count contains the frequencies for each bit length.
5450
 *     The length opt_len is updated; static_len is also updated if stree is
5451
 *     not null.
5452
 */
5453
function gen_bitlen(s, desc)
5454
//    deflate_state *s;
5455
//    tree_desc *desc;    /* the tree descriptor */
5456
{
5457
  var tree            = desc.dyn_tree;
5458
  var max_code        = desc.max_code;
5459
  var stree           = desc.stat_desc.static_tree;
5460
  var has_stree       = desc.stat_desc.has_stree;
5461
  var extra           = desc.stat_desc.extra_bits;
5462
  var base            = desc.stat_desc.extra_base;
5463
  var max_length      = desc.stat_desc.max_length;
5464
  var h;              /* heap index */
5465
  var n, m;           /* iterate over the tree elements */
5466
  var bits;           /* bit length */
5467
  var xbits;          /* extra bits */
5468
  var f;              /* frequency */
5469
  var overflow = 0;   /* number of elements with bit length too large */
5470
5471
  for (bits = 0; bits <= MAX_BITS; bits++) {
5472
    s.bl_count[bits] = 0;
5473
  }
5474
5475
  /* In a first pass, compute the optimal bit lengths (which may
5476
   * overflow in the case of the bit length tree).
5477
   */
5478
  tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
5479
5480
  for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
5481
    n = s.heap[h];
5482
    bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
5483
    if (bits > max_length) {
5484
      bits = max_length;
5485
      overflow++;
5486
    }
5487
    tree[n*2 + 1]/*.Len*/ = bits;
5488
    /* We overwrite tree[n].Dad which is no longer needed */
5489
5490
    if (n > max_code) { continue; } /* not a leaf node */
5491
5492
    s.bl_count[bits]++;
5493
    xbits = 0;
5494
    if (n >= base) {
5495
      xbits = extra[n-base];
5496
    }
5497
    f = tree[n * 2]/*.Freq*/;
5498
    s.opt_len += f * (bits + xbits);
5499
    if (has_stree) {
5500
      s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
5501
    }
5502
  }
5503
  if (overflow === 0) { return; }
5504
5505
  // Trace((stderr,"\nbit length overflow\n"));
5506
  /* This happens for example on obj2 and pic of the Calgary corpus */
5507
5508
  /* Find the first bit length which could increase: */
5509
  do {
5510
    bits = max_length-1;
5511
    while (s.bl_count[bits] === 0) { bits--; }
5512
    s.bl_count[bits]--;      /* move one leaf down the tree */
5513
    s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
5514
    s.bl_count[max_length]--;
5515
    /* The brother of the overflow item also moves one step up,
5516
     * but this does not affect bl_count[max_length]
5517
     */
5518
    overflow -= 2;
5519
  } while (overflow > 0);
5520
5521
  /* Now recompute all bit lengths, scanning in increasing frequency.
5522
   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
5523
   * lengths instead of fixing only the wrong ones. This idea is taken
5524
   * from 'ar' written by Haruhiko Okumura.)
5525
   */
5526
  for (bits = max_length; bits !== 0; bits--) {
5527
    n = s.bl_count[bits];
5528
    while (n !== 0) {
5529
      m = s.heap[--h];
5530
      if (m > max_code) { continue; }
5531
      if (tree[m*2 + 1]/*.Len*/ !== bits) {
5532
        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
5533
        s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
5534
        tree[m*2 + 1]/*.Len*/ = bits;
5535
      }
5536
      n--;
5537
    }
5538
  }
5539
}
5540
5541
5542
/* ===========================================================================
5543
 * Generate the codes for a given tree and bit counts (which need not be
5544
 * optimal).
5545
 * IN assertion: the array bl_count contains the bit length statistics for
5546
 * the given tree and the field len is set for all tree elements.
5547
 * OUT assertion: the field code is set for all tree elements of non
5548
 *     zero code length.
5549
 */
5550
function gen_codes(tree, max_code, bl_count)
5551
//    ct_data *tree;             /* the tree to decorate */
5552
//    int max_code;              /* largest code with non zero frequency */
5553
//    ushf *bl_count;            /* number of codes at each bit length */
5554
{
5555
  var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
5556
  var code = 0;              /* running code value */
5557
  var bits;                  /* bit index */
5558
  var n;                     /* code index */
5559
5560
  /* The distribution counts are first used to generate the code values
5561
   * without bit reversal.
5562
   */
5563
  for (bits = 1; bits <= MAX_BITS; bits++) {
5564
    next_code[bits] = code = (code + bl_count[bits-1]) << 1;
5565
  }
5566
  /* Check that the bit counts in bl_count are consistent. The last code
5567
   * must be all ones.
5568
   */
5569
  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
5570
  //        "inconsistent bit counts");
5571
  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
5572
5573
  for (n = 0;  n <= max_code; n++) {
5574
    var len = tree[n*2 + 1]/*.Len*/;
5575
    if (len === 0) { continue; }
5576
    /* Now reverse the bits */
5577
    tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
5578
5579
    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
5580
    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
5581
  }
5582
}
5583
5584
5585
/* ===========================================================================
5586
 * Initialize the various 'constant' tables.
5587
 */
5588
function tr_static_init() {
5589
  var n;        /* iterates over tree elements */
5590
  var bits;     /* bit counter */
5591
  var length;   /* length value */
5592
  var code;     /* code value */
5593
  var dist;     /* distance index */
5594
  var bl_count = new Array(MAX_BITS+1);
5595
  /* number of codes at each bit length for an optimal tree */
5596
5597
  // do check in _tr_init()
5598
  //if (static_init_done) return;
5599
5600
  /* For some embedded targets, global variables are not initialized: */
5601
/*#ifdef NO_INIT_GLOBAL_POINTERS
5602
  static_l_desc.static_tree = static_ltree;
5603
  static_l_desc.extra_bits = extra_lbits;
5604
  static_d_desc.static_tree = static_dtree;
5605
  static_d_desc.extra_bits = extra_dbits;
5606
  static_bl_desc.extra_bits = extra_blbits;
5607
#endif*/
5608
5609
  /* Initialize the mapping length (0..255) -> length code (0..28) */
5610
  length = 0;
5611
  for (code = 0; code < LENGTH_CODES-1; code++) {
5612
    base_length[code] = length;
5613
    for (n = 0; n < (1<<extra_lbits[code]); n++) {
5614
      _length_code[length++] = code;
5615
    }
5616
  }
5617
  //Assert (length == 256, "tr_static_init: length != 256");
5618
  /* Note that the length 255 (match length 258) can be represented
5619
   * in two different ways: code 284 + 5 bits or code 285, so we
5620
   * overwrite length_code[255] to use the best encoding:
5621
   */
5622
  _length_code[length-1] = code;
5623
5624
  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
5625
  dist = 0;
5626
  for (code = 0 ; code < 16; code++) {
5627
    base_dist[code] = dist;
5628
    for (n = 0; n < (1<<extra_dbits[code]); n++) {
5629
      _dist_code[dist++] = code;
5630
    }
5631
  }
5632
  //Assert (dist == 256, "tr_static_init: dist != 256");
5633
  dist >>= 7; /* from now on, all distances are divided by 128 */
5634
  for (; code < D_CODES; code++) {
5635
    base_dist[code] = dist << 7;
5636
    for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
5637
      _dist_code[256 + dist++] = code;
5638
    }
5639
  }
5640
  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
5641
5642
  /* Construct the codes of the static literal tree */
5643
  for (bits = 0; bits <= MAX_BITS; bits++) {
5644
    bl_count[bits] = 0;
5645
  }
5646
5647
  n = 0;
5648
  while (n <= 143) {
5649
    static_ltree[n*2 + 1]/*.Len*/ = 8;
5650
    n++;
5651
    bl_count[8]++;
5652
  }
5653
  while (n <= 255) {
5654
    static_ltree[n*2 + 1]/*.Len*/ = 9;
5655
    n++;
5656
    bl_count[9]++;
5657
  }
5658
  while (n <= 279) {
5659
    static_ltree[n*2 + 1]/*.Len*/ = 7;
5660
    n++;
5661
    bl_count[7]++;
5662
  }
5663
  while (n <= 287) {
5664
    static_ltree[n*2 + 1]/*.Len*/ = 8;
5665
    n++;
5666
    bl_count[8]++;
5667
  }
5668
  /* Codes 286 and 287 do not exist, but we must include them in the
5669
   * tree construction to get a canonical Huffman tree (longest code
5670
   * all ones)
5671
   */
5672
  gen_codes(static_ltree, L_CODES+1, bl_count);
5673
5674
  /* The static distance tree is trivial: */
5675
  for (n = 0; n < D_CODES; n++) {
5676
    static_dtree[n*2 + 1]/*.Len*/ = 5;
5677
    static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
5678
  }
5679
5680
  // Now data ready and we can init static trees
5681
  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
5682
  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
5683
  static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
5684
5685
  //static_init_done = true;
5686
}
5687
5688
5689
/* ===========================================================================
5690
 * Initialize a new block.
5691
 */
5692
function init_block(s) {
5693
  var n; /* iterates over tree elements */
5694
5695
  /* Initialize the trees. */
5696
  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
5697
  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
5698
  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
5699
5700
  s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
5701
  s.opt_len = s.static_len = 0;
5702
  s.last_lit = s.matches = 0;
5703
}
5704
5705
5706
/* ===========================================================================
5707
 * Flush the bit buffer and align the output on a byte boundary
5708
 */
5709
function bi_windup(s)
5710
{
5711
  if (s.bi_valid > 8) {
5712
    put_short(s, s.bi_buf);
5713
  } else if (s.bi_valid > 0) {
5714
    //put_byte(s, (Byte)s->bi_buf);
5715
    s.pending_buf[s.pending++] = s.bi_buf;
5716
  }
5717
  s.bi_buf = 0;
5718
  s.bi_valid = 0;
5719
}
5720
5721
/* ===========================================================================
5722
 * Copy a stored block, storing first the length and its
5723
 * one's complement if requested.
5724
 */
5725
function copy_block(s, buf, len, header)
5726
//DeflateState *s;
5727
//charf    *buf;    /* the input data */
5728
//unsigned len;     /* its length */
5729
//int      header;  /* true if block header must be written */
5730
{
5731
  bi_windup(s);        /* align on byte boundary */
5732
5733
  if (header) {
5734
    put_short(s, len);
5735
    put_short(s, ~len);
5736
  }
5737
//  while (len--) {
5738
//    put_byte(s, *buf++);
5739
//  }
5740
  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
5741
  s.pending += len;
5742
}
5743
5744
/* ===========================================================================
5745
 * Compares to subtrees, using the tree depth as tie breaker when
5746
 * the subtrees have equal frequency. This minimizes the worst case length.
5747
 */
5748
function smaller(tree, n, m, depth) {
5749
  var _n2 = n*2;
5750
  var _m2 = m*2;
5751
  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
5752
         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
5753
}
5754
5755
/* ===========================================================================
5756
 * Restore the heap property by moving down the tree starting at node k,
5757
 * exchanging a node with the smallest of its two sons if necessary, stopping
5758
 * when the heap property is re-established (each father smaller than its
5759
 * two sons).
5760
 */
5761
function pqdownheap(s, tree, k)
5762
//    deflate_state *s;
5763
//    ct_data *tree;  /* the tree to restore */
5764
//    int k;               /* node to move down */
5765
{
5766
  var v = s.heap[k];
5767
  var j = k << 1;  /* left son of k */
5768
  while (j <= s.heap_len) {
5769
    /* Set j to the smallest of the two sons: */
5770
    if (j < s.heap_len &&
5771
      smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
5772
      j++;
5773
    }
5774
    /* Exit if v is smaller than both sons */
5775
    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
5776
5777
    /* Exchange v with the smallest son */
5778
    s.heap[k] = s.heap[j];
5779
    k = j;
5780
5781
    /* And continue down the tree, setting j to the left son of k */
5782
    j <<= 1;
5783
  }
5784
  s.heap[k] = v;
5785
}
5786
5787
5788
// inlined manually
5789
// var SMALLEST = 1;
5790
5791
/* ===========================================================================
5792
 * Send the block data compressed using the given Huffman trees
5793
 */
5794
function compress_block(s, ltree, dtree)
5795
//    deflate_state *s;
5796
//    const ct_data *ltree; /* literal tree */
5797
//    const ct_data *dtree; /* distance tree */
5798
{
5799
  var dist;           /* distance of matched string */
5800
  var lc;             /* match length or unmatched char (if dist == 0) */
5801
  var lx = 0;         /* running index in l_buf */
5802
  var code;           /* the code to send */
5803
  var extra;          /* number of extra bits to send */
5804
5805
  if (s.last_lit !== 0) {
5806
    do {
5807
      dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
5808
      lc = s.pending_buf[s.l_buf + lx];
5809
      lx++;
5810
5811
      if (dist === 0) {
5812
        send_code(s, lc, ltree); /* send a literal byte */
5813
        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
5814
      } else {
5815
        /* Here, lc is the match length - MIN_MATCH */
5816
        code = _length_code[lc];
5817
        send_code(s, code+LITERALS+1, ltree); /* send the length code */
5818
        extra = extra_lbits[code];
5819
        if (extra !== 0) {
5820
          lc -= base_length[code];
5821
          send_bits(s, lc, extra);       /* send the extra length bits */
5822
        }
5823
        dist--; /* dist is now the match distance - 1 */
5824
        code = d_code(dist);
5825
        //Assert (code < D_CODES, "bad d_code");
5826
5827
        send_code(s, code, dtree);       /* send the distance code */
5828
        extra = extra_dbits[code];
5829
        if (extra !== 0) {
5830
          dist -= base_dist[code];
5831
          send_bits(s, dist, extra);   /* send the extra distance bits */
5832
        }
5833
      } /* literal or match pair ? */
5834
5835
      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
5836
      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
5837
      //       "pendingBuf overflow");
5838
5839
    } while (lx < s.last_lit);
5840
  }
5841
5842
  send_code(s, END_BLOCK, ltree);
5843
}
5844
5845
5846
/* ===========================================================================
5847
 * Construct one Huffman tree and assigns the code bit strings and lengths.
5848
 * Update the total bit length for the current block.
5849
 * IN assertion: the field freq is set for all tree elements.
5850
 * OUT assertions: the fields len and code are set to the optimal bit length
5851
 *     and corresponding code. The length opt_len is updated; static_len is
5852
 *     also updated if stree is not null. The field max_code is set.
5853
 */
5854
function build_tree(s, desc)
5855
//    deflate_state *s;
5856
//    tree_desc *desc; /* the tree descriptor */
5857
{
5858
  var tree     = desc.dyn_tree;
5859
  var stree    = desc.stat_desc.static_tree;
5860
  var has_stree = desc.stat_desc.has_stree;
5861
  var elems    = desc.stat_desc.elems;
5862
  var n, m;          /* iterate over heap elements */
5863
  var max_code = -1; /* largest code with non zero frequency */
5864
  var node;          /* new node being created */
5865
5866
  /* Construct the initial heap, with least frequent element in
5867
   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
5868
   * heap[0] is not used.
5869
   */
5870
  s.heap_len = 0;
5871
  s.heap_max = HEAP_SIZE;
5872
5873
  for (n = 0; n < elems; n++) {
5874
    if (tree[n * 2]/*.Freq*/ !== 0) {
5875
      s.heap[++s.heap_len] = max_code = n;
5876
      s.depth[n] = 0;
5877
5878
    } else {
5879
      tree[n*2 + 1]/*.Len*/ = 0;
5880
    }
5881
  }
5882
5883
  /* The pkzip format requires that at least one distance code exists,
5884
   * and that at least one bit should be sent even if there is only one
5885
   * possible code. So to avoid special checks later on we force at least
5886
   * two codes of non zero frequency.
5887
   */
5888
  while (s.heap_len < 2) {
5889
    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
5890
    tree[node * 2]/*.Freq*/ = 1;
5891
    s.depth[node] = 0;
5892
    s.opt_len--;
5893
5894
    if (has_stree) {
5895
      s.static_len -= stree[node*2 + 1]/*.Len*/;
5896
    }
5897
    /* node is 0 or 1 so it does not have extra bits */
5898
  }
5899
  desc.max_code = max_code;
5900
5901
  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
5902
   * establish sub-heaps of increasing lengths:
5903
   */
5904
  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
5905
5906
  /* Construct the Huffman tree by repeatedly combining the least two
5907
   * frequent nodes.
5908
   */
5909
  node = elems;              /* next internal node of the tree */
5910
  do {
5911
    //pqremove(s, tree, n);  /* n = node of least frequency */
5912
    /*** pqremove ***/
5913
    n = s.heap[1/*SMALLEST*/];
5914
    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
5915
    pqdownheap(s, tree, 1/*SMALLEST*/);
5916
    /***/
5917
5918
    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
5919
5920
    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
5921
    s.heap[--s.heap_max] = m;
5922
5923
    /* Create a new node father of n and m */
5924
    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
5925
    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
5926
    tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
5927
5928
    /* and insert the new node in the heap */
5929
    s.heap[1/*SMALLEST*/] = node++;
5930
    pqdownheap(s, tree, 1/*SMALLEST*/);
5931
5932
  } while (s.heap_len >= 2);
5933
5934
  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
5935
5936
  /* At this point, the fields freq and dad are set. We can now
5937
   * generate the bit lengths.
5938
   */
5939
  gen_bitlen(s, desc);
5940
5941
  /* The field len is now set, we can generate the bit codes */
5942
  gen_codes(tree, max_code, s.bl_count);
5943
}
5944
5945
5946
/* ===========================================================================
5947
 * Scan a literal or distance tree to determine the frequencies of the codes
5948
 * in the bit length tree.
5949
 */
5950
function scan_tree(s, tree, max_code)
5951
//    deflate_state *s;
5952
//    ct_data *tree;   /* the tree to be scanned */
5953
//    int max_code;    /* and its largest code of non zero frequency */
5954
{
5955
  var n;                     /* iterates over all tree elements */
5956
  var prevlen = -1;          /* last emitted length */
5957
  var curlen;                /* length of current code */
5958
5959
  var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
5960
5961
  var count = 0;             /* repeat count of the current code */
5962
  var max_count = 7;         /* max repeat count */
5963
  var min_count = 4;         /* min repeat count */
5964
5965
  if (nextlen === 0) {
5966
    max_count = 138;
5967
    min_count = 3;
5968
  }
5969
  tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
5970
5971
  for (n = 0; n <= max_code; n++) {
5972
    curlen = nextlen;
5973
    nextlen = tree[(n+1)*2 + 1]/*.Len*/;
5974
5975
    if (++count < max_count && curlen === nextlen) {
5976
      continue;
5977
5978
    } else if (count < min_count) {
5979
      s.bl_tree[curlen * 2]/*.Freq*/ += count;
5980
5981
    } else if (curlen !== 0) {
5982
5983
      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
5984
      s.bl_tree[REP_3_6*2]/*.Freq*/++;
5985
5986
    } else if (count <= 10) {
5987
      s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
5988
5989
    } else {
5990
      s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
5991
    }
5992
5993
    count = 0;
5994
    prevlen = curlen;
5995
5996
    if (nextlen === 0) {
5997
      max_count = 138;
5998
      min_count = 3;
5999
6000
    } else if (curlen === nextlen) {
6001
      max_count = 6;
6002
      min_count = 3;
6003
6004
    } else {
6005
      max_count = 7;
6006
      min_count = 4;
6007
    }
6008
  }
6009
}
6010
6011
6012
/* ===========================================================================
6013
 * Send a literal or distance tree in compressed form, using the codes in
6014
 * bl_tree.
6015
 */
6016
function send_tree(s, tree, max_code)
6017
//    deflate_state *s;
6018
//    ct_data *tree; /* the tree to be scanned */
6019
//    int max_code;       /* and its largest code of non zero frequency */
6020
{
6021
  var n;                     /* iterates over all tree elements */
6022
  var prevlen = -1;          /* last emitted length */
6023
  var curlen;                /* length of current code */
6024
6025
  var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
6026
6027
  var count = 0;             /* repeat count of the current code */
6028
  var max_count = 7;         /* max repeat count */
6029
  var min_count = 4;         /* min repeat count */
6030
6031
  /* tree[max_code+1].Len = -1; */  /* guard already set */
6032
  if (nextlen === 0) {
6033
    max_count = 138;
6034
    min_count = 3;
6035
  }
6036
6037
  for (n = 0; n <= max_code; n++) {
6038
    curlen = nextlen;
6039
    nextlen = tree[(n+1)*2 + 1]/*.Len*/;
6040
6041
    if (++count < max_count && curlen === nextlen) {
6042
      continue;
6043
6044
    } else if (count < min_count) {
6045
      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
6046
6047
    } else if (curlen !== 0) {
6048
      if (curlen !== prevlen) {
6049
        send_code(s, curlen, s.bl_tree);
6050
        count--;
6051
      }
6052
      //Assert(count >= 3 && count <= 6, " 3_6?");
6053
      send_code(s, REP_3_6, s.bl_tree);
6054
      send_bits(s, count-3, 2);
6055
6056
    } else if (count <= 10) {
6057
      send_code(s, REPZ_3_10, s.bl_tree);
6058
      send_bits(s, count-3, 3);
6059
6060
    } else {
6061
      send_code(s, REPZ_11_138, s.bl_tree);
6062
      send_bits(s, count-11, 7);
6063
    }
6064
6065
    count = 0;
6066
    prevlen = curlen;
6067
    if (nextlen === 0) {
6068
      max_count = 138;
6069
      min_count = 3;
6070
6071
    } else if (curlen === nextlen) {
6072
      max_count = 6;
6073
      min_count = 3;
6074
6075
    } else {
6076
      max_count = 7;
6077
      min_count = 4;
6078
    }
6079
  }
6080
}
6081
6082
6083
/* ===========================================================================
6084
 * Construct the Huffman tree for the bit lengths and return the index in
6085
 * bl_order of the last bit length code to send.
6086
 */
6087
function build_bl_tree(s) {
6088
  var max_blindex;  /* index of last bit length code of non zero freq */
6089
6090
  /* Determine the bit length frequencies for literal and distance trees */
6091
  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
6092
  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
6093
6094
  /* Build the bit length tree: */
6095
  build_tree(s, s.bl_desc);
6096
  /* opt_len now includes the length of the tree representations, except
6097
   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
6098
   */
6099
6100
  /* Determine the number of bit length codes to send. The pkzip format
6101
   * requires that at least 4 bit length codes be sent. (appnote.txt says
6102
   * 3 but the actual value used is 4.)
6103
   */
6104
  for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
6105
    if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
6106
      break;
6107
    }
6108
  }
6109
  /* Update opt_len to include the bit length tree and counts */
6110
  s.opt_len += 3*(max_blindex+1) + 5+5+4;
6111
  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
6112
  //        s->opt_len, s->static_len));
6113
6114
  return max_blindex;
6115
}
6116
6117
6118
/* ===========================================================================
6119
 * Send the header for a block using dynamic Huffman trees: the counts, the
6120
 * lengths of the bit length codes, the literal tree and the distance tree.
6121
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
6122
 */
6123
function send_all_trees(s, lcodes, dcodes, blcodes)
6124
//    deflate_state *s;
6125
//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
6126
{
6127
  var rank;                    /* index in bl_order */
6128
6129
  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
6130
  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
6131
  //        "too many codes");
6132
  //Tracev((stderr, "\nbl counts: "));
6133
  send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
6134
  send_bits(s, dcodes-1,   5);
6135
  send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
6136
  for (rank = 0; rank < blcodes; rank++) {
6137
    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
6138
    send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
6139
  }
6140
  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
6141
6142
  send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
6143
  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
6144
6145
  send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
6146
  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
6147
}
6148
6149
6150
/* ===========================================================================
6151
 * Check if the data type is TEXT or BINARY, using the following algorithm:
6152
 * - TEXT if the two conditions below are satisfied:
6153
 *    a) There are no non-portable control characters belonging to the
6154
 *       "black list" (0..6, 14..25, 28..31).
6155
 *    b) There is at least one printable character belonging to the
6156
 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
6157
 * - BINARY otherwise.
6158
 * - The following partially-portable control characters form a
6159
 *   "gray list" that is ignored in this detection algorithm:
6160
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
6161
 * IN assertion: the fields Freq of dyn_ltree are set.
6162
 */
6163
function detect_data_type(s) {
6164
  /* black_mask is the bit mask of black-listed bytes
6165
   * set bits 0..6, 14..25, and 28..31
6166
   * 0xf3ffc07f = binary 11110011111111111100000001111111
6167
   */
6168
  var black_mask = 0xf3ffc07f;
6169
  var n;
6170
6171
  /* Check for non-textual ("black-listed") bytes. */
6172
  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
6173
    if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
6174
      return Z_BINARY;
6175
    }
6176
  }
6177
6178
  /* Check for textual ("white-listed") bytes. */
6179
  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
6180
      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
6181
    return Z_TEXT;
6182
  }
6183
  for (n = 32; n < LITERALS; n++) {
6184
    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
6185
      return Z_TEXT;
6186
    }
6187
  }
6188
6189
  /* There are no "black-listed" or "white-listed" bytes:
6190
   * this stream either is empty or has tolerated ("gray-listed") bytes only.
6191
   */
6192
  return Z_BINARY;
6193
}
6194
6195
6196
var static_init_done = false;
6197
6198
/* ===========================================================================
6199
 * Initialize the tree data structures for a new zlib stream.
6200
 */
6201
function _tr_init(s)
6202
{
6203
6204
  if (!static_init_done) {
6205
    tr_static_init();
6206
    static_init_done = true;
6207
  }
6208
6209
  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
6210
  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
6211
  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
6212
6213
  s.bi_buf = 0;
6214
  s.bi_valid = 0;
6215
6216
  /* Initialize the first block of the first file: */
6217
  init_block(s);
6218
}
6219
6220
6221
/* ===========================================================================
6222
 * Send a stored block
6223
 */
6224
function _tr_stored_block(s, buf, stored_len, last)
6225
//DeflateState *s;
6226
//charf *buf;       /* input block */
6227
//ulg stored_len;   /* length of input block */
6228
//int last;         /* one if this is the last block for a file */
6229
{
6230
  send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3);    /* send block type */
6231
  copy_block(s, buf, stored_len, true); /* with header */
6232
}
6233
6234
6235
/* ===========================================================================
6236
 * Send one empty static block to give enough lookahead for inflate.
6237
 * This takes 10 bits, of which 7 may remain in the bit buffer.
6238
 */
6239
function _tr_align(s) {
6240
  send_bits(s, STATIC_TREES<<1, 3);
6241
  send_code(s, END_BLOCK, static_ltree);
6242
  bi_flush(s);
6243
}
6244
6245
6246
/* ===========================================================================
6247
 * Determine the best encoding for the current block: dynamic trees, static
6248
 * trees or store, and output the encoded block to the zip file.
6249
 */
6250
function _tr_flush_block(s, buf, stored_len, last)
6251
//DeflateState *s;
6252
//charf *buf;       /* input block, or NULL if too old */
6253
//ulg stored_len;   /* length of input block */
6254
//int last;         /* one if this is the last block for a file */
6255
{
6256
  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
6257
  var max_blindex = 0;        /* index of last bit length code of non zero freq */
6258
6259
  /* Build the Huffman trees unless a stored block is forced */
6260
  if (s.level > 0) {
6261
6262
    /* Check if the file is binary or text */
6263
    if (s.strm.data_type === Z_UNKNOWN) {
6264
      s.strm.data_type = detect_data_type(s);
6265
    }
6266
6267
    /* Construct the literal and distance trees */
6268
    build_tree(s, s.l_desc);
6269
    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
6270
    //        s->static_len));
6271
6272
    build_tree(s, s.d_desc);
6273
    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
6274
    //        s->static_len));
6275
    /* At this point, opt_len and static_len are the total bit lengths of
6276
     * the compressed block data, excluding the tree representations.
6277
     */
6278
6279
    /* Build the bit length tree for the above two trees, and get the index
6280
     * in bl_order of the last bit length code to send.
6281
     */
6282
    max_blindex = build_bl_tree(s);
6283
6284
    /* Determine the best encoding. Compute the block lengths in bytes. */
6285
    opt_lenb = (s.opt_len+3+7) >>> 3;
6286
    static_lenb = (s.static_len+3+7) >>> 3;
6287
6288
    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
6289
    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
6290
    //        s->last_lit));
6291
6292
    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
6293
6294
  } else {
6295
    // Assert(buf != (char*)0, "lost buf");
6296
    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
6297
  }
6298
6299
  if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
6300
    /* 4: two words for the lengths */
6301
6302
    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
6303
     * Otherwise we can't have processed more than WSIZE input bytes since
6304
     * the last block flush, because compression would have been
6305
     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
6306
     * transform a block into a stored block.
6307
     */
6308
    _tr_stored_block(s, buf, stored_len, last);
6309
6310
  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
6311
6312
    send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
6313
    compress_block(s, static_ltree, static_dtree);
6314
6315
  } else {
6316
    send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
6317
    send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
6318
    compress_block(s, s.dyn_ltree, s.dyn_dtree);
6319
  }
6320
  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
6321
  /* The above check is made mod 2^32, for files larger than 512 MB
6322
   * and uLong implemented on 32 bits.
6323
   */
6324
  init_block(s);
6325
6326
  if (last) {
6327
    bi_windup(s);
6328
  }
6329
  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
6330
  //       s->compressed_len-7*last));
6331
}
6332
6333
/* ===========================================================================
6334
 * Save the match info and tally the frequency counts. Return true if
6335
 * the current block must be flushed.
6336
 */
6337
function _tr_tally(s, dist, lc)
6338
//    deflate_state *s;
6339
//    unsigned dist;  /* distance of matched string */
6340
//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
6341
{
6342
  //var out_length, in_length, dcode;
6343
6344
  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
6345
  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
6346
6347
  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
6348
  s.last_lit++;
6349
6350
  if (dist === 0) {
6351
    /* lc is the unmatched char */
6352
    s.dyn_ltree[lc*2]/*.Freq*/++;
6353
  } else {
6354
    s.matches++;
6355
    /* Here, lc is the match length - MIN_MATCH */
6356
    dist--;             /* dist = match distance - 1 */
6357
    //Assert((ush)dist < (ush)MAX_DIST(s) &&
6358
    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
6359
    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
6360
6361
    s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
6362
    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
6363
  }
6364
6365
// (!) This block is disabled in zlib defailts,
6366
// don't enable it for binary compatibility
6367
6368
//#ifdef TRUNCATE_BLOCK
6369
//  /* Try to guess if it is profitable to stop the current block here */
6370
//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
6371
//    /* Compute an upper bound for the compressed length */
6372
//    out_length = s.last_lit*8;
6373
//    in_length = s.strstart - s.block_start;
6374
//
6375
//    for (dcode = 0; dcode < D_CODES; dcode++) {
6376
//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
6377
//    }
6378
//    out_length >>>= 3;
6379
//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
6380
//    //       s->last_lit, in_length, out_length,
6381
//    //       100L - out_length*100L/in_length));
6382
//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
6383
//      return true;
6384
//    }
6385
//  }
6386
//#endif
6387
6388
  return (s.last_lit === s.lit_bufsize-1);
6389
  /* We avoid equality with lit_bufsize because of wraparound at 64K
6390
   * on 16 bit machines and because stored blocks are restricted to
6391
   * 64K-1 bytes.
6392
   */
6393
}
6394
6395
exports._tr_init  = _tr_init;
6396
exports._tr_stored_block = _tr_stored_block;
6397
exports._tr_flush_block  = _tr_flush_block;
6398
exports._tr_tally = _tr_tally;
6399
exports._tr_align = _tr_align;
6400
6401
},{"../utils/common":4}],16:[function(require,module,exports){
6402
'use strict';
6403
6404
6405
function ZStream() {
6406
  /* next input byte */
6407
  this.input = null; // JS specific, because we have no pointers
6408
  this.next_in = 0;
6409
  /* number of bytes available at input */
6410
  this.avail_in = 0;
6411
  /* total number of input bytes read so far */
6412
  this.total_in = 0;
6413
  /* next output byte should be put there */
6414
  this.output = null; // JS specific, because we have no pointers
6415
  this.next_out = 0;
6416
  /* remaining free space at output */
6417
  this.avail_out = 0;
6418
  /* total number of bytes output so far */
6419
  this.total_out = 0;
6420
  /* last error message, NULL if no error */
6421
  this.msg = ''/*Z_NULL*/;
6422
  /* not visible by applications */
6423
  this.state = null;
6424
  /* best guess about the data type: binary or text */
6425
  this.data_type = 2/*Z_UNKNOWN*/;
6426
  /* adler32 value of the uncompressed data */
6427
  this.adler = 0;
6428
}
6429
6430
module.exports = ZStream;
6431
6432
},{}],17:[function(require,module,exports){
6433
6434
/*jslint browser: true, node: true */
6435
/*global require, module */
6436
6437
"use strict";
6438
6439
/*** Imports ***/
6440
6441
/**
6442
 * nifti
6443
 * @type {*|{}}
6444
 */
6445
var nifti = nifti || {};
6446
nifti.NIFTI1 = nifti.NIFTI1 || ((typeof require !== 'undefined') ? require('./nifti1.js') : null);
6447
nifti.NIFTI2 = nifti.NIFTI2 || ((typeof require !== 'undefined') ? require('./nifti2.js') : null);
6448
nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
6449
6450
var pako = pako || ((typeof require !== 'undefined') ? require('pako') : null);
6451
6452
6453
6454
/*** Static Methods ***/
6455
6456
/**
6457
 * Returns true if this data represents a NIFTI-1 header.
6458
 * @param {ArrayBuffer} data
6459
 * @returns {boolean}
6460
 */
6461
nifti.isNIFTI1 = function (data) {
6462
    var buf, mag1, mag2, mag3;
6463
6464
    if (data.byteLength < nifti.NIFTI1.STANDARD_HEADER_SIZE) {
6465
        return false;
6466
    }
6467
6468
    buf = new DataView(data);
6469
6470
    if (buf)
6471
6472
    mag1 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION);
6473
    mag2 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION + 1);
6474
    mag3 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION + 2);
6475
6476
    return !!((mag1 === nifti.NIFTI1.MAGIC_NUMBER[0]) && (mag2 === nifti.NIFTI1.MAGIC_NUMBER[1]) &&
6477
        (mag3 === nifti.NIFTI1.MAGIC_NUMBER[2]));
6478
};
6479
6480
6481
/**
6482
 * Returns true if this data represents a NIFTI-2 header.
6483
 * @param {ArrayBuffer} data
6484
 * @returns {boolean}
6485
 */
6486
nifti.isNIFTI2 = function (data) {
6487
    var buf, mag1, mag2, mag3;
6488
6489
    if (data.byteLength < nifti.NIFTI1.STANDARD_HEADER_SIZE) {
6490
        return false;
6491
    }
6492
6493
    buf = new DataView(data);
6494
    mag1 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION);
6495
    mag2 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION + 1);
6496
    mag3 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION + 2);
6497
6498
    return !!((mag1 === nifti.NIFTI2.MAGIC_NUMBER[0]) && (mag2 === nifti.NIFTI2.MAGIC_NUMBER[1]) &&
6499
    (mag3 === nifti.NIFTI2.MAGIC_NUMBER[2]));
6500
};
6501
6502
6503
6504
/**
6505
 * Returns true if this data represents a NIFTI header.
6506
 * @param {ArrayBuffer} data
6507
 * @returns {boolean}
6508
 */
6509
nifti.isNIFTI = function (data) {
6510
    return (nifti.isNIFTI1(data) || nifti.isNIFTI2(data));
6511
};
6512
6513
6514
6515
/**
6516
 * Returns true if this data is GZIP compressed.
6517
 * @param {ArrayBuffer} data
6518
 * @returns {boolean}
6519
 */
6520
nifti.isCompressed = function (data) {
6521
    var buf, magicCookie1, magicCookie2;
6522
6523
    if (data) {
6524
        buf = new DataView(data);
6525
6526
        magicCookie1 = buf.getUint8(0);
6527
        magicCookie2 = buf.getUint8(1);
6528
6529
        if (magicCookie1 === nifti.Utils.GUNZIP_MAGIC_COOKIE1) {
6530
            return true;
6531
        }
6532
6533
        if (magicCookie2 === nifti.Utils.GUNZIP_MAGIC_COOKIE2) {
6534
            return true;
6535
        }
6536
    }
6537
6538
    return false;
6539
};
6540
6541
6542
6543
/**
6544
 * Returns decompressed data.
6545
 * @param {ArrayBuffer} data
6546
 * @returns {ArrayBuffer}
6547
 */
6548
nifti.decompress = function (data) {
6549
    return pako.inflate(data).buffer;
6550
};
6551
6552
6553
6554
/**
6555
 * Reads and returns the header object.
6556
 * @param {ArrayBuffer} data
6557
 * @returns {nifti.NIFTI1|nifti.NIFTI2|null}
6558
 */
6559
nifti.readHeader = function (data) {
6560
    var header = null;
6561
6562
    if (nifti.isCompressed(data)) {
6563
        data = nifti.decompress(data);
6564
    }
6565
6566
    if (nifti.isNIFTI1(data)) {
6567
        header = new nifti.NIFTI1();
6568
    } else if (nifti.isNIFTI2(data)) {
6569
        header = new nifti.NIFTI2();
6570
    }
6571
6572
    if (header) {
6573
        header.readHeader(data);
6574
    } else {
6575
        console.error("That file does not appear to be NIFTI!");
6576
    }
6577
6578
    return header;
6579
};
6580
6581
6582
6583
/**
6584
 * Returns true if this header contains an extension.
6585
 * @param {nifti.NIFTI1|nifti.NIFTI2} header
6586
 * @returns {boolean}
6587
 */
6588
nifti.hasExtension = function (header) {
6589
    return (header.extensionFlag[0] != 0);
6590
};
6591
6592
6593
6594
/**
6595
 * Returns the image data.
6596
 * @param {nifti.NIFTI1|nifti.NIFTI2} header
6597
 * @param {ArrayBuffer} data
6598
 * @returns {ArrayBuffer}
6599
 */
6600
nifti.readImage = function (header, data) {
6601
    var imageOffset = header.vox_offset,
6602
        timeDim = 1,
6603
        statDim = 1;
6604
6605
    if (header.dims[4]) {
6606
        timeDim = header.dims[4];
6607
    }
6608
6609
    if (header.dims[5]) {
6610
        statDim = header.dims[5];
6611
    }
6612
6613
    var imageSize = header.dims[1] * header.dims[2] * header.dims[3] * timeDim * statDim * (header.numBitsPerVoxel / 8);
6614
    return data.slice(imageOffset, imageOffset + imageSize);
6615
};
6616
6617
6618
6619
/**
6620
 * Returns the extension data (including extension header).
6621
 * @param {nifti.NIFTI1|nifti.NIFTI2} header
6622
 * @param {ArrayBuffer} data
6623
 * @returns {ArrayBuffer}
6624
 */
6625
nifti.readExtension = function (header, data) {
6626
    var loc = header.getExtensionLocation(),
6627
        size = header.extensionSize;
6628
6629
    return data.slice(loc, loc + size);
6630
};
6631
6632
6633
6634
/**
6635
 * Returns the extension data.
6636
 * @param {nifti.NIFTI1|nifti.NIFTI2} header
6637
 * @param {ArrayBuffer} data
6638
 * @returns {ArrayBuffer}
6639
 */
6640
nifti.readExtensionData = function (header, data) {
6641
    var loc = header.getExtensionLocation(),
6642
        size = header.extensionSize;
6643
6644
    return data.slice(loc + 8, loc + size - 8);
6645
};
6646
6647
6648
/*** Exports ***/
6649
6650
var moduleType = typeof module;
6651
if ((moduleType !== 'undefined') && module.exports) {
6652
    module.exports = nifti;
6653
}
6654
6655
},{"./nifti1.js":18,"./nifti2.js":19,"./utilities.js":20,"pako":1}],18:[function(require,module,exports){
6656
6657
/*jslint browser: true, node: true */
6658
/*global */
6659
6660
"use strict";
6661
6662
/*** Imports ***/
6663
6664
var nifti = nifti || {};
6665
nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
6666
6667
6668
6669
/*** Constructor ***/
6670
6671
/**
6672
 * The NIFTI1 constructor.
6673
 * @constructor
6674
 * @property {boolean} littleEndian
6675
 * @property {number} dim_info
6676
 * @property {number[]} dims - image dimensions
6677
 * @property {number} intent_p1
6678
 * @property {number} intent_p2
6679
 * @property {number} intent_p3
6680
 * @property {number} intent_code
6681
 * @property {number} datatypeCode
6682
 * @property {number} numBitsPerVoxel
6683
 * @property {number} slice_start
6684
 * @property {number} slice_end
6685
 * @property {number} slice_code
6686
 * @property {number[]} pixDims - voxel dimensions
6687
 * @property {number} vox_offset
6688
 * @property {number} scl_slope
6689
 * @property {number} scl_inter
6690
 * @property {number} xyzt_units
6691
 * @property {number} cal_max
6692
 * @property {number} cal_min
6693
 * @property {number} slice_duration
6694
 * @property {number} toffset
6695
 * @property {string} description
6696
 * @property {string} aux_file
6697
 * @property {string} intent_name
6698
 * @property {number} qform_code
6699
 * @property {number} sform_code
6700
 * @property {number} quatern_b
6701
 * @property {number} quatern_c
6702
 * @property {number} quatern_d
6703
 * @property {number} quatern_x
6704
 * @property {number} quatern_y
6705
 * @property {number} quatern_z
6706
 * @property {Array.<Array.<number>>} affine
6707
 * @property {string} magic
6708
 * @property {boolean} isHDR - if hdr/img format
6709
 * @property {number[]} extensionFlag
6710
 * @property {number} extensionSize
6711
 * @property {number} extensionCode
6712
 * @type {Function}
6713
 */
6714
nifti.NIFTI1 = nifti.NIFTI1 || function () {
6715
    this.littleEndian = false;
6716
    this.dim_info = 0;
6717
    this.dims = [];
6718
    this.intent_p1 = 0;
6719
    this.intent_p2 = 0;
6720
    this.intent_p3 = 0;
6721
    this.intent_code = 0;
6722
    this.datatypeCode = 0;
6723
    this.numBitsPerVoxel = 0;
6724
    this.slice_start = 0;
6725
    this.slice_end = 0;
6726
    this.slice_code = 0;
6727
    this.pixDims = [];
6728
    this.vox_offset = 0;
6729
    this.scl_slope = 1;
6730
    this.scl_inter = 0;
6731
    this.xyzt_units = 0;
6732
    this.cal_max = 0;
6733
    this.cal_min = 0;
6734
    this.slice_duration = 0;
6735
    this.toffset = 0;
6736
    this.description = "";
6737
    this.aux_file = "";
6738
    this.intent_name = "";
6739
    this.qform_code = 0;
6740
    this.sform_code = 0;
6741
    this.quatern_b = 0;
6742
    this.quatern_c = 0;
6743
    this.quatern_d = 0;
6744
    this.qoffset_x = 0;
6745
    this.qoffset_y = 0;
6746
    this.qoffset_z = 0;
6747
    this.affine = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
6748
    this.magic = 0;
6749
    this.isHDR = false;
6750
    this.extensionFlag = [0, 0, 0, 0];
6751
    this.extensionSize = 0;
6752
    this.extensionCode = 0;
6753
};
6754
6755
6756
6757
/*** Static Pseudo-constants ***/
6758
6759
// datatype codes
6760
nifti.NIFTI1.TYPE_NONE            = 0;
6761
nifti.NIFTI1.TYPE_BINARY          = 1;
6762
nifti.NIFTI1.TYPE_UINT8           = 2;
6763
nifti.NIFTI1.TYPE_INT16           = 4;
6764
nifti.NIFTI1.TYPE_INT32           = 8;
6765
nifti.NIFTI1.TYPE_FLOAT32        = 16;
6766
nifti.NIFTI1.TYPE_COMPLEX64      = 32;
6767
nifti.NIFTI1.TYPE_FLOAT64        = 64;
6768
nifti.NIFTI1.TYPE_RGB24         = 128;
6769
nifti.NIFTI1.TYPE_INT8          = 256;
6770
nifti.NIFTI1.TYPE_UINT16        = 512;
6771
nifti.NIFTI1.TYPE_UINT32        = 768;
6772
nifti.NIFTI1.TYPE_INT64        = 1024;
6773
nifti.NIFTI1.TYPE_UINT64       = 1280;
6774
nifti.NIFTI1.TYPE_FLOAT128     = 1536;
6775
nifti.NIFTI1.TYPE_COMPLEX128   = 1792;
6776
nifti.NIFTI1.TYPE_COMPLEX256   = 2048;
6777
6778
// transform codes
6779
nifti.NIFTI1.XFORM_UNKNOWN        = 0;
6780
nifti.NIFTI1.XFORM_SCANNER_ANAT   = 1;
6781
nifti.NIFTI1.XFORM_ALIGNED_ANAT   = 2;
6782
nifti.NIFTI1.XFORM_TALAIRACH      = 3;
6783
nifti.NIFTI1.XFORM_MNI_152        = 4;
6784
6785
// unit codes
6786
nifti.NIFTI1.SPATIAL_UNITS_MASK = 0x07;
6787
nifti.NIFTI1.TEMPORAL_UNITS_MASK = 0x38;
6788
nifti.NIFTI1.UNITS_UNKNOWN        = 0;
6789
nifti.NIFTI1.UNITS_METER          = 1;
6790
nifti.NIFTI1.UNITS_MM             = 2;
6791
nifti.NIFTI1.UNITS_MICRON         = 3;
6792
nifti.NIFTI1.UNITS_SEC            = 8;
6793
nifti.NIFTI1.UNITS_MSEC          = 16;
6794
nifti.NIFTI1.UNITS_USEC          = 24;
6795
nifti.NIFTI1.UNITS_HZ            = 32;
6796
nifti.NIFTI1.UNITS_PPM           = 40;
6797
nifti.NIFTI1.UNITS_RADS          = 48;
6798
6799
// nifti1 codes
6800
nifti.NIFTI1.MAGIC_COOKIE = 348;
6801
nifti.NIFTI1.STANDARD_HEADER_SIZE = 348;
6802
nifti.NIFTI1.MAGIC_NUMBER_LOCATION = 344;
6803
nifti.NIFTI1.MAGIC_NUMBER = [0x6E, 0x2B, 0x31];  // n+1 (.nii)
6804
nifti.NIFTI1.MAGIC_NUMBER2 = [0x6E, 0x69, 0x31];  // ni1 (.hdr/.img)
6805
nifti.NIFTI1.EXTENSION_HEADER_SIZE = 8;
6806
6807
6808
/*** Prototype Methods ***/
6809
6810
/**
6811
 * Reads the header data.
6812
 * @param {ArrayBuffer} data
6813
 */
6814
nifti.NIFTI1.prototype.readHeader = function (data) {
6815
    var rawData = new DataView(data),
6816
        magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian),
6817
        ctr,
6818
        ctrOut,
6819
        ctrIn,
6820
        index;
6821
6822
    if (magicCookieVal !== nifti.NIFTI1.MAGIC_COOKIE) {  // try as little endian
6823
        this.littleEndian = true;
6824
        magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian);
6825
    }
6826
6827
    if (magicCookieVal !== nifti.NIFTI1.MAGIC_COOKIE) {
6828
        throw new Error("This does not appear to be a NIFTI file!");
6829
    }
6830
6831
    this.dim_info = nifti.Utils.getByteAt(rawData, 39);
6832
6833
    for (ctr = 0; ctr < 8; ctr += 1) {
6834
        index = 40 + (ctr * 2);
6835
        this.dims[ctr] = nifti.Utils.getShortAt(rawData, index, this.littleEndian);
6836
    }
6837
6838
    this.intent_p1 = nifti.Utils.getFloatAt(rawData, 56, this.littleEndian);
6839
    this.intent_p2 = nifti.Utils.getFloatAt(rawData, 60, this.littleEndian);
6840
    this.intent_p3 = nifti.Utils.getFloatAt(rawData, 64, this.littleEndian);
6841
    this.intent_code = nifti.Utils.getShortAt(rawData, 68, this.littleEndian);
6842
6843
    this.datatypeCode = nifti.Utils.getShortAt(rawData, 70, this.littleEndian);
6844
    this.numBitsPerVoxel = nifti.Utils.getShortAt(rawData, 72, this.littleEndian);
6845
6846
    this.slice_start = nifti.Utils.getShortAt(rawData, 74, this.littleEndian);
6847
6848
    for (ctr = 0; ctr < 8; ctr += 1) {
6849
        index = 76 + (ctr * 4);
6850
        this.pixDims[ctr] = nifti.Utils.getFloatAt(rawData, index, this.littleEndian);
6851
    }
6852
6853
    this.vox_offset = nifti.Utils.getFloatAt(rawData, 108, this.littleEndian);
6854
6855
    this.scl_slope = nifti.Utils.getFloatAt(rawData, 112, this.littleEndian);
6856
    this.scl_inter = nifti.Utils.getFloatAt(rawData, 116, this.littleEndian);
6857
6858
    this.slice_end = nifti.Utils.getShortAt(rawData, 120, this.littleEndian);
6859
    this.slice_code = nifti.Utils.getByteAt(rawData, 122);
6860
6861
    this.xyzt_units = nifti.Utils.getByteAt(rawData, 123);
6862
6863
    this.cal_max = nifti.Utils.getFloatAt(rawData, 124, this.littleEndian);
6864
    this.cal_min = nifti.Utils.getFloatAt(rawData, 128, this.littleEndian);
6865
6866
    this.slice_duration = nifti.Utils.getFloatAt(rawData, 132, this.littleEndian);
6867
    this.toffset = nifti.Utils.getFloatAt(rawData, 136, this.littleEndian);
6868
6869
    this.description = nifti.Utils.getStringAt(rawData, 148, 228);
6870
    this.aux_file = nifti.Utils.getStringAt(rawData, 228, 252);
6871
6872
    this.qform_code = nifti.Utils.getShortAt(rawData, 252, this.littleEndian);
6873
    this.sform_code = nifti.Utils.getShortAt(rawData, 254, this.littleEndian);
6874
6875
    this.quatern_b = nifti.Utils.getFloatAt(rawData, 256, this.littleEndian);
6876
    this.quatern_c = nifti.Utils.getFloatAt(rawData, 260, this.littleEndian);
6877
    this.quatern_d = nifti.Utils.getFloatAt(rawData, 264, this.littleEndian);
6878
    this.qoffset_x = nifti.Utils.getFloatAt(rawData, 268, this.littleEndian);
6879
    this.qoffset_y = nifti.Utils.getFloatAt(rawData, 272, this.littleEndian);
6880
    this.qoffset_z = nifti.Utils.getFloatAt(rawData, 276, this.littleEndian);
6881
6882
    for (ctrOut = 0; ctrOut < 3; ctrOut += 1) {
6883
        for (ctrIn = 0; ctrIn < 4; ctrIn += 1) {
6884
            index = 280 + (((ctrOut * 4) + ctrIn) * 4);
6885
            this.affine[ctrOut][ctrIn] = nifti.Utils.getFloatAt(rawData, index, this.littleEndian);
6886
        }
6887
    }
6888
6889
    this.affine[3][0] = 0;
6890
    this.affine[3][1] = 0;
6891
    this.affine[3][2] = 0;
6892
    this.affine[3][3] = 1;
6893
6894
    this.intent_name = nifti.Utils.getStringAt(rawData, 328, 344);
6895
    this.magic = nifti.Utils.getStringAt(rawData, 344, 348);
6896
6897
    this.isHDR = (this.magic === nifti.NIFTI1.MAGIC_NUMBER2);
6898
6899
    if (rawData.byteLength > nifti.NIFTI1.MAGIC_COOKIE) {
6900
        this.extensionFlag[0] = nifti.Utils.getByteAt(rawData, 348);
6901
        this.extensionFlag[1] = nifti.Utils.getByteAt(rawData, 348 + 1);
6902
        this.extensionFlag[2] = nifti.Utils.getByteAt(rawData, 348 + 2);
6903
        this.extensionFlag[3] = nifti.Utils.getByteAt(rawData, 348 + 3);
6904
6905
        if (this.extensionFlag[0]) {
6906
            this.extensionSize = this.getExtensionSize(rawData);
6907
            this.extensionCode = this.getExtensionCode(rawData);
6908
        }
6909
    }
6910
};
6911
6912
6913
/**
6914
 * Returns a formatted string of header fields.
6915
 * @returns {string}
6916
 */
6917
nifti.NIFTI1.prototype.toFormattedString = function () {
6918
    var fmt = nifti.Utils.formatNumber,
6919
        string = "";
6920
6921
    string += ("Dim Info = " + this.dim_info + "\n");
6922
6923
    string += ("Image Dimensions (1-8): " +
6924
        this.dims[0] + ", " +
6925
        this.dims[1] + ", " +
6926
        this.dims[2] + ", " +
6927
        this.dims[3] + ", " +
6928
        this.dims[4] + ", " +
6929
        this.dims[5] + ", " +
6930
        this.dims[6] + ", " +
6931
        this.dims[7] + "\n");
6932
6933
    string += ("Intent Parameters (1-3): " +
6934
        this.intent_p1 + ", " +
6935
        this.intent_p2 + ", " +
6936
        this.intent_p3) + "\n";
6937
6938
    string += ("Intent Code = " + this.intent_code + "\n");
6939
    string += ("Datatype = " + this.datatypeCode +  " (" + this.getDatatypeCodeString(this.datatypeCode) + ")\n");
6940
    string += ("Bits Per Voxel = " + this.numBitsPerVoxel + "\n");
6941
    string += ("Slice Start = " + this.slice_start + "\n");
6942
    string += ("Voxel Dimensions (1-8): " +
6943
        fmt(this.pixDims[0]) + ", " +
6944
        fmt(this.pixDims[1]) + ", " +
6945
        fmt(this.pixDims[2]) + ", " +
6946
        fmt(this.pixDims[3]) + ", " +
6947
        fmt(this.pixDims[4]) + ", " +
6948
        fmt(this.pixDims[5]) + ", " +
6949
        fmt(this.pixDims[6]) + ", " +
6950
        fmt(this.pixDims[7]) + "\n");
6951
6952
    string += ("Image Offset = " + this.vox_offset + "\n");
6953
    string += ("Data Scale:  Slope = " + fmt(this.scl_slope) + "  Intercept = " + fmt(this.scl_inter) + "\n");
6954
    string += ("Slice End = " + this.slice_end + "\n");
6955
    string += ("Slice Code = " + this.slice_code + "\n");
6956
    string += ("Units Code = " + this.xyzt_units + " (" + this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.xyzt_units) + ", " + this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.xyzt_units) + ")\n");
6957
    string += ("Display Range:  Max = " + fmt(this.cal_max) + "  Min = " + fmt(this.cal_min) + "\n");
6958
    string += ("Slice Duration = " + this.slice_duration + "\n");
6959
    string += ("Time Axis Shift = " + this.toffset + "\n");
6960
    string += ("Description: \"" + this.description + "\"\n");
6961
    string += ("Auxiliary File: \"" + this.aux_file + "\"\n");
6962
    string += ("Q-Form Code = " + this.qform_code + " (" + this.getTransformCodeString(this.qform_code) + ")\n");
6963
    string += ("S-Form Code = " + this.sform_code + " (" + this.getTransformCodeString(this.sform_code) + ")\n");
6964
    string += ("Quaternion Parameters:  " +
6965
        "b = " + fmt(this.quatern_b) + "  " +
6966
        "c = " + fmt(this.quatern_c) + "  " +
6967
        "d = " + fmt(this.quatern_d) + "\n");
6968
6969
    string += ("Quaternion Offsets:  " +
6970
        "x = " + this.qoffset_x + "  " +
6971
        "y = " + this.qoffset_y + "  " +
6972
        "z = " + this.qoffset_z + "\n");
6973
6974
    string += ("S-Form Parameters X: " +
6975
        fmt(this.affine[0][0]) + ", " +
6976
        fmt(this.affine[0][1]) + ", " +
6977
        fmt(this.affine[0][2]) + ", " +
6978
        fmt(this.affine[0][3]) + "\n");
6979
6980
    string += ("S-Form Parameters Y: " +
6981
        fmt(this.affine[1][0]) + ", " +
6982
        fmt(this.affine[1][1]) + ", " +
6983
        fmt(this.affine[1][2]) + ", " +
6984
        fmt(this.affine[1][3]) + "\n");
6985
6986
    string += ("S-Form Parameters Z: " +
6987
        fmt(this.affine[2][0]) + ", " +
6988
        fmt(this.affine[2][1]) + ", " +
6989
        fmt(this.affine[2][2]) + ", " +
6990
        fmt(this.affine[2][3]) + "\n");
6991
6992
    string += ("Intent Name: \"" + this.intent_name + "\"\n");
6993
6994
    if (this.extensionFlag[0]) {
6995
        string += ("Extension: Size = " + this.extensionSize + "  Code = " + this.extensionCode + "\n");
6996
6997
    }
6998
6999
    return string;
7000
};
7001
7002
7003
/**
7004
 * Returns a human-readable string of datatype.
7005
 * @param {number} code
7006
 * @returns {string}
7007
 */
7008
nifti.NIFTI1.prototype.getDatatypeCodeString = function (code) {
7009
    if (code === nifti.NIFTI1.TYPE_UINT8) {
7010
        return "1-Byte Unsigned Integer";
7011
    } else if (code === nifti.NIFTI1.TYPE_INT16) {
7012
        return "2-Byte Signed Integer";
7013
    } else if (code === nifti.NIFTI1.TYPE_INT32) {
7014
        return "4-Byte Signed Integer";
7015
    } else if (code === nifti.NIFTI1.TYPE_FLOAT32) {
7016
        return "4-Byte Float";
7017
    } else if (code === nifti.NIFTI1.TYPE_FLOAT64) {
7018
        return "8-Byte Float";
7019
    } else if (code === nifti.NIFTI1.TYPE_RGB24) {
7020
        return "RGB";
7021
    } else if (code === nifti.NIFTI1.TYPE_INT8) {
7022
        return "1-Byte Signed Integer";
7023
    } else if (code === nifti.NIFTI1.TYPE_UINT16) {
7024
        return "2-Byte Unsigned Integer";
7025
    } else if (code === nifti.NIFTI1.TYPE_UINT32) {
7026
        return "4-Byte Unsigned Integer";
7027
    } else if (code === nifti.NIFTI1.TYPE_INT64) {
7028
        return "8-Byte Signed Integer";
7029
    } else if (code === nifti.NIFTI1.TYPE_UINT64) {
7030
        return "8-Byte Unsigned Integer";
7031
    } else {
7032
        return "Unknown";
7033
    }
7034
};
7035
7036
7037
/**
7038
 * Returns a human-readable string of transform type.
7039
 * @param {number} code
7040
 * @returns {string}
7041
 */
7042
nifti.NIFTI1.prototype.getTransformCodeString = function (code) {
7043
    if (code === nifti.NIFTI1.XFORM_SCANNER_ANAT) {
7044
        return "Scanner";
7045
    } else if (code === nifti.NIFTI1.XFORM_ALIGNED_ANAT) {
7046
        return "Aligned";
7047
    } else if (code === nifti.NIFTI1.XFORM_TALAIRACH) {
7048
        return "Talairach";
7049
    } else if (code === nifti.NIFTI1.XFORM_MNI_152) {
7050
        return "MNI";
7051
    } else {
7052
        return "Unknown";
7053
    }
7054
};
7055
7056
7057
/**
7058
 * Returns a human-readable string of spatial and temporal units.
7059
 * @param {number} code
7060
 * @returns {string}
7061
 */
7062
nifti.NIFTI1.prototype.getUnitsCodeString = function (code) {
7063
    if (code === nifti.NIFTI1.UNITS_METER) {
7064
        return "Meters";
7065
    } else if (code === nifti.NIFTI1.UNITS_MM) {
7066
        return "Millimeters";
7067
    } else if (code === nifti.NIFTI1.UNITS_MICRON) {
7068
        return "Microns";
7069
    } else if (code === nifti.NIFTI1.UNITS_SEC) {
7070
        return "Seconds";
7071
    } else if (code === nifti.NIFTI1.UNITS_MSEC) {
7072
        return "Milliseconds";
7073
    } else if (code === nifti.NIFTI1.UNITS_USEC) {
7074
        return "Microseconds";
7075
    } else if (code === nifti.NIFTI1.UNITS_HZ) {
7076
        return "Hz";
7077
    } else if (code === nifti.NIFTI1.UNITS_PPM) {
7078
        return "PPM";
7079
    } else if (code === nifti.NIFTI1.UNITS_RADS) {
7080
        return "Rads";
7081
    } else {
7082
        return "Unknown";
7083
    }
7084
};
7085
7086
7087
/**
7088
 * Returns the qform matrix.
7089
 * @returns {Array.<Array.<number>>}
7090
 */
7091
nifti.NIFTI1.prototype.getQformMat = function () {
7092
    return this.convertNiftiQFormToNiftiSForm(this.quatern_b, this.quatern_c, this.quatern_d, this.qoffset_x,
7093
        this.qoffset_y, this.qoffset_z, this.pixDims[1], this.pixDims[2], this.pixDims[3], this.pixDims[0]);
7094
};
7095
7096
7097
7098
/**
7099
 * Converts qform to an affine.  (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
7100
 * @param {number} qb
7101
 * @param {number} qc
7102
 * @param {number} qd
7103
 * @param {number} qx
7104
 * @param {number} qy
7105
 * @param {number} qz
7106
 * @param {number} dx
7107
 * @param {number} dy
7108
 * @param {number} dz
7109
 * @param {number} qfac
7110
 * @returns {Array.<Array.<number>>}
7111
 */
7112
nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm = function (qb, qc, qd, qx, qy, qz, dx, dy, dz,
7113
                                                qfac) {
7114
    var R = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
7115
        a,
7116
        b = qb,
7117
        c = qc,
7118
        d = qd,
7119
        xd,
7120
        yd,
7121
        zd;
7122
7123
    // last row is always [ 0 0 0 1 ]
7124
    R[3][0] = R[3][1] = R[3][2] = 0.0;
7125
    R[3][3] = 1.0;
7126
7127
    // compute a parameter from b,c,d
7128
    a = 1.0 - (b * b + c * c + d * d);
7129
    if (a < 0.0000001) {                   /* special case */
7130
7131
        a = 1.0 / Math.sqrt(b * b + c * c + d * d);
7132
        b *= a;
7133
        c *= a;
7134
        d *= a;        /* normalize (b,c,d) vector */
7135
        a = 0.0;                        /* a = 0 ==> 180 degree rotation */
7136
    } else {
7137
7138
        a = Math.sqrt(a);                     /* angle = 2*arccos(a) */
7139
    }
7140
7141
    // load rotation matrix, including scaling factors for voxel sizes
7142
    xd = (dx > 0.0) ? dx : 1.0;       /* make sure are positive */
7143
    yd = (dy > 0.0) ? dy : 1.0;
7144
    zd = (dz > 0.0) ? dz : 1.0;
7145
7146
    if (qfac < 0.0) {
7147
        zd = -zd;         /* left handedness? */
7148
    }
7149
7150
    R[0][0] =       (a * a + b * b - c * c - d * d) * xd;
7151
    R[0][1] = 2.0 * (b * c - a * d) * yd;
7152
    R[0][2] = 2.0 * (b * d + a * c) * zd;
7153
    R[1][0] = 2.0 * (b * c + a * d) * xd;
7154
    R[1][1] =       (a * a + c * c - b * b - d * d) * yd;
7155
    R[1][2] = 2.0 * (c * d - a * b) * zd;
7156
    R[2][0] = 2.0 * (b * d - a * c) * xd;
7157
    R[2][1] = 2.0 * (c * d + a * b) * yd;
7158
    R[2][2] =       (a * a + d * d - c * c - b * b) * zd;
7159
7160
    // load offsets
7161
    R[0][3] = qx;
7162
    R[1][3] = qy;
7163
    R[2][3] = qz;
7164
7165
    return R;
7166
};
7167
7168
7169
7170
/**
7171
 * Converts sform to an orientation string (e.g., XYZ+--).  (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
7172
 * @param {Array.<Array.<number>>} R
7173
 * @returns {string}
7174
 */
7175
nifti.NIFTI1.prototype.convertNiftiSFormToNEMA = function (R) {
7176
    var xi, xj, xk, yi, yj, yk, zi, zj, zk, val, detQ, detP, i, j, k, p, q, r, ibest, jbest, kbest, pbest, qbest, rbest,
7177
        M, vbest, Q, P, iChar, jChar, kChar, iSense, jSense, kSense;
7178
    k = 0;
7179
7180
    Q = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
7181
    P = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
7182
7183
    //if( icod == NULL || jcod == NULL || kcod == NULL ) return ; /* bad */
7184
7185
    //*icod = *jcod = *kcod = 0 ; /* this.errorMessage returns, if sh*t happens */
7186
7187
    /* load column vectors for each (i,j,k) direction from matrix */
7188
7189
    /*-- i axis --*/ /*-- j axis --*/ /*-- k axis --*/
7190
7191
    xi = R[0][0];
7192
    xj = R[0][1];
7193
    xk = R[0][2];
7194
7195
    yi = R[1][0];
7196
    yj = R[1][1];
7197
    yk = R[1][2];
7198
7199
    zi = R[2][0];
7200
    zj = R[2][1];
7201
    zk = R[2][2];
7202
7203
    /* normalize column vectors to get unit vectors along each ijk-axis */
7204
7205
    /* normalize i axis */
7206
    val = Math.sqrt(xi * xi + yi * yi + zi * zi);
7207
    if (val === 0.0) {  /* stupid input */
7208
        return null;
7209
    }
7210
7211
    xi /= val;
7212
    yi /= val;
7213
    zi /= val;
7214
7215
    /* normalize j axis */
7216
    val = Math.sqrt(xj * xj + yj * yj + zj * zj);
7217
    if (val === 0.0) {  /* stupid input */
7218
        return null;
7219
    }
7220
7221
    xj /= val;
7222
    yj /= val;
7223
    zj /= val;
7224
7225
    /* orthogonalize j axis to i axis, if needed */
7226
    val = xi * xj + yi * yj + zi * zj;    /* dot product between i and j */
7227
    if (Math.abs(val) > 1.E-4) {
7228
        xj -= val * xi;
7229
        yj -= val * yi;
7230
        zj -= val * zi;
7231
        val = Math.sqrt(xj * xj + yj * yj + zj * zj);  /* must renormalize */
7232
        if (val === 0.0) {              /* j was parallel to i? */
7233
            return null;
7234
        }
7235
        xj /= val;
7236
        yj /= val;
7237
        zj /= val;
7238
    }
7239
7240
    /* normalize k axis; if it is zero, make it the cross product i x j */
7241
    val = Math.sqrt(xk * xk + yk * yk + zk * zk);
7242
    if (val === 0.0) {
7243
        xk = yi * zj - zi * yj;
7244
        yk = zi * xj - zj * xi;
7245
        zk = xi * yj - yi * xj;
7246
    } else {
7247
        xk /= val;
7248
        yk /= val;
7249
        zk /= val;
7250
    }
7251
7252
    /* orthogonalize k to i */
7253
    val = xi * xk + yi * yk + zi * zk;    /* dot product between i and k */
7254
    if (Math.abs(val) > 1.E-4) {
7255
        xk -= val * xi;
7256
        yk -= val * yi;
7257
        zk -= val * zi;
7258
        val = Math.sqrt(xk * xk + yk * yk + zk * zk);
7259
        if (val === 0.0) {    /* bad */
7260
            return null;
7261
        }
7262
        xk /= val;
7263
        yk /= val;
7264
        zk /= val;
7265
    }
7266
7267
    /* orthogonalize k to j */
7268
    val = xj * xk + yj * yk + zj * zk;    /* dot product between j and k */
7269
    if (Math.abs(val) > 1.e-4) {
7270
        xk -= val * xj;
7271
        yk -= val * yj;
7272
        zk -= val * zj;
7273
        val = Math.sqrt(xk * xk + yk * yk + zk * zk);
7274
        if (val === 0.0) {     /* bad */
7275
            return null;
7276
        }
7277
        xk /= val;
7278
        yk /= val;
7279
        zk /= val;
7280
    }
7281
7282
    Q[0][0] = xi;
7283
    Q[0][1] = xj;
7284
    Q[0][2] = xk;
7285
    Q[1][0] = yi;
7286
    Q[1][1] = yj;
7287
    Q[1][2] = yk;
7288
    Q[2][0] = zi;
7289
    Q[2][1] = zj;
7290
    Q[2][2] = zk;
7291
7292
    /* at this point, Q is the rotation matrix from the (i,j,k) to (x,y,z) axes */
7293
7294
    detQ = this.nifti_mat33_determ(Q);
7295
    if (detQ === 0.0) { /* shouldn't happen unless user is a DUFIS */
7296
        return null;
7297
    }
7298
7299
    /* Build and test all possible +1/-1 coordinate permutation matrices P;
7300
     then find the P such that the rotation matrix M=PQ is closest to the
7301
     identity, in the sense of M having the smallest total rotation angle. */
7302
7303
    /* Despite the formidable looking 6 nested loops, there are
7304
     only 3*3*3*2*2*2 = 216 passes, which will run very quickly. */
7305
7306
    vbest = -666.0;
7307
    ibest = pbest = qbest = rbest = 1;
7308
    jbest = 2;
7309
    kbest = 3;
7310
7311
    for (i = 1; i <= 3; i += 1) {     /* i = column number to use for row #1 */
7312
        for (j = 1; j <= 3; j += 1) {    /* j = column number to use for row #2 */
7313
            if (i !== j) {
7314
                for (k = 1; k <= 3; k += 1) {  /* k = column number to use for row #3 */
7315
                    if (!(i === k || j === k)) {
7316
                        P[0][0] = P[0][1] = P[0][2] = P[1][0] = P[1][1] = P[1][2] = P[2][0] = P[2][1] = P[2][2] = 0.0;
7317
                        for (p = -1; p <= 1; p += 2) {    /* p,q,r are -1 or +1      */
7318
                            for (q = -1; q <= 1; q += 2) {   /* and go into rows #1,2,3 */
7319
                                for (r = -1; r <= 1; r += 2) {
7320
                                    P[0][i - 1] = p;
7321
                                    P[1][j - 1] = q;
7322
                                    P[2][k - 1] = r;
7323
                                    detP = this.nifti_mat33_determ(P);           /* sign of permutation */
7324
                                    if ((detP * detQ) > 0.0) {
7325
                                        M = this.nifti_mat33_mul(P, Q);
7326
7327
                                        /* angle of M rotation = 2.0*acos(0.5*sqrt(1.0+trace(M)))       */
7328
                                        /* we want largest trace(M) == smallest angle == M nearest to I */
7329
7330
                                        val = M[0][0] + M[1][1] + M[2][2]; /* trace */
7331
                                        if (val > vbest) {
7332
                                            vbest = val;
7333
                                            ibest = i;
7334
                                            jbest = j;
7335
                                            kbest = k;
7336
                                            pbest = p;
7337
                                            qbest = q;
7338
                                            rbest = r;
7339
                                        }
7340
                                    }  /* doesn't match sign of Q */
7341
                                }
7342
                            }
7343
                        }
7344
                    }
7345
                }
7346
            }
7347
        }
7348
    }
7349
7350
    /* At this point ibest is 1 or 2 or 3; pbest is -1 or +1; etc.
7351
7352
     The matrix P that corresponds is the best permutation approximation
7353
     to Q-inverse; that is, P (approximately) takes (x,y,z) coordinates
7354
     to the (i,j,k) axes.
7355
7356
     For example, the first row of P (which contains pbest in column ibest)
7357
     determines the way the i axis points relative to the anatomical
7358
     (x,y,z) axes.  If ibest is 2, then the i axis is along the y axis,
7359
     which is direction P2A (if pbest > 0) or A2P (if pbest < 0).
7360
7361
     So, using ibest and pbest, we can assign the output code for
7362
     the i axis.  Mutatis mutandis for the j and k axes, of course. */
7363
7364
    iChar = jChar = kChar = iSense = jSense = kSense = 0;
7365
7366
    switch (ibest * pbest) {
7367
        case 1: /*i = NIFTI_L2R*/
7368
            iChar = 'X';
7369
            iSense = '+';
7370
            break;
7371
        case -1: /*i = NIFTI_R2L*/
7372
            iChar = 'X';
7373
            iSense = '-';
7374
            break;
7375
        case 2: /*i = NIFTI_P2A*/
7376
            iChar = 'Y';
7377
            iSense = '+';
7378
            break;
7379
        case -2: /*i = NIFTI_A2P*/
7380
            iChar = 'Y';
7381
            iSense = '-';
7382
            break;
7383
        case 3: /*i = NIFTI_I2S*/
7384
            iChar = 'Z';
7385
            iSense = '+';
7386
            break;
7387
        case -3: /*i = NIFTI_S2I*/
7388
            iChar = 'Z';
7389
            iSense = '-';
7390
            break;
7391
    }
7392
7393
    switch (jbest * qbest) {
7394
        case 1: /*j = NIFTI_L2R*/
7395
            jChar = 'X';
7396
            jSense = '+';
7397
            break;
7398
        case -1: /*j = NIFTI_R2L*/
7399
            jChar = 'X';
7400
            jSense = '-';
7401
            break;
7402
        case 2: /*j = NIFTI_P2A*/
7403
            jChar = 'Y';
7404
            jSense = '+';
7405
            break;
7406
        case -2: /*j = NIFTI_A2P*/
7407
            jChar = 'Y';
7408
            jSense = '-';
7409
            break;
7410
        case 3: /*j = NIFTI_I2S*/
7411
            jChar = 'Z';
7412
            jSense = '+';
7413
            break;
7414
        case -3: /*j = NIFTI_S2I*/
7415
            jChar = 'Z';
7416
            jSense = '-';
7417
            break;
7418
    }
7419
7420
    switch (kbest * rbest) {
7421
        case 1: /*k = NIFTI_L2R*/
7422
            kChar = 'X';
7423
            kSense = '+';
7424
            break;
7425
        case -1: /*k = NIFTI_R2L*/
7426
            kChar = 'X';
7427
            kSense = '-';
7428
            break;
7429
        case 2: /*k = NIFTI_P2A*/
7430
            kChar = 'Y';
7431
            kSense = '+';
7432
            break;
7433
        case -2: /*k = NIFTI_A2P*/
7434
            kChar = 'Y';
7435
            kSense = '-';
7436
            break;
7437
        case 3: /*k = NIFTI_I2S*/
7438
            kChar = 'Z';
7439
            kSense = '+';
7440
            break;
7441
        case -3: /*k = NIFTI_S2I*/
7442
            kChar = 'Z';
7443
            kSense = '-';
7444
            break;
7445
    }
7446
7447
    return (iChar + jChar + kChar + iSense + jSense + kSense);
7448
};
7449
7450
7451
7452
nifti.NIFTI1.prototype.nifti_mat33_mul = function (A, B) {
7453
    var C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
7454
        i,
7455
        j;
7456
7457
    for (i = 0; i < 3; i += 1) {
7458
        for (j = 0; j < 3; j += 1) {
7459
            C[i][j] =  A[i][0] * B[0][j]  + A[i][1] * B[1][j] + A[i][2] * B[2][j];
7460
        }
7461
    }
7462
7463
    return C;
7464
};
7465
7466
7467
7468
nifti.NIFTI1.prototype.nifti_mat33_determ = function (R) {
7469
    var r11, r12, r13, r21, r22, r23, r31, r32, r33;
7470
    /*  INPUT MATRIX:  */
7471
    r11 = R[0][0];
7472
    r12 = R[0][1];
7473
    r13 = R[0][2];
7474
    r21 = R[1][0];
7475
    r22 = R[1][1];
7476
    r23 = R[1][2];
7477
    r31 = R[2][0];
7478
    r32 = R[2][1];
7479
    r33 = R[2][2];
7480
7481
    return (r11 * r22 * r33 - r11 * r32 * r23 - r21 * r12 * r33 + r21 * r32 * r13 + r31 * r12 * r23 - r31 * r22 * r13);
7482
};
7483
7484
7485
/**
7486
 * Returns the byte index of the extension.
7487
 * @returns {number}
7488
 */
7489
nifti.NIFTI1.prototype.getExtensionLocation = function() {
7490
    return nifti.NIFTI1.MAGIC_COOKIE + 4;
7491
};
7492
7493
7494
/**
7495
 * Returns the extension size.
7496
 * @param {DataView} data
7497
 * @returns {number}
7498
 */
7499
nifti.NIFTI1.prototype.getExtensionSize = function(data) {
7500
    return nifti.Utils.getIntAt(data, this.getExtensionLocation(), this.littleEndian);
7501
};
7502
7503
7504
7505
/**
7506
 * Returns the extension code.
7507
 * @param {DataView} data
7508
 * @returns {number}
7509
 */
7510
nifti.NIFTI1.prototype.getExtensionCode = function(data) {
7511
    return nifti.Utils.getIntAt(data, this.getExtensionLocation() + 4, this.littleEndian);
7512
};
7513
7514
7515
7516
/*** Exports ***/
7517
7518
var moduleType = typeof module;
7519
if ((moduleType !== 'undefined') && module.exports) {
7520
    module.exports = nifti.NIFTI1;
7521
}
7522
7523
},{"./utilities.js":20}],19:[function(require,module,exports){
7524
7525
/*jslint browser: true, node: true */
7526
/*global */
7527
7528
"use strict";
7529
7530
/*** Imports ***/
7531
7532
var nifti = nifti || {};
7533
nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
7534
nifti.NIFTI1 = nifti.NIFTI1 || ((typeof require !== 'undefined') ? require('./nifti1.js') : null);
7535
7536
7537
/*** Constructor ***/
7538
7539
/**
7540
 * The NIFTI2 constructor.
7541
 * @constructor
7542
 * @property {boolean} littleEndian
7543
 * @property {number} dim_info
7544
 * @property {number[]} dims - image dimensions
7545
 * @property {number} intent_p1
7546
 * @property {number} intent_p2
7547
 * @property {number} intent_p3
7548
 * @property {number} intent_code
7549
 * @property {number} datatypeCode
7550
 * @property {number} numBitsPerVoxel
7551
 * @property {number} slice_start
7552
 * @property {number} slice_end
7553
 * @property {number} slice_code
7554
 * @property {number[]} pixDims - voxel dimensions
7555
 * @property {number} vox_offset
7556
 * @property {number} scl_slope
7557
 * @property {number} scl_inter
7558
 * @property {number} xyzt_units
7559
 * @property {number} cal_max
7560
 * @property {number} cal_min
7561
 * @property {number} slice_duration
7562
 * @property {number} toffset
7563
 * @property {string} description
7564
 * @property {string} aux_file
7565
 * @property {string} intent_name
7566
 * @property {number} qform_code
7567
 * @property {number} sform_code
7568
 * @property {number} quatern_b
7569
 * @property {number} quatern_c
7570
 * @property {number} quatern_d
7571
 * @property {number} quatern_x
7572
 * @property {number} quatern_y
7573
 * @property {number} quatern_z
7574
 * @property {Array.<Array.<number>>} affine
7575
 * @property {string} magic
7576
 * @property {number[]} extensionFlag
7577
 * @type {Function}
7578
 */
7579
nifti.NIFTI2 = nifti.NIFTI2 || function () {
7580
    this.littleEndian = false;
7581
    this.dim_info = 0;
7582
    this.dims = [];
7583
    this.intent_p1 = 0;
7584
    this.intent_p2 = 0;
7585
    this.intent_p3 = 0;
7586
    this.intent_code = 0;
7587
    this.datatypeCode = 0;
7588
    this.numBitsPerVoxel = 0;
7589
    this.slice_start = 0;
7590
    this.slice_end = 0;
7591
    this.slice_code = 0;
7592
    this.pixDims = [];
7593
    this.vox_offset = 0;
7594
    this.scl_slope = 1;
7595
    this.scl_inter = 0;
7596
    this.xyzt_units = 0;
7597
    this.cal_max = 0;
7598
    this.cal_min = 0;
7599
    this.slice_duration = 0;
7600
    this.toffset = 0;
7601
    this.description = "";
7602
    this.aux_file = "";
7603
    this.intent_name = "";
7604
    this.qform_code = 0;
7605
    this.sform_code = 0;
7606
    this.quatern_b = 0;
7607
    this.quatern_c = 0;
7608
    this.quatern_d = 0;
7609
    this.qoffset_x = 0;
7610
    this.qoffset_y = 0;
7611
    this.qoffset_z = 0;
7612
    this.affine = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
7613
    this.magic = 0;
7614
    this.extensionFlag = [0, 0, 0, 0];
7615
};
7616
7617
7618
7619
/*** Static Pseudo-constants ***/
7620
7621
nifti.NIFTI2.MAGIC_COOKIE = 540;
7622
nifti.NIFTI2.MAGIC_NUMBER_LOCATION = 4;
7623
nifti.NIFTI2.MAGIC_NUMBER = [0x6E, 0x2B, 0x32, 0, 0x0D, 0x0A, 0x1A, 0x0A];  // n+2\0
7624
7625
7626
7627
/*** Prototype Methods ***/
7628
7629
/**
7630
 * Reads the header data.
7631
 * @param {ArrayBuffer} data
7632
 */
7633
nifti.NIFTI2.prototype.readHeader = function (data) {
7634
    var rawData = new DataView(data),
7635
        magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian),
7636
        ctr,
7637
        ctrOut,
7638
        ctrIn,
7639
        index,
7640
        array;
7641
7642
    if (magicCookieVal !== nifti.NIFTI2.MAGIC_COOKIE) {  // try as little endian
7643
        this.littleEndian = true;
7644
        magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian);
7645
    }
7646
7647
    if (magicCookieVal !== nifti.NIFTI2.MAGIC_COOKIE) {
7648
        throw new Error("This does not appear to be a NIFTI file!");
7649
    }
7650
7651
    this.datatypeCode = nifti.Utils.getShortAt(rawData, 12, this.littleEndian);
7652
    this.numBitsPerVoxel = nifti.Utils.getShortAt(rawData, 14, this.littleEndian);
7653
7654
    for (ctr = 0; ctr < 8; ctr += 1) {
7655
        index = 16 + (ctr * 8);
7656
        this.dims[ctr] = nifti.Utils.getLongAt(rawData, index, this.littleEndian);
7657
    }
7658
7659
    this.intent_p1 = nifti.Utils.getDoubleAt(rawData, 80, this.littleEndian);
7660
    this.intent_p2 = nifti.Utils.getDoubleAt(rawData, 88, this.littleEndian);
7661
    this.intent_p3 = nifti.Utils.getDoubleAt(rawData, 96, this.littleEndian);
7662
7663
    for (ctr = 0; ctr < 8; ctr += 1) {
7664
        index = 104 + (ctr * 8);
7665
        this.pixDims[ctr] = nifti.Utils.getDoubleAt(rawData, index, this.littleEndian);
7666
    }
7667
7668
    this.vox_offset = nifti.Utils.getLongAt(rawData, 168, this.littleEndian);
7669
7670
    this.scl_slope = nifti.Utils.getDoubleAt(rawData, 176, this.littleEndian);
7671
    this.scl_inter = nifti.Utils.getDoubleAt(rawData, 184, this.littleEndian);
7672
7673
    this.cal_max = nifti.Utils.getDoubleAt(rawData, 192, this.littleEndian);
7674
    this.cal_min = nifti.Utils.getDoubleAt(rawData, 200, this.littleEndian);
7675
7676
    this.slice_duration = nifti.Utils.getDoubleAt(rawData, 208, this.littleEndian);
7677
7678
    this.toffset = nifti.Utils.getDoubleAt(rawData, 216, this.littleEndian);
7679
7680
    this.slice_start = nifti.Utils.getLongAt(rawData, 224, this.littleEndian);
7681
    this.slice_end = nifti.Utils.getLongAt(rawData, 232, this.littleEndian);
7682
7683
    this.description = nifti.Utils.getStringAt(rawData, 240, 240 + 80);
7684
    this.aux_file = nifti.Utils.getStringAt(rawData, 320, 320 + 24);
7685
7686
    this.qform_code = nifti.Utils.getIntAt(rawData, 344, this.littleEndian);
7687
    this.sform_code = nifti.Utils.getIntAt(rawData, 348, this.littleEndian);
7688
7689
    this.quatern_b = nifti.Utils.getDoubleAt(rawData, 352, this.littleEndian);
7690
    this.quatern_c = nifti.Utils.getDoubleAt(rawData, 360, this.littleEndian);
7691
    this.quatern_d = nifti.Utils.getDoubleAt(rawData, 368, this.littleEndian);
7692
    this.qoffset_x = nifti.Utils.getDoubleAt(rawData, 376, this.littleEndian);
7693
    this.qoffset_y = nifti.Utils.getDoubleAt(rawData, 384, this.littleEndian);
7694
    this.qoffset_z = nifti.Utils.getDoubleAt(rawData, 392, this.littleEndian);
7695
7696
    for (ctrOut = 0; ctrOut < 3; ctrOut += 1) {
7697
        for (ctrIn = 0; ctrIn < 4; ctrIn += 1) {
7698
            index = 400 + (((ctrOut * 4) + ctrIn) * 8);
7699
            this.affine[ctrOut][ctrIn] = nifti.Utils.getDoubleAt(rawData, index, this.littleEndian);
7700
        }
7701
    }
7702
7703
    this.affine[3][0] = 0;
7704
    this.affine[3][1] = 0;
7705
    this.affine[3][2] = 0;
7706
    this.affine[3][3] = 1;
7707
7708
    this.slice_code = nifti.Utils.getIntAt(rawData, 496, this.littleEndian);
7709
    this.xyzt_units = nifti.Utils.getIntAt(rawData, 500, this.littleEndian);
7710
    this.intent_code = nifti.Utils.getIntAt(rawData, 504, this.littleEndian);
7711
    this.intent_name = nifti.Utils.getStringAt(rawData, 508, 508 + 16);
7712
7713
    this.dim_info = nifti.Utils.getByteAt(rawData, 524);
7714
7715
    if (rawData.byteLength > nifti.NIFTI2.MAGIC_COOKIE) {
7716
        this.extensionFlag[0] = nifti.Utils.getByteAt(rawData, 540);
7717
        this.extensionFlag[1] = nifti.Utils.getByteAt(rawData, 540 + 1);
7718
        this.extensionFlag[2] = nifti.Utils.getByteAt(rawData, 540 + 2);
7719
        this.extensionFlag[3] = nifti.Utils.getByteAt(rawData, 540 + 3);
7720
7721
        if (this.extensionFlag[0]) {
7722
            this.extensionSize = this.getExtensionSize(rawData);
7723
            this.extensionCode = this.getExtensionCode(rawData);
7724
        }
7725
    }
7726
};
7727
7728
7729
7730
/**
7731
 * Returns a formatted string of header fields.
7732
 * @returns {string}
7733
 */
7734
nifti.NIFTI2.prototype.toFormattedString = function () {
7735
    var fmt = nifti.Utils.formatNumber,
7736
        string = "";
7737
7738
    string += ("Datatype = " +  + this.datatypeCode + " (" + this.getDatatypeCodeString(this.datatypeCode) + ")\n");
7739
    string += ("Bits Per Voxel = " + " = " + this.numBitsPerVoxel + "\n");
7740
    string += ("Image Dimensions" + " (1-8): " +
7741
        this.dims[0] + ", " +
7742
        this.dims[1] + ", " +
7743
        this.dims[2] + ", " +
7744
        this.dims[3] + ", " +
7745
        this.dims[4] + ", " +
7746
        this.dims[5] + ", " +
7747
        this.dims[6] + ", " +
7748
        this.dims[7] + "\n");
7749
7750
    string += ("Intent Parameters (1-3): " +
7751
        this.intent_p1 + ", " +
7752
        this.intent_p2 + ", " +
7753
        this.intent_p3) + "\n";
7754
7755
    string += ("Voxel Dimensions (1-8): " +
7756
        fmt(this.pixDims[0]) + ", " +
7757
        fmt(this.pixDims[1]) + ", " +
7758
        fmt(this.pixDims[2]) + ", " +
7759
        fmt(this.pixDims[3]) + ", " +
7760
        fmt(this.pixDims[4]) + ", " +
7761
        fmt(this.pixDims[5]) + ", " +
7762
        fmt(this.pixDims[6]) + ", " +
7763
        fmt(this.pixDims[7]) + "\n");
7764
7765
    string += ("Image Offset = " + this.vox_offset + "\n");
7766
    string += ("Data Scale:  Slope = " + fmt(this.scl_slope) + "  Intercept = " + fmt(this.scl_inter) + "\n");
7767
    string += ("Display Range:  Max = " + fmt(this.cal_max) + "  Min = " + fmt(this.cal_min) + "\n");
7768
    string += ("Slice Duration = " + this.slice_duration + "\n");
7769
    string += ("Time Axis Shift = " + this.toffset + "\n");
7770
    string += ("Slice Start = " + this.slice_start + "\n");
7771
    string += ("Slice End = " + this.slice_end + "\n");
7772
    string += ("Description: \"" + this.description + "\"\n");
7773
    string += ("Auxiliary File: \"" + this.aux_file + "\"\n");
7774
    string += ("Q-Form Code = " + this.qform_code + " (" + this.getTransformCodeString(this.qform_code) + ")\n");
7775
    string += ("S-Form Code = " + this.sform_code + " (" + this.getTransformCodeString(this.sform_code) + ")\n");
7776
    string += ("Quaternion Parameters:  " +
7777
    "b = " + fmt(this.quatern_b) + "  " +
7778
    "c = " + fmt(this.quatern_c) + "  " +
7779
    "d = " + fmt(this.quatern_d) + "\n");
7780
7781
    string += ("Quaternion Offsets:  " +
7782
    "x = " + this.qoffset_x + "  " +
7783
    "y = " + this.qoffset_y + "  " +
7784
    "z = " + this.qoffset_z + "\n");
7785
7786
    string += ("S-Form Parameters X: " +
7787
    fmt(this.affine[0][0]) + ", " +
7788
    fmt(this.affine[0][1]) + ", " +
7789
    fmt(this.affine[0][2]) + ", " +
7790
    fmt(this.affine[0][3]) + "\n");
7791
7792
    string += ("S-Form Parameters Y: " +
7793
    fmt(this.affine[1][0]) + ", " +
7794
    fmt(this.affine[1][1]) + ", " +
7795
    fmt(this.affine[1][2]) + ", " +
7796
    fmt(this.affine[1][3]) + "\n");
7797
7798
    string += ("S-Form Parameters Z: " +
7799
    fmt(this.affine[2][0]) + ", " +
7800
    fmt(this.affine[2][1]) + ", " +
7801
    fmt(this.affine[2][2]) + ", " +
7802
    fmt(this.affine[2][3]) + "\n");
7803
7804
    string += ("Slice Code = " + this.slice_code + "\n");
7805
    string += ("Units Code = " + this.xyzt_units + " (" + this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.xyzt_units) + ", " + this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.xyzt_units) + ")\n");
7806
    string += ("Intent Code = " + this.intent_code + "\n");
7807
    string += ("Intent Name: \"" + this.intent_name + "\"\n");
7808
7809
    string += ("Dim Info = " + this.dim_info + "\n");
7810
7811
    return string;
7812
};
7813
7814
7815
7816
/**
7817
 * Returns the byte index of the extension.
7818
 * @returns {number}
7819
 */
7820
nifti.NIFTI2.prototype.getExtensionLocation = function() {
7821
    return nifti.NIFTI2.MAGIC_COOKIE + 4;
7822
};
7823
7824
7825
7826
/**
7827
 * Returns the extension size.
7828
 * @param {DataView} data
7829
 * @returns {number}
7830
 */
7831
nifti.NIFTI2.prototype.getExtensionSize = nifti.NIFTI1.prototype.getExtensionSize;
7832
7833
7834
7835
/**
7836
 * Returns the extension code.
7837
 * @param {DataView} data
7838
 * @returns {number}
7839
 */
7840
nifti.NIFTI2.prototype.getExtensionCode = nifti.NIFTI1.prototype.getExtensionCode;
7841
7842
7843
7844
/**
7845
 * Returns a human-readable string of datatype.
7846
 * @param {number} code
7847
 * @returns {string}
7848
 */
7849
nifti.NIFTI2.prototype.getDatatypeCodeString = nifti.NIFTI1.prototype.getDatatypeCodeString;
7850
7851
7852
7853
/**
7854
 * Returns a human-readable string of transform type.
7855
 * @param {number} code
7856
 * @returns {string}
7857
 */
7858
nifti.NIFTI2.prototype.getTransformCodeString = nifti.NIFTI1.prototype.getTransformCodeString;
7859
7860
7861
7862
/**
7863
 * Returns a human-readable string of spatial and temporal units.
7864
 * @param {number} code
7865
 * @returns {string}
7866
 */
7867
nifti.NIFTI2.prototype.getUnitsCodeString = nifti.NIFTI1.prototype.getUnitsCodeString;
7868
7869
7870
7871
/**
7872
 * Returns the qform matrix.
7873
 * @returns {Array.<Array.<number>>}
7874
 */
7875
nifti.NIFTI2.prototype.getQformMat = nifti.NIFTI1.prototype.getQformMat;
7876
7877
7878
7879
/**
7880
 * Converts qform to an affine.  (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
7881
 * @param {number} qb
7882
 * @param {number} qc
7883
 * @param {number} qd
7884
 * @param {number} qx
7885
 * @param {number} qy
7886
 * @param {number} qz
7887
 * @param {number} dx
7888
 * @param {number} dy
7889
 * @param {number} dz
7890
 * @param {number} qfac
7891
 * @returns {Array.<Array.<number>>}
7892
 */
7893
nifti.NIFTI2.prototype.convertNiftiQFormToNiftiSForm = nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm;
7894
7895
7896
7897
/**
7898
 * Converts sform to an orientation string (e.g., XYZ+--).  (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
7899
 * @param {Array.<Array.<number>>} R
7900
 * @returns {string}
7901
 */
7902
nifti.NIFTI2.prototype.convertNiftiSFormToNEMA = nifti.NIFTI1.prototype.convertNiftiSFormToNEMA;
7903
7904
7905
7906
nifti.NIFTI2.prototype.nifti_mat33_mul = nifti.NIFTI1.prototype.nifti_mat33_mul;
7907
7908
7909
7910
nifti.NIFTI2.prototype.nifti_mat33_determ = nifti.NIFTI1.prototype.nifti_mat33_determ;
7911
7912
7913
7914
/*** Exports ***/
7915
7916
var moduleType = typeof module;
7917
if ((moduleType !== 'undefined') && module.exports) {
7918
    module.exports = nifti.NIFTI2;
7919
}
7920
7921
},{"./nifti1.js":18,"./utilities.js":20}],20:[function(require,module,exports){
7922
7923
/*jslint browser: true, node: true */
7924
/*global require, module */
7925
7926
"use strict";
7927
7928
/*** Imports ***/
7929
7930
var nifti = nifti || {};
7931
nifti.Utils = nifti.Utils || {};
7932
7933
7934
7935
/*** Static Pseudo-constants ***/
7936
7937
nifti.Utils.crcTable = null;
7938
nifti.Utils.GUNZIP_MAGIC_COOKIE1 = 31;
7939
nifti.Utils.GUNZIP_MAGIC_COOKIE2 = 139;
7940
7941
7942
7943
/*** Static methods ***/
7944
7945
nifti.Utils.getStringAt = function (data, start, end) {
7946
    var str = "", ctr, ch;
7947
7948
    for (ctr = start; ctr < end; ctr += 1) {
7949
        ch = data.getUint8(ctr);
7950
7951
        if (ch !== 0) {
7952
            str += String.fromCharCode(ch);
7953
        }
7954
    }
7955
7956
    return str;
7957
};
7958
7959
7960
7961
nifti.Utils.getByteAt = function (data, start) {
7962
    return data.getInt8(start);
7963
};
7964
7965
7966
7967
nifti.Utils.getShortAt = function (data, start, littleEndian) {
7968
    return data.getInt16(start, littleEndian);
7969
};
7970
7971
7972
7973
nifti.Utils.getIntAt = function (data, start, littleEndian) {
7974
    return data.getInt32(start, littleEndian);
7975
};
7976
7977
7978
7979
nifti.Utils.getFloatAt = function (data, start, littleEndian) {
7980
    return data.getFloat32(start, littleEndian);
7981
};
7982
7983
7984
7985
nifti.Utils.getDoubleAt = function (data, start, littleEndian) {
7986
    return data.getFloat64(start, littleEndian);
7987
};
7988
7989
7990
7991
nifti.Utils.getLongAt = function (data, start, littleEndian) {
7992
    var ctr, array = [], value = 0;
7993
7994
    for (ctr = 0; ctr < 8; ctr += 1) {
7995
        array[ctr] = nifti.Utils.getByteAt(data, start + ctr, littleEndian);
7996
    }
7997
7998
    for (ctr = array.length - 1; ctr >= 0; ctr--) {
7999
        value = (value * 256) + array[ctr];
8000
    }
8001
8002
    return value;
8003
};
8004
8005
8006
8007
nifti.Utils.toArrayBuffer = function (buffer) {
8008
    var ab, view, i;
8009
8010
    ab = new ArrayBuffer(buffer.length);
8011
    view = new Uint8Array(ab);
8012
    for (i = 0; i < buffer.length; i += 1) {
8013
        view[i] = buffer[i];
8014
    }
8015
    return ab;
8016
};
8017
8018
8019
8020
nifti.Utils.isString = function (obj) {
8021
    return (typeof obj === "string" || obj instanceof String);
8022
};
8023
8024
8025
nifti.Utils.formatNumber = function (num, shortFormat) {
8026
    var val = 0;
8027
8028
    if (nifti.Utils.isString(num)) {
8029
        val = Number(num);
8030
    } else {
8031
        val = num;
8032
    }
8033
8034
    if (shortFormat) {
8035
        val = val.toPrecision(5);
8036
    } else {
8037
        val = val.toPrecision(7);
8038
    }
8039
8040
    return parseFloat(val);
8041
};
8042
8043
8044
8045
// http://stackoverflow.com/questions/18638900/javascript-crc32
8046
nifti.Utils.makeCRCTable = function(){
8047
    var c;
8048
    var crcTable = [];
8049
    for(var n =0; n < 256; n++){
8050
        c = n;
8051
        for(var k =0; k < 8; k++){
8052
            c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
8053
        }
8054
        crcTable[n] = c;
8055
    }
8056
    return crcTable;
8057
};
8058
8059
8060
8061
nifti.Utils.crc32 = function(dataView) {
8062
    var crcTable = nifti.Utils.crcTable || (nifti.Utils.crcTable = nifti.Utils.makeCRCTable());
8063
    var crc = 0 ^ (-1);
8064
8065
    for (var i = 0; i < dataView.byteLength; i++ ) {
8066
        crc = (crc >>> 8) ^ crcTable[(crc ^ dataView.getUint8(i)) & 0xFF];
8067
    }
8068
8069
    return (crc ^ (-1)) >>> 0;
8070
};
8071
8072
8073
8074
/*** Exports ***/
8075
8076
var moduleType = typeof module;
8077
if ((moduleType !== 'undefined') && module.exports) {
8078
    module.exports = nifti.Utils;
8079
}
8080
8081
},{}]},{},[17])(17)
8082
});