Move to es6

This commit is contained in:
Vitaly Puzrin 2020-11-08 11:31:30 +03:00
parent f681f66fd3
commit 505e36d9f0
37 changed files with 1091 additions and 1082 deletions

View file

@ -1,10 +1,9 @@
env: env:
node: true node: true
es6: true
globals: parserOptions:
Uint8Array: false ecmaVersion: 2015
Uint16Array: false
Int32Array: false
ignorePatterns: ignorePatterns:
- coverage/ - coverage/
@ -29,7 +28,7 @@ rules:
dot-location: [ 2, 'property' ] dot-location: [ 2, 'property' ]
eol-last: 2 eol-last: 2
eqeqeq: 2 eqeqeq: 2
func-style: [ 2, declaration ] # func-style: [ 2, declaration ]
guard-for-in: 2 guard-for-in: 2
handle-callback-err: 2 handle-callback-err: 2
indent: [ 2, 2, { VariableDeclarator: { var: 2, let: 2, const: 3 }, SwitchCase: 1, ignoreComments: true, MemberExpression: off, ignoredNodes: ["ConditionalExpression"] } ] indent: [ 2, 2, { VariableDeclarator: { var: 2, let: 2, const: 3 }, SwitchCase: 1, ignoreComments: true, MemberExpression: off, ignoredNodes: ["ConditionalExpression"] } ]

View file

@ -11,7 +11,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Removed binary strings and `Array` support. - Removed binary strings and `Array` support.
- Removed fallbacks for unsupported TypedArray methods (`.set()`, `.subarray()`). - Removed fallbacks for unsupported TypedArray methods (`.set()`, `.subarray()`).
- Removed support of `Inflate` & `Deflate` instance create without `new`. - Removed support of `Inflate` & `Deflate` instance create without `new`.
- Upgrade build tools to modern ones. - Switched to es6. Legacy es5 builds available in `/dist`.
- Structure of `/dist` folder changed.
- Upgraded build tools to modern ones.
## [1.0.11] - 2020-01-29 ## [1.0.11] - 2020-01-29
### Fixed ### Fixed

View file

@ -2,26 +2,26 @@
'use strict'; 'use strict';
var LEVEL = 6; const LEVEL = 6;
var path = require('path'); const path = require('path');
var fs = require('fs'); const fs = require('fs');
var util = require('util'); const util = require('util');
var Benchmark = require('benchmark'); const Benchmark = require('benchmark');
var ansi = require('ansi'); const ansi = require('ansi');
var cursor = ansi(process.stdout); const cursor = ansi(process.stdout);
var pako = require('../'); const pako = require('../');
var IMPLS_DIRECTORY = path.join(__dirname, 'implementations'); const IMPLS_DIRECTORY = path.join(__dirname, 'implementations');
var IMPLS_PATHS = {}; const IMPLS_PATHS = {};
var IMPLS = []; const IMPLS = [];
fs.readdirSync(IMPLS_DIRECTORY).sort().forEach(function (name) { fs.readdirSync(IMPLS_DIRECTORY).sort().forEach(function (name) {
var file = path.join(IMPLS_DIRECTORY, name); const file = path.join(IMPLS_DIRECTORY, name);
var code = require(file); const code = require(file);
IMPLS_PATHS[name] = file; IMPLS_PATHS[name] = file;
IMPLS.push({ IMPLS.push({
@ -32,15 +32,15 @@ fs.readdirSync(IMPLS_DIRECTORY).sort().forEach(function (name) {
/* eslint-disable no-console */ /* eslint-disable no-console */
var SAMPLES_DIRECTORY = path.join(__dirname, 'samples'); const SAMPLES_DIRECTORY = path.join(__dirname, 'samples');
var SAMPLES = []; const SAMPLES = [];
fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) { fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) {
var filepath = path.join(SAMPLES_DIRECTORY, sample), const filepath = path.join(SAMPLES_DIRECTORY, sample);
extname = path.extname(filepath), const extname = path.extname(filepath);
basename = path.basename(filepath, extname); const basename = path.basename(filepath, extname);
var content = {}; // raw/compressed data in different formats const content = {}; // raw/compressed data in different formats
content.buffer = fs.readFileSync(filepath); content.buffer = fs.readFileSync(filepath);
content.typed = new Uint8Array(content.buffer); content.typed = new Uint8Array(content.buffer);
@ -51,7 +51,7 @@ fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) {
content.deflateRawTyped = pako.deflateRaw(content.typed, { level: LEVEL }); content.deflateRawTyped = pako.deflateRaw(content.typed, { level: LEVEL });
var title = util.format('(%d bytes raw / ~%d bytes compressed)', content.typed.length, content.deflateTyped.length); const title = util.format('(%d bytes raw / ~%d bytes compressed)', content.typed.length, content.deflateTyped.length);
function onComplete() { function onComplete() {
@ -59,7 +59,7 @@ fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) {
} }
var suite = new Benchmark.Suite(title, { const suite = new Benchmark.Suite(title, {
onStart: function onStart() { onStart: function onStart() {
console.log('\nSample: %s %s', sample, title); console.log('\nSample: %s %s', sample, title);
@ -108,7 +108,7 @@ fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) {
function select(patterns) { function select(patterns) {
var result = []; const result = [];
if (!(patterns instanceof Array)) { if (!(patterns instanceof Array)) {
patterns = [ patterns ]; patterns = [ patterns ];
@ -131,7 +131,7 @@ function select(patterns) {
function run(files) { function run(files) {
var selected = select(files); const selected = select(files);
if (selected.length > 0) { if (selected.length > 0) {
console.log('Selected samples: (%d of %d)', selected.length, SAMPLES.length); console.log('Selected samples: (%d of %d)', selected.length, SAMPLES.length);

View file

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var deflateSync = require('zlibjs').deflateSync; const deflateSync = require('zlibjs').deflateSync;
exports.run = function (data, level) { exports.run = (data, level) => {
// Compression levels not supported. Use unknown defaults always // Compression levels not supported. Use unknown defaults always
return deflateSync(data.typed, { level: level }); return deflateSync(data.typed, { level: level });
}; };

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var pako = require('../../../'); const pako = require('../../../');
exports.run = function (data, level) { exports.run = (data, level) => {
return pako.deflate(data.typed, { level: level }); return pako.deflate(data.typed, { level: level });
}; };

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var zlib = require('zlib'); const zlib = require('zlib');
exports.run = function (data, level) { exports.run = (data, level) => {
zlib.deflateSync(data.buffer, { level:level }); zlib.deflateSync(data.buffer, { level:level });
}; };

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var pako = require('../../../'); const pako = require('../../../');
exports.run = function (data, level) { exports.run = (data, level) => {
return pako.gzip(data.typed, { level: level }); return pako.gzip(data.typed, { level: level });
}; };

View file

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var inflateSync = require('zlibjs').inflateSync; const inflateSync = require('zlibjs').inflateSync;
exports.run = function (data/*, level*/) { exports.run = (data/*, level*/) => {
// Compression levels not supported. Use unknown defaults always // Compression levels not supported. Use unknown defaults always
return inflateSync(data.deflateTyped); return inflateSync(data.deflateTyped);
}; };

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var pako = require('../../../'); const pako = require('../../../');
exports.run = function (data) { exports.run = (data) => {
return pako.inflate(data.deflateTyped, {}); return pako.inflate(data.deflateTyped, {});
}; };

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var zlib = require('zlib'); const zlib = require('zlib');
exports.run = function (data) { exports.run = (data) => {
zlib.inflateSync(data.deflateTyped); zlib.inflateSync(data.deflateTyped);
}; };

View file

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var pako = require('../../../'); const pako = require('../../../');
exports.run = function (data) { exports.run = (data) => {
return pako.ungzip(data.gzipTyped, { return pako.ungzip(data.gzipTyped, {
}); });
}; };

View file

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var pako = require('../'); const pako = require('../');
var data = new Uint8Array(fs.readFileSync(path.join(__dirname, '/samples/lorem_1mb.txt'))); const data = new Uint8Array(fs.readFileSync(path.join(__dirname, '/samples/lorem_1mb.txt')));
var deflated = pako.deflate(data, { level: 6/*, to: 'string'*/ }); const deflated = pako.deflate(data, { level: 6/*, to: 'string'*/ });
for (var i = 0; i < 200; i++) { for (let i = 0; i < 200; i++) {
pako.inflate(deflated, { to: 'string' }); pako.inflate(deflated, { to: 'string' });
} }

View file

@ -1,5 +1,2 @@
env:
es6: true
parserOptions: parserOptions:
ecmaVersion: 2017 ecmaVersion: 2017

View file

@ -23,7 +23,7 @@ function error(msg) {
} }
const server = http.createServer(async function (req, res) { const server = http.createServer(async (req, res) => {
console.log('--- received request'); console.log('--- received request');
@ -35,7 +35,7 @@ const server = http.createServer(async function (req, res) {
// //
// Check request size early by header and terminate immediately for big data // Check request size early by header and terminate immediately for big data
// //
let length = parseInt((req.headers['content-length'] || '0'), 10); const length = parseInt((req.headers['content-length'] || '0'), 10);
if (!length || isNaN(length)) throw error('Length required'); if (!length || isNaN(length)) throw error('Length required');
@ -45,12 +45,12 @@ const server = http.createServer(async function (req, res) {
let err = null; let err = null;
let form = new multiparty.Form({ const form = new multiparty.Form({
maxFieldsSize: MAX_FIELDS_SIZE, maxFieldsSize: MAX_FIELDS_SIZE,
maxFilesSize: MAX_FILES_SIZE maxFilesSize: MAX_FILES_SIZE
}); });
let files = await new Promise(resolve => { const files = await new Promise(resolve => {
form.parse(req, function (e, fields, files) { form.parse(req, function (e, fields, files) {
if (e) err = e; if (e) err = e;
resolve(files); resolve(files);
@ -62,21 +62,21 @@ const server = http.createServer(async function (req, res) {
throw err; throw err;
} }
let bin = await readFile(files.binson[0].path); const bin = await readFile(files.binson[0].path);
// Kludge - here we should cleanup all files // Kludge - here we should cleanup all files
fs.unlinkSync(files.binson[0].path); fs.unlinkSync(files.binson[0].path);
// Decompress binary content // Decompress binary content
// Note! Can throw error on bad data // Note! Can throw error on bad data
let uncompressed = await inflate(bin); const uncompressed = await inflate(bin);
// Convert utf8 buffer -> utf16 string (native JavaScript string format) // Convert utf8 buffer -> utf16 string (native JavaScript string format)
let decoded = uncompressed.toString(); const decoded = uncompressed.toString();
// Finally, create an object // Finally, create an object
// Note! Can throw error on bad data // Note! Can throw error on bad data
let obj = JSON.parse(decoded); const obj = JSON.parse(decoded);
console.log('--- received object is: ', obj); console.log('--- received object is: ', obj);
res.end('ok'); res.end('ok');

View file

@ -1,13 +1,13 @@
// Top level file is just a mixin of submodules & constants // Top level file is just a mixin of submodules & constants
'use strict'; 'use strict';
var assign = require('./lib/utils/common').assign; const assign = require('./lib/utils/common').assign;
var deflate = require('./lib/deflate'); const deflate = require('./lib/deflate');
var inflate = require('./lib/inflate'); const inflate = require('./lib/inflate');
var constants = require('./lib/zlib/constants'); const constants = require('./lib/zlib/constants');
var pako = {}; let pako = {};
assign(pako, deflate, inflate, constants); assign(pako, deflate, inflate, constants);

View file

@ -1,29 +1,24 @@
'use strict'; 'use strict';
var zlib_deflate = require('./zlib/deflate'); const zlib_deflate = require('./zlib/deflate');
var utils = require('./utils/common'); const utils = require('./utils/common');
var strings = require('./utils/strings'); const strings = require('./utils/strings');
var msg = require('./zlib/messages'); const msg = require('./zlib/messages');
var ZStream = require('./zlib/zstream'); const ZStream = require('./zlib/zstream');
var toString = Object.prototype.toString; const toString = Object.prototype.toString;
/* Public constants ==========================================================*/ /* Public constants ==========================================================*/
/* ===========================================================================*/ /* ===========================================================================*/
var Z_NO_FLUSH = 0; const {
var Z_FINISH = 4; Z_NO_FLUSH, Z_FINISH,
Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,
var Z_OK = 0; Z_DEFAULT_COMPRESSION,
var Z_STREAM_END = 1; Z_DEFAULT_STRATEGY,
var Z_SYNC_FLUSH = 2; Z_DEFLATED
} = require('./zlib/constants');
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/ /* ===========================================================================*/
@ -101,11 +96,11 @@ var Z_DEFLATED = 8;
* ##### Example: * ##### Example:
* *
* ```javascript * ```javascript
* var pako = require('pako') * const pako = require('pako')
* , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
* *
* var deflate = new pako.Deflate({ level: 3}); * const deflate = new pako.Deflate({ level: 3});
* *
* deflate.push(chunk1, false); * deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk * deflate.push(chunk2, true); // true -> last chunk
@ -125,7 +120,7 @@ function Deflate(options) {
strategy: Z_DEFAULT_STRATEGY strategy: Z_DEFAULT_STRATEGY
}, options || {}); }, options || {});
var opt = this.options; let opt = this.options;
if (opt.raw && (opt.windowBits > 0)) { if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits; opt.windowBits = -opt.windowBits;
@ -143,7 +138,7 @@ function Deflate(options) {
this.strm = new ZStream(); this.strm = new ZStream();
this.strm.avail_out = 0; this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2( let status = zlib_deflate.deflateInit2(
this.strm, this.strm,
opt.level, opt.level,
opt.method, opt.method,
@ -161,7 +156,7 @@ function Deflate(options) {
} }
if (opt.dictionary) { if (opt.dictionary) {
var dict; let dict;
// Convert data if needed // Convert data if needed
if (typeof opt.dictionary === 'string') { if (typeof opt.dictionary === 'string') {
// If we need to compress text, change encoding to utf8. // If we need to compress text, change encoding to utf8.
@ -209,13 +204,13 @@ function Deflate(options) {
* ``` * ```
**/ **/
Deflate.prototype.push = function (data, mode) { Deflate.prototype.push = function (data, mode) {
var strm = this.strm; const strm = this.strm;
var chunkSize = this.options.chunkSize; const chunkSize = this.options.chunkSize;
var status, _mode; let status;
if (this.ended) { return false; } if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); const _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed // Convert data if needed
if (typeof data === 'string') { if (typeof data === 'string') {
@ -326,14 +321,14 @@ Deflate.prototype.onEnd = function (status) {
* ##### Example: * ##### Example:
* *
* ```javascript * ```javascript
* var pako = require('pako') * const pako = require('pako')
* , data = new Uint8Array([1,2,3,4,5,6,7,8,9]); * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
* *
* console.log(pako.deflate(data)); * console.log(pako.deflate(data));
* ``` * ```
**/ **/
function deflate(input, options) { function deflate(input, options) {
var deflator = new Deflate(options); const deflator = new Deflate(options);
deflator.push(input, true); deflator.push(input, true);

View file

@ -1,15 +1,25 @@
'use strict'; 'use strict';
var zlib_inflate = require('./zlib/inflate'); const zlib_inflate = require('./zlib/inflate');
var utils = require('./utils/common'); const utils = require('./utils/common');
var strings = require('./utils/strings'); const strings = require('./utils/strings');
var c = require('./zlib/constants'); const msg = require('./zlib/messages');
var msg = require('./zlib/messages'); const ZStream = require('./zlib/zstream');
var ZStream = require('./zlib/zstream'); const GZheader = require('./zlib/gzheader');
var GZheader = require('./zlib/gzheader');
const toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
const {
Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_BUF_ERROR
} = require('./zlib/constants');
/* ===========================================================================*/
var toString = Object.prototype.toString;
/** /**
* class Inflate * class Inflate
@ -76,11 +86,11 @@ var toString = Object.prototype.toString;
* ##### Example: * ##### Example:
* *
* ```javascript * ```javascript
* var pako = require('pako') * const pako = require('pako')
* , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
* *
* var inflate = new pako.Inflate({ level: 3}); * const inflate = new pako.Inflate({ level: 3});
* *
* inflate.push(chunk1, false); * inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk * inflate.push(chunk2, true); // true -> last chunk
@ -97,7 +107,7 @@ function Inflate(options) {
to: '' to: ''
}, options || {}); }, options || {});
var opt = this.options; const opt = this.options;
// Force window size for `raw` data, if not set directly, // Force window size for `raw` data, if not set directly,
// because we have no header for autodetect. // because we have no header for autodetect.
@ -130,12 +140,12 @@ function Inflate(options) {
this.strm = new ZStream(); this.strm = new ZStream();
this.strm.avail_out = 0; this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2( let status = zlib_inflate.inflateInit2(
this.strm, this.strm,
opt.windowBits opt.windowBits
); );
if (status !== c.Z_OK) { if (status !== Z_OK) {
throw new Error(msg[status]); throw new Error(msg[status]);
} }
@ -153,7 +163,7 @@ function Inflate(options) {
} }
if (opt.raw) { //In raw mode we need to set the dictionary early if (opt.raw) { //In raw mode we need to set the dictionary early
status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
if (status !== c.Z_OK) { if (status !== Z_OK) {
throw new Error(msg[status]); throw new Error(msg[status]);
} }
} }
@ -186,18 +196,18 @@ function Inflate(options) {
* ``` * ```
**/ **/
Inflate.prototype.push = function (data, mode) { Inflate.prototype.push = function (data, mode) {
var strm = this.strm; const strm = this.strm;
var chunkSize = this.options.chunkSize; const chunkSize = this.options.chunkSize;
var dictionary = this.options.dictionary; const dictionary = this.options.dictionary;
var status, _mode; let status, _mode;
var next_out_utf8, tail, utf8str; let next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call // Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed. // when we check that all output data was flushed.
var allowBufError = false; let allowBufError = false;
if (this.ended) { return false; } if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed // Convert data if needed
if (toString.call(data) === '[object ArrayBuffer]') { if (toString.call(data) === '[object ArrayBuffer]') {
@ -216,25 +226,25 @@ Inflate.prototype.push = function (data, mode) {
strm.avail_out = chunkSize; strm.avail_out = chunkSize;
} }
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ status = zlib_inflate.inflate(strm, Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_NEED_DICT && dictionary) { if (status === Z_NEED_DICT && dictionary) {
status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
} }
if (status === c.Z_BUF_ERROR && allowBufError === true) { if (status === Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK; status = Z_OK;
allowBufError = false; allowBufError = false;
} }
if (status !== c.Z_STREAM_END && status !== c.Z_OK) { if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status); this.onEnd(status);
this.ended = true; this.ended = true;
return false; return false;
} }
if (strm.next_out) { if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') { if (this.options.to === 'string') {
@ -267,23 +277,23 @@ Inflate.prototype.push = function (data, mode) {
allowBufError = true; allowBufError = true;
} }
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
if (status === c.Z_STREAM_END) { if (status === Z_STREAM_END) {
_mode = c.Z_FINISH; _mode = Z_FINISH;
} }
// Finalize on the last chunk. // Finalize on the last chunk.
if (_mode === c.Z_FINISH) { if (_mode === Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm); status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status); this.onEnd(status);
this.ended = true; this.ended = true;
return status === c.Z_OK; return status === Z_OK;
} }
// callback interim results if Z_SYNC_FLUSH. // callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) { if (_mode === Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK); this.onEnd(Z_OK);
strm.avail_out = 0; strm.avail_out = 0;
return true; return true;
} }
@ -317,7 +327,7 @@ Inflate.prototype.onData = function (chunk) {
**/ **/
Inflate.prototype.onEnd = function (status) { Inflate.prototype.onEnd = function (status) {
// On success - join // On success - join
if (status === c.Z_OK) { if (status === Z_OK) {
if (this.options.to === 'string') { if (this.options.to === 'string') {
this.result = this.chunks.join(''); this.result = this.chunks.join('');
} else { } else {
@ -358,9 +368,9 @@ Inflate.prototype.onEnd = function (status) {
* ##### Example: * ##### Example:
* *
* ```javascript * ```javascript
* var pako = require('pako') * const pako = require('pako');
* , input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])) * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
* , output; * let output;
* *
* try { * try {
* output = pako.inflate(input); * output = pako.inflate(input);
@ -370,7 +380,7 @@ Inflate.prototype.onEnd = function (status) {
* ``` * ```
**/ **/
function inflate(input, options) { function inflate(input, options) {
var inflator = new Inflate(options); const inflator = new Inflate(options);
inflator.push(input, true); inflator.push(input, true);

View file

@ -1,21 +1,21 @@
'use strict'; 'use strict';
function _has(obj, key) { const _has = (obj, key) => {
return Object.prototype.hasOwnProperty.call(obj, key); return Object.prototype.hasOwnProperty.call(obj, key);
} };
module.exports.assign = function (obj /*from1, from2, from3, ...*/) { module.exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1); const sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) { while (sources.length) {
var source = sources.shift(); const source = sources.shift();
if (!source) { continue; } if (!source) { continue; }
if (typeof source !== 'object') { if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object'); throw new TypeError(source + 'must be non-object');
} }
for (var p in source) { for (const p in source) {
if (_has(source, p)) { if (_has(source, p)) {
obj[p] = source[p]; obj[p] = source[p];
} }
@ -27,20 +27,19 @@ module.exports.assign = function (obj /*from1, from2, from3, ...*/) {
// Join array of chunks to single array. // Join array of chunks to single array.
module.exports.flattenChunks = function (chunks) { module.exports.flattenChunks = (chunks) => {
var i, l, len, pos, chunk, result;
// calculate data length // calculate data length
len = 0; let len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
for (let i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length; len += chunks[i].length;
} }
// join chunks // join chunks
result = new Uint8Array(len); const result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) { for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i]; let chunk = chunks[i];
result.set(chunk, pos); result.set(chunk, pos);
pos += chunk.length; pos += chunk.length;
} }

View file

@ -7,7 +7,7 @@
// - apply(Array) can fail on Android 2.2 // - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari // - apply(Uint8Array) can fail on iOS 5.1 Safari
// //
var STR_APPLY_UIA_OK = true; let STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
@ -15,16 +15,16 @@ try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APP
// Table with utf8 lengths (calculated by first byte of sequence) // Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff // because max possible codepoint is 0x10ffff
var _utf8len = new Uint8Array(256); const _utf8len = new Uint8Array(256);
for (var q = 0; q < 256; q++) { for (let q = 0; q < 256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
} }
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible) // convert string to array (typed, when possible)
exports.string2buf = function (str) { module.exports.string2buf = (str) => {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size // count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) { for (m_pos = 0; m_pos < str_len; m_pos++) {
@ -77,7 +77,7 @@ exports.string2buf = function (str) {
}; };
// Helper // Helper
function buf2binstring(buf, len) { const buf2binstring = (buf, len) => {
// On Chrome, the arguments in a function call that are allowed is `65534`. // On Chrome, the arguments in a function call that are allowed is `65534`.
// If the length of the buffer is smaller than that, we can use this optimization, // If the length of the buffer is smaller than that, we can use this optimization,
// otherwise we will take a slower path. // otherwise we will take a slower path.
@ -87,30 +87,30 @@ function buf2binstring(buf, len) {
} }
} }
var result = ''; let result = '';
for (var i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]); result += String.fromCharCode(buf[i]);
} }
return result; return result;
} };
// convert array to string // convert array to string
exports.buf2string = function (buf, max) { module.exports.buf2string = (buf, max) => {
var i, out, c, c_len; let i, out;
var len = max || buf.length; const len = max || buf.length;
// Reserve max possible length (2 words per char) // Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for // NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array. // String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2); const utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) { for (out = 0, i = 0; i < len;) {
c = buf[i++]; let c = buf[i++];
// quick process ascii // quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; } if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c]; let c_len = _utf8len[c];
// skip 5 & 6 byte codes // skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
@ -144,14 +144,13 @@ exports.buf2string = function (buf, max) {
// //
// buf[] - utf8 bytes array // buf[] - utf8 bytes array
// max - length limit (mandatory); // max - length limit (mandatory);
exports.utf8border = function (buf, max) { module.exports.utf8border = (buf, max) => {
var pos;
max = max || buf.length; max = max || buf.length;
if (max > buf.length) { max = buf.length; } if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found // go back from last position, until start of sequence found
pos = max - 1; let pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Very small and broken sequence, // Very small and broken sequence,

View file

@ -23,8 +23,8 @@
// misrepresented as being the original software. // misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
function adler32(adler, buf, len, pos) { const adler32 = (adler, buf, len, pos) => {
var s1 = (adler & 0xffff) |0, let s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0,
n = 0; n = 0;
@ -45,7 +45,7 @@ function adler32(adler, buf, len, pos) {
} }
return (s1 | (s2 << 16)) |0; return (s1 | (s2 << 16)) |0;
} };
module.exports = adler32; module.exports = adler32;

View file

@ -24,8 +24,8 @@
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
// Use ordinary array, since untyped makes no boost here // Use ordinary array, since untyped makes no boost here
function makeTable() { const makeTable = () => {
var c, table = []; let c, table = [];
for (var n = 0; n < 256; n++) { for (var n = 0; n < 256; n++) {
c = n; c = n;
@ -36,24 +36,24 @@ function makeTable() {
} }
return table; return table;
} };
// Create table on load. Just 255 signed longs. Not a problem. // Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable(); const crcTable = new Uint32Array(makeTable());
function crc32(crc, buf, len, pos) { const crc32 = (crc, buf, len, pos) => {
var t = crcTable, const t = crcTable;
end = pos + len; const end = pos + len;
crc ^= -1; crc ^= -1;
for (var i = pos; i < end; i++) { for (let i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
} }
return (crc ^ (-1)); // >>> 0; return (crc ^ (-1)); // >>> 0;
} };
module.exports = crc32; module.exports = crc32;

View file

@ -19,118 +19,81 @@
// misrepresented as being the original software. // misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
var trees = require('./trees'); const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = require('./trees');
var adler32 = require('./adler32'); const adler32 = require('./adler32');
var crc32 = require('./crc32'); const crc32 = require('./crc32');
var msg = require('./messages'); const msg = require('./messages');
/* Public constants ==========================================================*/ /* Public constants ==========================================================*/
/* ===========================================================================*/ /* ===========================================================================*/
const {
/* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK,
var Z_NO_FLUSH = 0; Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,
var Z_PARTIAL_FLUSH = 1; Z_DEFAULT_COMPRESSION,
//var Z_SYNC_FLUSH = 2; Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY,
var Z_FULL_FLUSH = 3; Z_UNKNOWN,
var Z_FINISH = 4; Z_DEFLATED
var Z_BLOCK = 5; } = require('./constants');
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/ /*============================================================================*/
var MAX_MEM_LEVEL = 9; const MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */ /* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15; const MAX_WBITS = 15;
/* 32K LZ77 window */ /* 32K LZ77 window */
var DEF_MEM_LEVEL = 8; const DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29; const LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */ /* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256; const LITERALS = 256;
/* number of literal bytes 0..255 */ /* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES; const L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */ /* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30; const D_CODES = 30;
/* number of distance codes */ /* number of distance codes */
var BL_CODES = 19; const BL_CODES = 19;
/* number of codes used to transfer the bit lengths */ /* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1; const HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */ /* maximum heap size */
var MAX_BITS = 15; const MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */ /* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3; const MIN_MATCH = 3;
var MAX_MATCH = 258; const MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20; const PRESET_DICT = 0x20;
var INIT_STATE = 42; const INIT_STATE = 42;
var EXTRA_STATE = 69; const EXTRA_STATE = 69;
var NAME_STATE = 73; const NAME_STATE = 73;
var COMMENT_STATE = 91; const COMMENT_STATE = 91;
var HCRC_STATE = 103; const HCRC_STATE = 103;
var BUSY_STATE = 113; const BUSY_STATE = 113;
var FINISH_STATE = 666; const FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */ const BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) { const err = (strm, errorCode) => {
strm.msg = msg[errorCode]; strm.msg = msg[errorCode];
return errorCode; return errorCode;
} };
function rank(f) { const rank = (f) => {
return ((f) << 1) - ((f) > 4 ? 9 : 0); return ((f) << 1) - ((f) > 4 ? 9 : 0);
} };
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } const zero = (buf) => {
let len = buf.length; while (--len >= 0) { buf[len] = 0; }
};
/* ========================================================================= /* =========================================================================
@ -139,11 +102,11 @@ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; }
* to avoid allocating a large strm->output buffer and copying into it. * to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()). * (See also read_buf()).
*/ */
function flush_pending(strm) { const flush_pending = (strm) => {
var s = strm.state; const s = strm.state;
//_tr_flush_bits(s); //_tr_flush_bits(s);
var len = s.pending; let len = s.pending;
if (len > strm.avail_out) { if (len > strm.avail_out) {
len = strm.avail_out; len = strm.avail_out;
} }
@ -158,19 +121,19 @@ function flush_pending(strm) {
if (s.pending === 0) { if (s.pending === 0) {
s.pending_out = 0; s.pending_out = 0;
} }
} };
function flush_block_only(s, last) { const flush_block_only = (s, last) => {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart; s.block_start = s.strstart;
flush_pending(s.strm); flush_pending(s.strm);
} };
function put_byte(s, b) { const put_byte = (s, b) => {
s.pending_buf[s.pending++] = b; s.pending_buf[s.pending++] = b;
} };
/* ========================================================================= /* =========================================================================
@ -178,12 +141,13 @@ function put_byte(s, b) {
* IN assertion: the stream state is correct and there is enough room in * IN assertion: the stream state is correct and there is enough room in
* pending_buf. * pending_buf.
*/ */
function putShortMSB(s, b) { const putShortMSB = (s, b) => {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff)); // put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff; s.pending_buf[s.pending++] = b & 0xff;
} };
/* =========================================================================== /* ===========================================================================
@ -193,8 +157,9 @@ function putShortMSB(s, b) {
* allocating a large strm->input buffer and copying from it. * allocating a large strm->input buffer and copying from it.
* (See also flush_pending()). * (See also flush_pending()).
*/ */
function read_buf(strm, buf, start, size) { const read_buf = (strm, buf, start, size) => {
var len = strm.avail_in;
let len = strm.avail_in;
if (len > size) { len = size; } if (len > size) { len = size; }
if (len === 0) { return 0; } if (len === 0) { return 0; }
@ -215,7 +180,7 @@ function read_buf(strm, buf, start, size) {
strm.total_in += len; strm.total_in += len;
return len; return len;
} };
/* =========================================================================== /* ===========================================================================
@ -227,28 +192,29 @@ function read_buf(strm, buf, start, size) {
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead. * OUT assertion: the match length is not greater than s->lookahead.
*/ */
function longest_match(s, cur_match) { const longest_match = (s, cur_match) => {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */ let chain_length = s.max_chain_length; /* max hash chain length */
var match; /* matched string */ let scan = s.strstart; /* current string */
var len; /* length of current match */ let match; /* matched string */
var best_len = s.prev_length; /* best match length so far */ let len; /* length of current match */
var nice_match = s.nice_match; /* stop if match long enough */ let best_len = s.prev_length; /* best match length so far */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? let nice_match = s.nice_match; /* stop if match long enough */
const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut const _win = s.window; // shortcut
var wmask = s.w_mask; const wmask = s.w_mask;
var prev = s.prev; const prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code, /* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0. * we prevent matches with the string of window index 0.
*/ */
var strend = s.strstart + MAX_MATCH; const strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1]; let scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len]; let scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary. * It is easy to get rid of this optimization if necessary.
@ -327,7 +293,7 @@ function longest_match(s, cur_match) {
return best_len; return best_len;
} }
return s.lookahead; return s.lookahead;
} };
/* =========================================================================== /* ===========================================================================
@ -340,9 +306,10 @@ function longest_match(s, cur_match) {
* performed for at least two bytes (required for the zip translate_eol * performed for at least two bytes (required for the zip translate_eol
* option -- not supported here). * option -- not supported here).
*/ */
function fill_window(s) { const fill_window = (s) => {
var _w_size = s.w_size;
var p, n, m, more, str; const _w_size = s.w_size;
let p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
@ -384,6 +351,7 @@ function fill_window(s) {
n = s.hash_size; n = s.hash_size;
p = n; p = n;
do { do {
m = s.head[--p]; m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0); s.head[p] = (m >= _w_size ? m - _w_size : 0);
@ -391,6 +359,7 @@ function fill_window(s) {
n = _w_size; n = _w_size;
p = n; p = n;
do { do {
m = s.prev[--p]; m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0); s.prev[p] = (m >= _w_size ? m - _w_size : 0);
@ -457,8 +426,8 @@ function fill_window(s) {
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/ */
// if (s.high_water < s.window_size) { // if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead; // const curr = s.strstart + s.lookahead;
// var init = 0; // let init = 0;
// //
// if (s.high_water < curr) { // if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT // /* Previous high water mark below current data -- zero WIN_INIT
@ -485,7 +454,7 @@ function fill_window(s) {
// //
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search"); // "not enough room for search");
} };
/* =========================================================================== /* ===========================================================================
* Copy without compression as much as possible from the input stream, return * Copy without compression as much as possible from the input stream, return
@ -496,11 +465,12 @@ function fill_window(s) {
* NOTE: this function should be optimized to avoid extra copying from * NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf. * window to pending_buf.
*/ */
function deflate_stored(s, flush) { const deflate_stored = (s, flush) => {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header: * to pending_buf_size, and each stored block has a 5 byte header:
*/ */
var max_block_size = 0xffff; let max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) { if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5; max_block_size = s.pending_buf_size - 5;
@ -535,7 +505,7 @@ function deflate_stored(s, flush) {
s.lookahead = 0; s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */ /* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size; const max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) { if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */ /* strstart == 0 is possible when wraparound on 16-bit machine */
@ -585,7 +555,7 @@ function deflate_stored(s, flush) {
} }
return BS_NEED_MORE; return BS_NEED_MORE;
} };
/* =========================================================================== /* ===========================================================================
* Compress as much as possible from the input stream, return the current * Compress as much as possible from the input stream, return the current
@ -594,9 +564,10 @@ function deflate_stored(s, flush) {
* new strings in the dictionary only for unmatched strings or for short * new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options. * matches. It is used only for the fast compression options.
*/ */
function deflate_fast(s, flush) { const deflate_fast = (s, flush) => {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */ let hash_head; /* head of the hash chain */
let bflush; /* set if current block must be flushed */
for (;;) { for (;;) {
/* Make sure that we always have enough lookahead, except /* Make sure that we always have enough lookahead, except
@ -642,7 +613,7 @@ function deflate_fast(s, flush) {
/*** _tr_tally_dist(s, s.strstart - s.match_start, /*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/ s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length; s.lookahead -= s.match_length;
@ -682,7 +653,7 @@ function deflate_fast(s, flush) {
/* No match, output a literal byte */ /* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart])); //Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]); bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--; s.lookahead--;
s.strstart++; s.strstart++;
@ -715,18 +686,19 @@ function deflate_fast(s, flush) {
/***/ /***/
} }
return BS_BLOCK_DONE; return BS_BLOCK_DONE;
} };
/* =========================================================================== /* ===========================================================================
* Same as above, but achieves better compression. We use a lazy * Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is * evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position. * no better match at the next window position.
*/ */
function deflate_slow(s, flush) { const deflate_slow = (s, flush) => {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert; let hash_head; /* head of hash chain */
let bflush; /* set if current block must be flushed */
let max_insert;
/* Process the input block. */ /* Process the input block. */
for (;;) { for (;;) {
@ -790,7 +762,7 @@ function deflate_slow(s, flush) {
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/ s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match. /* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not * strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in * enough lookahead, the last two strings are not inserted in
@ -827,7 +799,7 @@ function deflate_slow(s, flush) {
*/ */
//Tracevv((stderr,"%c", s->window[s->strstart-1])); //Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
if (bflush) { if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/ /*** FLUSH_BLOCK_ONLY(s, 0) ***/
@ -852,7 +824,7 @@ function deflate_slow(s, flush) {
if (s.match_available) { if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1])); //Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
s.match_available = 0; s.match_available = 0;
} }
@ -876,7 +848,7 @@ function deflate_slow(s, flush) {
} }
return BS_BLOCK_DONE; return BS_BLOCK_DONE;
} };
/* =========================================================================== /* ===========================================================================
@ -884,12 +856,13 @@ function deflate_slow(s, flush) {
* one. Do not maintain a hash table. (It will be regenerated if this run of * one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.) * deflate switches away from Z_RLE.)
*/ */
function deflate_rle(s, flush) { const deflate_rle = (s, flush) => {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window; let bflush; /* set if current block must be flushed */
let prev; /* byte at distance one to match */
let scan, strend; /* scan goes up to strend for length of run */
const _win = s.window;
for (;;) { for (;;) {
/* Make sure that we always have enough lookahead, except /* Make sure that we always have enough lookahead, except
@ -931,7 +904,7 @@ function deflate_rle(s, flush) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length); //check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length; s.lookahead -= s.match_length;
s.strstart += s.match_length; s.strstart += s.match_length;
@ -940,7 +913,7 @@ function deflate_rle(s, flush) {
/* No match, output a literal byte */ /* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart])); //Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]); bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--; s.lookahead--;
s.strstart++; s.strstart++;
@ -973,14 +946,15 @@ function deflate_rle(s, flush) {
/***/ /***/
} }
return BS_BLOCK_DONE; return BS_BLOCK_DONE;
} };
/* =========================================================================== /* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.) * (It will be regenerated if this run of deflate switches away from Huffman.)
*/ */
function deflate_huff(s, flush) { const deflate_huff = (s, flush) => {
var bflush; /* set if current block must be flushed */
let bflush; /* set if current block must be flushed */
for (;;) { for (;;) {
/* Make sure that we have a literal to write. */ /* Make sure that we have a literal to write. */
@ -998,7 +972,7 @@ function deflate_huff(s, flush) {
s.match_length = 0; s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart])); //Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]); bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--; s.lookahead--;
s.strstart++; s.strstart++;
if (bflush) { if (bflush) {
@ -1029,7 +1003,7 @@ function deflate_huff(s, flush) {
/***/ /***/
} }
return BS_BLOCK_DONE; return BS_BLOCK_DONE;
} };
/* Values for max_lazy_match, good_match and max_chain_length, depending on /* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to * the desired pack level (0..9). The values given below have been tuned to
@ -1037,6 +1011,7 @@ function deflate_huff(s, flush) {
* found for specific files. * found for specific files.
*/ */
function Config(good_length, max_lazy, nice_length, max_chain, func) { function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length; this.good_length = good_length;
this.max_lazy = max_lazy; this.max_lazy = max_lazy;
this.nice_length = nice_length; this.nice_length = nice_length;
@ -1044,9 +1019,7 @@ function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.func = func; this.func = func;
} }
var configuration_table; const configuration_table = [
configuration_table = [
/* good lazy nice chain */ /* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
@ -1065,7 +1038,8 @@ configuration_table = [
/* =========================================================================== /* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream * Initialize the "longest match" routines for a new zlib stream
*/ */
function lm_init(s) { const lm_init = (s) => {
s.window_size = 2 * s.w_size; s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/ /*** CLEAR_HASH(s); ***/
@ -1085,7 +1059,7 @@ function lm_init(s) {
s.match_length = s.prev_length = MIN_MATCH - 1; s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0; s.match_available = 0;
s.ins_h = 0; s.ins_h = 0;
} };
function DeflateState() { function DeflateState() {
@ -1277,8 +1251,7 @@ function DeflateState() {
} }
function deflateResetKeep(strm) { const deflateResetKeep = (strm) => {
var s;
if (!strm || !strm.state) { if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR); return err(strm, Z_STREAM_ERROR);
@ -1287,7 +1260,7 @@ function deflateResetKeep(strm) {
strm.total_in = strm.total_out = 0; strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN; strm.data_type = Z_UNKNOWN;
s = strm.state; const s = strm.state;
s.pending = 0; s.pending = 0;
s.pending_out = 0; s.pending_out = 0;
@ -1301,33 +1274,36 @@ function deflateResetKeep(strm) {
: :
1; // adler32(0, Z_NULL, 0) 1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH; s.last_flush = Z_NO_FLUSH;
trees._tr_init(s); _tr_init(s);
return Z_OK; return Z_OK;
} };
function deflateReset(strm) { const deflateReset = (strm) => {
var ret = deflateResetKeep(strm);
const ret = deflateResetKeep(strm);
if (ret === Z_OK) { if (ret === Z_OK) {
lm_init(strm.state); lm_init(strm.state);
} }
return ret; return ret;
} };
function deflateSetHeader(strm, head) { const deflateSetHeader = (strm, head) => {
if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head; strm.state.gzhead = head;
return Z_OK; return Z_OK;
} };
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
if (!strm) { // === Z_NULL if (!strm) { // === Z_NULL
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
var wrap = 1; let wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) { if (level === Z_DEFAULT_COMPRESSION) {
level = 6; level = 6;
@ -1356,7 +1332,7 @@ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
} }
/* until 256-byte window bug fixed */ /* until 256-byte window bug fixed */
var s = new DeflateState(); const s = new DeflateState();
strm.state = s; strm.state = s;
s.strm = strm; s.strm = strm;
@ -1399,23 +1375,24 @@ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
s.method = method; s.method = method;
return deflateReset(strm); return deflateReset(strm);
} };
const deflateInit = (strm, level) => {
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
} };
function deflate(strm, flush) { const deflate = (strm, flush) => {
var old_flush, s;
var beg, val; // for gzip header write only let beg, val; // for gzip header write only
if (!strm || !strm.state || if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) { flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
} }
s = strm.state; const s = strm.state;
if (!strm.output || if (!strm.output ||
(!strm.input && strm.avail_in !== 0) || (!strm.input && strm.avail_in !== 0) ||
@ -1424,7 +1401,7 @@ function deflate(strm, flush) {
} }
s.strm = strm; /* just in case */ s.strm = strm; /* just in case */
old_flush = s.last_flush; const old_flush = s.last_flush;
s.last_flush = flush; s.last_flush = flush;
/* Write the header */ /* Write the header */
@ -1475,8 +1452,8 @@ function deflate(strm, flush) {
} }
else // DEFLATE header else // DEFLATE header
{ {
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1; let level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0; level_flags = 0;
@ -1659,7 +1636,7 @@ function deflate(strm, flush) {
*/ */
if (strm.avail_in !== 0 || s.lookahead !== 0 || if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush)); configuration_table[s.level].func(s, flush));
@ -1682,11 +1659,11 @@ function deflate(strm, flush) {
} }
if (bstate === BS_BLOCK_DONE) { if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) { if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s); _tr_align(s);
} }
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false); _tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized /* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync(). * as a special marker by inflate_sync().
*/ */
@ -1738,16 +1715,16 @@ function deflate(strm, flush) {
if (s.wrap > 0) { s.wrap = -s.wrap; } if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */ /* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END; return s.pending !== 0 ? Z_OK : Z_STREAM_END;
} };
function deflateEnd(strm) {
var status; const deflateEnd = (strm) => {
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
status = strm.state.status; const status = strm.state.status;
if (status !== INIT_STATE && if (status !== INIT_STATE &&
status !== EXTRA_STATE && status !== EXTRA_STATE &&
status !== NAME_STATE && status !== NAME_STATE &&
@ -1762,30 +1739,23 @@ function deflateEnd(strm) {
strm.state = null; strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
} };
/* ========================================================================= /* =========================================================================
* Initializes the compression dictionary from the given byte * Initializes the compression dictionary from the given byte
* sequence without producing any compressed output. * sequence without producing any compressed output.
*/ */
function deflateSetDictionary(strm, dictionary) { const deflateSetDictionary = (strm, dictionary) => {
var dictLength = dictionary.length;
var s; let dictLength = dictionary.length;
var str, n;
var wrap;
var avail;
var next;
var input;
var tmpDict;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
s = strm.state; const s = strm.state;
wrap = s.wrap; const wrap = s.wrap;
if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
@ -1810,22 +1780,22 @@ function deflateSetDictionary(strm, dictionary) {
} }
/* use the tail */ /* use the tail */
// dictionary = dictionary.slice(dictLength - s.w_size); // dictionary = dictionary.slice(dictLength - s.w_size);
tmpDict = new Uint8Array(s.w_size); let tmpDict = new Uint8Array(s.w_size);
tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0); tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
dictionary = tmpDict; dictionary = tmpDict;
dictLength = s.w_size; dictLength = s.w_size;
} }
/* insert dictionary into window and hash */ /* insert dictionary into window and hash */
avail = strm.avail_in; const avail = strm.avail_in;
next = strm.next_in; const next = strm.next_in;
input = strm.input; const input = strm.input;
strm.avail_in = dictLength; strm.avail_in = dictLength;
strm.next_in = 0; strm.next_in = 0;
strm.input = dictionary; strm.input = dictionary;
fill_window(s); fill_window(s);
while (s.lookahead >= MIN_MATCH) { while (s.lookahead >= MIN_MATCH) {
str = s.strstart; let str = s.strstart;
n = s.lookahead - (MIN_MATCH - 1); let n = s.lookahead - (MIN_MATCH - 1);
do { do {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
@ -1850,7 +1820,7 @@ function deflateSetDictionary(strm, dictionary) {
strm.avail_in = avail; strm.avail_in = avail;
s.wrap = wrap; s.wrap = wrap;
return Z_OK; return Z_OK;
} };
exports.deflateInit = deflateInit; exports.deflateInit = deflateInit;

View file

@ -20,8 +20,8 @@
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
// See state defs from inflate.js // See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */ const BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/* /*
Decode literal, length, and distance codes and write out the resulting Decode literal, length, and distance codes and write out the resulting
@ -59,39 +59,38 @@ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
output space. output space.
*/ */
module.exports = function inflate_fast(strm, start) { module.exports = function inflate_fast(strm, start) {
var state; let _in; /* local strm.input */
var _in; /* local strm.input */ let last; /* have enough input while in < last */
var last; /* have enough input while in < last */ let _out; /* local strm.output */
var _out; /* local strm.output */ let beg; /* inflate()'s initial strm.output */
var beg; /* inflate()'s initial strm.output */ let end; /* while out < end, enough space available */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT //#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */ let dmax; /* maximum distance from zlib header */
//#endif //#endif
var wsize; /* window size or zero if not using window */ let wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */ let whave; /* valid bytes in the window */
var wnext; /* window write index */ let wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools // Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */ let s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */ let hold; /* local strm.hold */
var bits; /* local strm.bits */ let bits; /* local strm.bits */
var lcode; /* local strm.lencode */ let lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */ let dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */ let lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */ let dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */ let here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */ let op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */ /* window position, window bytes to copy */
var len; /* match length, unused bytes */ let len; /* match length, unused bytes */
var dist; /* match distance */ let dist; /* match distance */
var from; /* where to copy match from */ let from; /* where to copy match from */
var from_source; let from_source;
var input, output; // JS specific, because we have no pointers let input, output; // JS specific, because we have no pointers
/* copy state to local variables */ /* copy state to local variables */
state = strm.state; const state = strm.state;
//here = state.here; //here = state.here;
_in = strm.next_in; _in = strm.next_in;
input = strm.input; input = strm.input;

View file

@ -19,102 +19,82 @@
// misrepresented as being the original software. // misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
var adler32 = require('./adler32'); const adler32 = require('./adler32');
var crc32 = require('./crc32'); const crc32 = require('./crc32');
var inflate_fast = require('./inffast'); const inflate_fast = require('./inffast');
var inflate_table = require('./inftrees'); const inflate_table = require('./inftrees');
var CODES = 0; const CODES = 0;
var LENS = 1; const LENS = 1;
var DISTS = 2; const DISTS = 2;
/* Public constants ==========================================================*/ /* Public constants ==========================================================*/
/* ===========================================================================*/ /* ===========================================================================*/
const {
/* Allowed flush values; see deflate() and inflate() below for details */ Z_FINISH, Z_BLOCK, Z_TREES,
//var Z_NO_FLUSH = 0; Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR, Z_BUF_ERROR,
//var Z_PARTIAL_FLUSH = 1; Z_DEFLATED
//var Z_SYNC_FLUSH = 2; } = require('./constants');
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/ /* STATES ====================================================================*/
/* ===========================================================================*/ /* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */ const HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */ const FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */ const TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */ const EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */ const NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */ const COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */ const HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */ const DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */ const DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */ const STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */ const COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */ const TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */ const LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */ const LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */ const LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */ const LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */ const DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */ const DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */ const MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */ const LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */ const CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */ const DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */ const BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */ const MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/ /* ===========================================================================*/
var ENOUGH_LENS = 852; const ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592; const ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15; const MAX_WBITS = 15;
/* 32K LZ77 window */ /* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS; const DEF_WBITS = MAX_WBITS;
function zswap32(q) { const zswap32 = (q) => {
return (((q >>> 24) & 0xff) + return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) + ((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) + ((q & 0xff00) << 8) +
((q & 0xff) << 24)); ((q & 0xff) << 24));
} };
function InflateState() { function InflateState() {
@ -175,11 +155,11 @@ function InflateState() {
this.was = 0; /* initial length of match */ this.was = 0; /* initial length of match */
} }
function inflateResetKeep(strm) {
var state; const inflateResetKeep = (strm) => {
if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state; const state = strm.state;
strm.total_in = strm.total_out = state.total = 0; strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/ strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */ if (state.wrap) { /* to support ill-conceived Java test suite */
@ -200,27 +180,27 @@ function inflateResetKeep(strm) {
state.back = -1; state.back = -1;
//Tracev((stderr, "inflate: reset\n")); //Tracev((stderr, "inflate: reset\n"));
return Z_OK; return Z_OK;
} };
function inflateReset(strm) {
var state; const inflateReset = (strm) => {
if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state; const state = strm.state;
state.wsize = 0; state.wsize = 0;
state.whave = 0; state.whave = 0;
state.wnext = 0; state.wnext = 0;
return inflateResetKeep(strm); return inflateResetKeep(strm);
} };
function inflateReset2(strm, windowBits) {
var wrap; const inflateReset2 = (strm, windowBits) => {
var state; let wrap;
/* get the state */ /* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state; const state = strm.state;
/* extract wrap request from windowBits parameter */ /* extract wrap request from windowBits parameter */
if (windowBits < 0) { if (windowBits < 0) {
@ -246,31 +226,32 @@ function inflateReset2(strm, windowBits) {
state.wrap = wrap; state.wrap = wrap;
state.wbits = windowBits; state.wbits = windowBits;
return inflateReset(strm); return inflateReset(strm);
} };
function inflateInit2(strm, windowBits) {
var ret; const inflateInit2 = (strm, windowBits) => {
var state;
if (!strm) { return Z_STREAM_ERROR; } if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */ //strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState(); const state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR; //if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n")); //Tracev((stderr, "inflate: allocated\n"));
strm.state = state; strm.state = state;
state.window = null/*Z_NULL*/; state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits); const ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) { if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/; strm.state = null/*Z_NULL*/;
} }
return ret; return ret;
} };
const inflateInit = (strm) => {
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS); return inflateInit2(strm, DEF_WBITS);
} };
/* /*
@ -283,20 +264,20 @@ function inflateInit(strm) {
used for threaded applications, since the rewriting of the tables and virgin used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe. may not be thread-safe.
*/ */
var virgin = true; let virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate let lenfix, distfix; // We have no pointers in JS, so keep tables separate
const fixedtables = (state) => {
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */ /* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) { if (virgin) {
var sym;
lenfix = new Int32Array(512); lenfix = new Int32Array(512);
distfix = new Int32Array(32); distfix = new Int32Array(32);
/* literal/length table */ /* literal/length table */
sym = 0; let sym = 0;
while (sym < 144) { state.lens[sym++] = 8; } while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; } while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; } while (sym < 280) { state.lens[sym++] = 7; }
@ -318,7 +299,7 @@ function fixedtables(state) {
state.lenbits = 9; state.lenbits = 9;
state.distcode = distfix; state.distcode = distfix;
state.distbits = 5; state.distbits = 5;
} };
/* /*
@ -335,9 +316,10 @@ function fixedtables(state) {
output will fall in the output data, making match copies simpler and faster. output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches. The advantage may be dependent on the size of the processor's data caches.
*/ */
function updatewindow(strm, src, end, copy) { const updatewindow = (strm, src, end, copy) => {
var dist;
var state = strm.state; let dist;
const state = strm.state;
/* if it hasn't been done already, allocate space for the window */ /* if it hasn't been done already, allocate space for the window */
if (state.window === null) { if (state.window === null) {
@ -375,33 +357,35 @@ function updatewindow(strm, src, end, copy) {
} }
} }
return 0; return 0;
} };
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS const inflate = (strm, flush) => {
var order = /* permutation of code lengths */ let state;
[ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; let input, output; // input/output buffers
let next; /* next input INDEX */
let put; /* next output INDEX */
let have, left; /* available input and output */
let hold; /* bit buffer */
let bits; /* bits in bit buffer */
let _in, _out; /* save starting available input and output */
let copy; /* number of stored or match bytes to copy */
let from; /* where to copy match bytes from */
let from_source;
let here = 0; /* current decoding table entry */
let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//let last; /* parent table entry */
let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
let len; /* length to copy for repeats, bits to drop */
let ret; /* return code */
const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */
let opts;
let n; // temporary variable for NEED_BITS
const order = /* permutation of code lengths */
new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);
if (!strm || !strm.state || !strm.output || if (!strm || !strm.state || !strm.output ||
@ -1467,42 +1451,44 @@ function inflate(strm, flush) {
ret = Z_BUF_ERROR; ret = Z_BUF_ERROR;
} }
return ret; return ret;
} };
function inflateEnd(strm) {
const inflateEnd = (strm) => {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
var state = strm.state; let state = strm.state;
if (state.window) { if (state.window) {
state.window = null; state.window = null;
} }
strm.state = null; strm.state = null;
return Z_OK; return Z_OK;
} };
function inflateGetHeader(strm, head) {
var state; const inflateGetHeader = (strm, head) => {
/* check state */ /* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state; const state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */ /* save header structure */
state.head = head; state.head = head;
head.done = false; head.done = false;
return Z_OK; return Z_OK;
} };
function inflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
var state; const inflateSetDictionary = (strm, dictionary) => {
var dictid; const dictLength = dictionary.length;
var ret;
let state;
let dictid;
let ret;
/* check state */ /* check state */
if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
@ -1531,7 +1517,8 @@ function inflateSetDictionary(strm, dictionary) {
state.havedict = 1; state.havedict = 1;
// Tracev((stderr, "inflate: dictionary set\n")); // Tracev((stderr, "inflate: dictionary set\n"));
return Z_OK; return Z_OK;
} };
exports.inflateReset = inflateReset; exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2; exports.inflateReset2 = inflateReset2;

View file

@ -19,66 +19,66 @@
// misrepresented as being the original software. // misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution. // 3. This notice may not be removed or altered from any source distribution.
var MAXBITS = 15; const MAXBITS = 15;
var ENOUGH_LENS = 852; const ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592; const ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0; const CODES = 0;
var LENS = 1; const LENS = 1;
var DISTS = 2; const DISTS = 2;
var lbase = [ /* Length codes 257..285 base */ const lbase = new Uint16Array([ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
]; ]);
var lext = [ /* Length codes 257..285 extra */ const lext = new Uint8Array([ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
]; ]);
var dbase = [ /* Distance codes 0..29 base */ const dbase = new Uint16Array([ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0 8193, 12289, 16385, 24577, 0, 0
]; ]);
var dext = [ /* Distance codes 0..29 extra */ const dext = new Uint8Array([ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64 28, 28, 29, 29, 64, 64
]; ]);
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>
{ {
var bits = opts.bits; const bits = opts.bits;
//here = opts.here; /* table entry for duplication */ //here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */ let len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */ let sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */ let min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */ let root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */ let curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */ let drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */ let left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */ let used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */ let huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */ let incr; /* for incrementing code, index */
var fill; /* index for replicating entries */ let fill; /* index for replicating entries */
var low; /* low bits for current root entry */ let low; /* low bits for current root entry */
var mask; /* mask for low root bits */ let mask; /* mask for low root bits */
var next; /* next available space in table */ let next; /* next available space in table */
var base = null; /* base value table to use */ let base = null; /* base value table to use */
var base_index = 0; let base_index = 0;
// var shoextra; /* extra bits table to use */ // let shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */ let end; /* use base and extra for symbol > end */
var count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null; let extra = null;
var extra_index = 0; let extra_index = 0;
var here_bits, here_op, here_val; let here_bits, here_op, here_val;
/* /*
Process a set of code lengths to create a canonical Huffman code. The Process a set of code lengths to create a canonical Huffman code. The
@ -339,3 +339,6 @@ module.exports = function inflate_table(type, lens, lens_index, codes, table, ta
opts.bits = root; opts.bits = root;
return 0; return 0;
}; };
module.exports = inflate_table;

View file

@ -25,32 +25,32 @@
/* ===========================================================================*/ /* ===========================================================================*/
//var Z_FILTERED = 1; //const Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2; //const Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3; //const Z_RLE = 3;
var Z_FIXED = 4; const Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0; //const Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */ /* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0; const Z_BINARY = 0;
var Z_TEXT = 1; const Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT //const Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2; const Z_UNKNOWN = 2;
/*============================================================================*/ /*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } function zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h // From zutil.h
var STORED_BLOCK = 0; const STORED_BLOCK = 0;
var STATIC_TREES = 1; const STATIC_TREES = 1;
var DYN_TREES = 2; const DYN_TREES = 2;
/* The three kinds of block type */ /* The three kinds of block type */
var MIN_MATCH = 3; const MIN_MATCH = 3;
var MAX_MATCH = 258; const MAX_MATCH = 258;
/* The minimum and maximum match lengths */ /* The minimum and maximum match lengths */
// From deflate.h // From deflate.h
@ -58,28 +58,28 @@ var MAX_MATCH = 258;
* Internal compression state. * Internal compression state.
*/ */
var LENGTH_CODES = 29; const LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */ /* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256; const LITERALS = 256;
/* number of literal bytes 0..255 */ /* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES; const L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */ /* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30; const D_CODES = 30;
/* number of distance codes */ /* number of distance codes */
var BL_CODES = 19; const BL_CODES = 19;
/* number of codes used to transfer the bit lengths */ /* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1; const HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */ /* maximum heap size */
var MAX_BITS = 15; const MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */ /* All codes must not exceed MAX_BITS bits */
var Buf_size = 16; const Buf_size = 16;
/* size of bit buffer in bi_buf */ /* size of bit buffer in bi_buf */
@ -87,33 +87,33 @@ var Buf_size = 16;
* Constants * Constants
*/ */
var MAX_BL_BITS = 7; const MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */ /* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256; const END_BLOCK = 256;
/* end of block literal code */ /* end of block literal code */
var REP_3_6 = 16; const REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */ /* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17; const REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */ /* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18; const REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */ /* repeat a zero length 11-138 times (7 bits of repeat count) */
/* eslint-disable comma-spacing,array-bracket-spacing */ /* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits = /* extra bits for each length code */ const extra_lbits = /* extra bits for each length code */
[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]; new Uint8Array([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]);
var extra_dbits = /* extra bits for each distance code */ const extra_dbits = /* extra bits for each distance code */
[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]; new Uint8Array([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]);
var extra_blbits = /* extra bits for each bit length code */ const extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);
var bl_order = const bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);
/* eslint-enable comma-spacing,array-bracket-spacing */ /* eslint-enable comma-spacing,array-bracket-spacing */
/* The lengths of the bit length codes are sent in order of decreasing /* The lengths of the bit length codes are sent in order of decreasing
@ -126,10 +126,10 @@ var bl_order =
// We pre-fill arrays with 0 to avoid uninitialized gaps // We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES + 2) * 2); const static_ltree = new Array((L_CODES + 2) * 2);
zero(static_ltree); zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no /* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However * need for the L_CODES extra codes used during heap construction. However
@ -137,28 +137,28 @@ zero(static_ltree);
* below). * below).
*/ */
var static_dtree = new Array(D_CODES * 2); const static_dtree = new Array(D_CODES * 2);
zero(static_dtree); zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use /* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.) * 5 bits.)
*/ */
var _dist_code = new Array(DIST_CODE_LEN); const _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code); zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances /* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of * 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances. * the 15 bit distances.
*/ */
var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code); zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */ /* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES); const base_length = new Array(LENGTH_CODES);
zero(base_length); zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */ /* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES); const base_dist = new Array(D_CODES);
zero(base_dist); zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */ /* First normalized distance for each code (0 = distance of 1) */
@ -176,9 +176,9 @@ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length)
} }
var static_l_desc; let static_l_desc;
var static_d_desc; let static_d_desc;
var static_bl_desc; let static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) { function TreeDesc(dyn_tree, stat_desc) {
@ -189,28 +189,30 @@ function TreeDesc(dyn_tree, stat_desc) {
function d_code(dist) { const d_code = (dist) => {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
} };
/* =========================================================================== /* ===========================================================================
* Output a short LSB first on the stream. * Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf. * IN assertion: there is enough room in pendingBuf.
*/ */
function put_short(s, w) { const put_short = (s, w) => {
// put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8)); // put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
} };
/* =========================================================================== /* ===========================================================================
* Send a value on a given number of bits. * Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits. * IN assertion: length <= 16 and value fits in length bits.
*/ */
function send_bits(s, value, length) { const send_bits = (s, value, length) => {
if (s.bi_valid > (Buf_size - length)) { if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf); put_short(s, s.bi_buf);
@ -220,12 +222,13 @@ function send_bits(s, value, length) {
s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length; s.bi_valid += length;
} }
} };
function send_code(s, c, tree) { const send_code = (s, c, tree) => {
send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
} };
/* =========================================================================== /* ===========================================================================
@ -233,21 +236,23 @@ function send_code(s, c, tree) {
* method would use a table) * method would use a table)
* IN assertion: 1 <= len <= 15 * IN assertion: 1 <= len <= 15
*/ */
function bi_reverse(code, len) { const bi_reverse = (code, len) => {
var res = 0;
let res = 0;
do { do {
res |= code & 1; res |= code & 1;
code >>>= 1; code >>>= 1;
res <<= 1; res <<= 1;
} while (--len > 0); } while (--len > 0);
return res >>> 1; return res >>> 1;
} };
/* =========================================================================== /* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it. * Flush the bit buffer, keeping at most 7 bits in it.
*/ */
function bi_flush(s) { const bi_flush = (s) => {
if (s.bi_valid === 16) { if (s.bi_valid === 16) {
put_short(s, s.bi_buf); put_short(s, s.bi_buf);
s.bi_buf = 0; s.bi_buf = 0;
@ -258,7 +263,7 @@ function bi_flush(s) {
s.bi_buf >>= 8; s.bi_buf >>= 8;
s.bi_valid -= 8; s.bi_valid -= 8;
} }
} };
/* =========================================================================== /* ===========================================================================
@ -271,23 +276,23 @@ function bi_flush(s) {
* The length opt_len is updated; static_len is also updated if stree is * The length opt_len is updated; static_len is also updated if stree is
* not null. * not null.
*/ */
function gen_bitlen(s, desc) const gen_bitlen = (s, desc) =>
// deflate_state *s; // deflate_state *s;
// tree_desc *desc; /* the tree descriptor */ // tree_desc *desc; /* the tree descriptor */
{ {
var tree = desc.dyn_tree; const tree = desc.dyn_tree;
var max_code = desc.max_code; const max_code = desc.max_code;
var stree = desc.stat_desc.static_tree; const stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree; const has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits; const extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base; const base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length; const max_length = desc.stat_desc.max_length;
var h; /* heap index */ let h; /* heap index */
var n, m; /* iterate over the tree elements */ let n, m; /* iterate over the tree elements */
var bits; /* bit length */ let bits; /* bit length */
var xbits; /* extra bits */ let xbits; /* extra bits */
var f; /* frequency */ let f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */ let overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) { for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0; s.bl_count[bits] = 0;
@ -357,7 +362,7 @@ function gen_bitlen(s, desc)
n--; n--;
} }
} }
} };
/* =========================================================================== /* ===========================================================================
@ -368,15 +373,15 @@ function gen_bitlen(s, desc)
* OUT assertion: the field code is set for all tree elements of non * OUT assertion: the field code is set for all tree elements of non
* zero code length. * zero code length.
*/ */
function gen_codes(tree, max_code, bl_count) const gen_codes = (tree, max_code, bl_count) =>
// ct_data *tree; /* the tree to decorate */ // ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */ // int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */ // ushf *bl_count; /* number of codes at each bit length */
{ {
var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
var code = 0; /* running code value */ let code = 0; /* running code value */
var bits; /* bit index */ let bits; /* bit index */
var n; /* code index */ let n; /* code index */
/* The distribution counts are first used to generate the code values /* The distribution counts are first used to generate the code values
* without bit reversal. * without bit reversal.
@ -392,7 +397,7 @@ function gen_codes(tree, max_code, bl_count)
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) { for (n = 0; n <= max_code; n++) {
var len = tree[n * 2 + 1]/*.Len*/; let len = tree[n * 2 + 1]/*.Len*/;
if (len === 0) { continue; } if (len === 0) { continue; }
/* Now reverse the bits */ /* Now reverse the bits */
tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
@ -400,19 +405,20 @@ function gen_codes(tree, max_code, bl_count)
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
} }
} };
/* =========================================================================== /* ===========================================================================
* Initialize the various 'constant' tables. * Initialize the various 'constant' tables.
*/ */
function tr_static_init() { const tr_static_init = () => {
var n; /* iterates over tree elements */
var bits; /* bit counter */ let n; /* iterates over tree elements */
var length; /* length value */ let bits; /* bit counter */
var code; /* code value */ let length; /* length value */
var dist; /* distance index */ let code; /* code value */
var bl_count = new Array(MAX_BITS + 1); let dist; /* distance index */
const bl_count = new Array(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */ /* number of codes at each bit length for an optimal tree */
// do check in _tr_init() // do check in _tr_init()
@ -504,14 +510,15 @@ function tr_static_init() {
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true; //static_init_done = true;
} };
/* =========================================================================== /* ===========================================================================
* Initialize a new block. * Initialize a new block.
*/ */
function init_block(s) { const init_block = (s) => {
var n; /* iterates over tree elements */
let n; /* iterates over tree elements */
/* Initialize the trees. */ /* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
@ -521,13 +528,13 @@ function init_block(s) {
s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0; s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0; s.last_lit = s.matches = 0;
} };
/* =========================================================================== /* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary * Flush the bit buffer and align the output on a byte boundary
*/ */
function bi_windup(s) const bi_windup = (s) =>
{ {
if (s.bi_valid > 8) { if (s.bi_valid > 8) {
put_short(s, s.bi_buf); put_short(s, s.bi_buf);
@ -537,13 +544,13 @@ function bi_windup(s)
} }
s.bi_buf = 0; s.bi_buf = 0;
s.bi_valid = 0; s.bi_valid = 0;
} };
/* =========================================================================== /* ===========================================================================
* Copy a stored block, storing first the length and its * Copy a stored block, storing first the length and its
* one's complement if requested. * one's complement if requested.
*/ */
function copy_block(s, buf, len, header) const copy_block = (s, buf, len, header) =>
//DeflateState *s; //DeflateState *s;
//charf *buf; /* the input data */ //charf *buf; /* the input data */
//unsigned len; /* its length */ //unsigned len; /* its length */
@ -560,18 +567,19 @@ function copy_block(s, buf, len, header)
// } // }
s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending); s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);
s.pending += len; s.pending += len;
} };
/* =========================================================================== /* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when * Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length. * the subtrees have equal frequency. This minimizes the worst case length.
*/ */
function smaller(tree, n, m, depth) { const smaller = (tree, n, m, depth) => {
var _n2 = n * 2;
var _m2 = m * 2; const _n2 = n * 2;
const _m2 = m * 2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
} };
/* =========================================================================== /* ===========================================================================
* Restore the heap property by moving down the tree starting at node k, * Restore the heap property by moving down the tree starting at node k,
@ -579,13 +587,13 @@ function smaller(tree, n, m, depth) {
* when the heap property is re-established (each father smaller than its * when the heap property is re-established (each father smaller than its
* two sons). * two sons).
*/ */
function pqdownheap(s, tree, k) const pqdownheap = (s, tree, k) =>
// deflate_state *s; // deflate_state *s;
// ct_data *tree; /* the tree to restore */ // ct_data *tree; /* the tree to restore */
// int k; /* node to move down */ // int k; /* node to move down */
{ {
var v = s.heap[k]; const v = s.heap[k];
var j = k << 1; /* left son of k */ let j = k << 1; /* left son of k */
while (j <= s.heap_len) { while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */ /* Set j to the smallest of the two sons: */
if (j < s.heap_len && if (j < s.heap_len &&
@ -603,25 +611,25 @@ function pqdownheap(s, tree, k)
j <<= 1; j <<= 1;
} }
s.heap[k] = v; s.heap[k] = v;
} };
// inlined manually // inlined manually
// var SMALLEST = 1; // const SMALLEST = 1;
/* =========================================================================== /* ===========================================================================
* Send the block data compressed using the given Huffman trees * Send the block data compressed using the given Huffman trees
*/ */
function compress_block(s, ltree, dtree) const compress_block = (s, ltree, dtree) =>
// deflate_state *s; // deflate_state *s;
// const ct_data *ltree; /* literal tree */ // const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */ // const ct_data *dtree; /* distance tree */
{ {
var dist; /* distance of matched string */ let dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */ let lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */ let lx = 0; /* running index in l_buf */
var code; /* the code to send */ let code; /* the code to send */
var extra; /* number of extra bits to send */ let extra; /* number of extra bits to send */
if (s.last_lit !== 0) { if (s.last_lit !== 0) {
do { do {
@ -661,7 +669,7 @@ function compress_block(s, ltree, dtree)
} }
send_code(s, END_BLOCK, ltree); send_code(s, END_BLOCK, ltree);
} };
/* =========================================================================== /* ===========================================================================
@ -672,17 +680,17 @@ function compress_block(s, ltree, dtree)
* and corresponding code. The length opt_len is updated; static_len is * and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set. * also updated if stree is not null. The field max_code is set.
*/ */
function build_tree(s, desc) const build_tree = (s, desc) =>
// deflate_state *s; // deflate_state *s;
// tree_desc *desc; /* the tree descriptor */ // tree_desc *desc; /* the tree descriptor */
{ {
var tree = desc.dyn_tree; const tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree; const stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree; const has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems; const elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */ let n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */ let max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */ let node; /* new node being created */
/* Construct the initial heap, with least frequent element in /* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
@ -761,27 +769,27 @@ function build_tree(s, desc)
/* The field len is now set, we can generate the bit codes */ /* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count); gen_codes(tree, max_code, s.bl_count);
} };
/* =========================================================================== /* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes * Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree. * in the bit length tree.
*/ */
function scan_tree(s, tree, max_code) const scan_tree = (s, tree, max_code) =>
// deflate_state *s; // deflate_state *s;
// ct_data *tree; /* the tree to be scanned */ // ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */ // int max_code; /* and its largest code of non zero frequency */
{ {
var n; /* iterates over all tree elements */ let n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */ let prevlen = -1; /* last emitted length */
var curlen; /* length of current code */ let curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */ let count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */ let max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */ let min_count = 4; /* min repeat count */
if (nextlen === 0) { if (nextlen === 0) {
max_count = 138; max_count = 138;
@ -827,27 +835,27 @@ function scan_tree(s, tree, max_code)
min_count = 4; min_count = 4;
} }
} }
} };
/* =========================================================================== /* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in * Send a literal or distance tree in compressed form, using the codes in
* bl_tree. * bl_tree.
*/ */
function send_tree(s, tree, max_code) const send_tree = (s, tree, max_code) =>
// deflate_state *s; // deflate_state *s;
// ct_data *tree; /* the tree to be scanned */ // ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */ // int max_code; /* and its largest code of non zero frequency */
{ {
var n; /* iterates over all tree elements */ let n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */ let prevlen = -1; /* last emitted length */
var curlen; /* length of current code */ let curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */ let count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */ let max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */ let min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */ /* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) { if (nextlen === 0) {
@ -898,15 +906,16 @@ function send_tree(s, tree, max_code)
min_count = 4; min_count = 4;
} }
} }
} };
/* =========================================================================== /* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in * Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send. * bl_order of the last bit length code to send.
*/ */
function build_bl_tree(s) { const build_bl_tree = (s) => {
var max_blindex; /* index of last bit length code of non zero freq */
let max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */ /* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
@ -933,7 +942,7 @@ function build_bl_tree(s) {
// s->opt_len, s->static_len)); // s->opt_len, s->static_len));
return max_blindex; return max_blindex;
} };
/* =========================================================================== /* ===========================================================================
@ -941,11 +950,11 @@ function build_bl_tree(s) {
* lengths of the bit length codes, the literal tree and the distance tree. * lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/ */
function send_all_trees(s, lcodes, dcodes, blcodes) const send_all_trees = (s, lcodes, dcodes, blcodes) =>
// deflate_state *s; // deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */ // int lcodes, dcodes, blcodes; /* number of codes for each tree */
{ {
var rank; /* index in bl_order */ let rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
@ -965,7 +974,7 @@ function send_all_trees(s, lcodes, dcodes, blcodes)
send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
} };
/* =========================================================================== /* ===========================================================================
@ -981,13 +990,13 @@ function send_all_trees(s, lcodes, dcodes, blcodes)
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set. * IN assertion: the fields Freq of dyn_ltree are set.
*/ */
function detect_data_type(s) { const detect_data_type = (s) => {
/* black_mask is the bit mask of black-listed bytes /* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31 * set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111 * 0xf3ffc07f = binary 11110011111111111100000001111111
*/ */
var black_mask = 0xf3ffc07f; let black_mask = 0xf3ffc07f;
var n; let n;
/* Check for non-textual ("black-listed") bytes. */ /* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) { for (n = 0; n <= 31; n++, black_mask >>>= 1) {
@ -1011,15 +1020,15 @@ function detect_data_type(s) {
* this stream either is empty or has tolerated ("gray-listed") bytes only. * this stream either is empty or has tolerated ("gray-listed") bytes only.
*/ */
return Z_BINARY; return Z_BINARY;
} };
var static_init_done = false; let static_init_done = false;
/* =========================================================================== /* ===========================================================================
* Initialize the tree data structures for a new zlib stream. * Initialize the tree data structures for a new zlib stream.
*/ */
function _tr_init(s) const _tr_init = (s) =>
{ {
if (!static_init_done) { if (!static_init_done) {
@ -1036,13 +1045,13 @@ function _tr_init(s)
/* Initialize the first block of the first file: */ /* Initialize the first block of the first file: */
init_block(s); init_block(s);
} };
/* =========================================================================== /* ===========================================================================
* Send a stored block * Send a stored block
*/ */
function _tr_stored_block(s, buf, stored_len, last) const _tr_stored_block = (s, buf, stored_len, last) =>
//DeflateState *s; //DeflateState *s;
//charf *buf; /* input block */ //charf *buf; /* input block */
//ulg stored_len; /* length of input block */ //ulg stored_len; /* length of input block */
@ -1050,32 +1059,32 @@ function _tr_stored_block(s, buf, stored_len, last)
{ {
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */ copy_block(s, buf, stored_len, true); /* with header */
} };
/* =========================================================================== /* ===========================================================================
* Send one empty static block to give enough lookahead for inflate. * Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer. * This takes 10 bits, of which 7 may remain in the bit buffer.
*/ */
function _tr_align(s) { const _tr_align = (s) => {
send_bits(s, STATIC_TREES << 1, 3); send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree); send_code(s, END_BLOCK, static_ltree);
bi_flush(s); bi_flush(s);
} };
/* =========================================================================== /* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static * Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file. * trees or store, and output the encoded block to the zip file.
*/ */
function _tr_flush_block(s, buf, stored_len, last) const _tr_flush_block = (s, buf, stored_len, last) =>
//DeflateState *s; //DeflateState *s;
//charf *buf; /* input block, or NULL if too old */ //charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */ //ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */ //int last; /* one if this is the last block for a file */
{ {
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */ let max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */ /* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) { if (s.level > 0) {
@ -1149,18 +1158,18 @@ function _tr_flush_block(s, buf, stored_len, last)
} }
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last)); // s->compressed_len-7*last));
} };
/* =========================================================================== /* ===========================================================================
* Save the match info and tally the frequency counts. Return true if * Save the match info and tally the frequency counts. Return true if
* the current block must be flushed. * the current block must be flushed.
*/ */
function _tr_tally(s, dist, lc) const _tr_tally = (s, dist, lc) =>
// deflate_state *s; // deflate_state *s;
// unsigned dist; /* distance of matched string */ // unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{ {
//var out_length, in_length, dcode; //let out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
@ -1211,7 +1220,7 @@ function _tr_tally(s, dist, lc)
* on 16 bit machines and because stored blocks are restricted to * on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes. * 64K-1 bytes.
*/ */
} };
exports._tr_init = _tr_init; exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block; exports._tr_stored_block = _tr_stored_block;

View file

@ -33,6 +33,8 @@
"prepublishOnly": "npm run gh-doc" "prepublishOnly": "npm run gh-doc"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-env": "^7.12.1",
"@rollup/plugin-babel": "^5.2.1",
"@rollup/plugin-commonjs": "^16.0.0", "@rollup/plugin-commonjs": "^16.0.0",
"@rollup/plugin-node-resolve": "^10.0.0", "@rollup/plugin-node-resolve": "^10.0.0",
"eslint": "^7.13.0", "eslint": "^7.13.0",

View file

@ -2,6 +2,8 @@ import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'; import commonjs from '@rollup/plugin-commonjs';
import pkg from './package.json'; import pkg from './package.json';
import { terser } from 'rollup-plugin-terser'; import { terser } from 'rollup-plugin-terser';
import babel from '@rollup/plugin-babel';
const banner = { const banner = {
banner() { banner() {
@ -10,8 +12,21 @@ const banner = {
} }
const plugins = [ nodeResolve(), commonjs(), banner ]; const plugins = [ nodeResolve(), commonjs(), banner ];
const plugins_es5 = [
nodeResolve(),
commonjs(),
babel({
babelHelpers: 'bundled',
presets: [
[ "@babel/preset-env" ]
]
}),
banner
];
export default [ export default [
// es6
{ {
input: 'index.js', input: 'index.js',
output: [ output: [
@ -35,5 +50,31 @@ export default [
{ file: 'dist/pako_inflate.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] } { file: 'dist/pako_inflate.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] }
], ],
plugins: plugins plugins: plugins
},
// es5
{
input: 'index.js',
output: [
{ file: 'dist/pako.es5.js', format: 'umd', name: 'pako' },
{ file: 'dist/pako.es5.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] }
],
plugins: plugins_es5
},
{
input: 'lib/deflate.js',
output: [
{ file: 'dist/pako_deflate.es5.js', format: 'umd', name: 'pako' },
{ file: 'dist/pako_deflate.es5.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] }
],
plugins: plugins_es5
},
{
input: 'lib/inflate.js',
output: [
{ file: 'dist/pako_inflate.es5.js', format: 'umd', name: 'pako' },
{ file: 'dist/pako_inflate.es5.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] }
],
plugins: plugins_es5
} }
]; ];

View file

@ -1,27 +1,27 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var helpers = require('./helpers'); const { loadSamples } = require('./helpers');
var pako = require('../index'); const pako = require('../index');
var samples = helpers.loadSamples(); const samples = loadSamples();
function randomBuf(size) { function randomBuf(size) {
var buf = new Uint8Array(size); const buf = new Uint8Array(size);
for (var i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
buf[i] = Math.round(Math.random() * 256); buf[i] = Math.round(Math.random() * 256);
} }
return buf; return buf;
} }
function testChunk(buf, expected, packer, chunkSize) { function testChunk(buf, expected, packer, chunkSize) {
var i, _in, count, pos, size, expFlushCount; let i, _in, count, pos, size, expFlushCount;
var onData = packer.onData; let onData = packer.onData;
var flushCount = 0; let flushCount = 0;
packer.onData = function () { packer.onData = function () {
flushCount++; flushCount++;
@ -46,51 +46,51 @@ function testChunk(buf, expected, packer, chunkSize) {
assert.strictEqual(flushCount, expFlushCount, 'onData called ' + flushCount + 'times, expected: ' + expFlushCount); assert.strictEqual(flushCount, expFlushCount, 'onData called ' + flushCount + 'times, expected: ' + expFlushCount);
} }
describe('Small input chunks', function () { describe('Small input chunks', () => {
it('deflate 100b by 1b chunk', function () { it('deflate 100b by 1b chunk', () => {
var buf = randomBuf(100); const buf = randomBuf(100);
var deflated = pako.deflate(buf); const deflated = pako.deflate(buf);
testChunk(buf, deflated, new pako.Deflate(), 1); testChunk(buf, deflated, new pako.Deflate(), 1);
}); });
it('deflate 20000b by 10b chunk', function () { it('deflate 20000b by 10b chunk', () => {
var buf = randomBuf(20000); const buf = randomBuf(20000);
var deflated = pako.deflate(buf); const deflated = pako.deflate(buf);
testChunk(buf, deflated, new pako.Deflate(), 10); testChunk(buf, deflated, new pako.Deflate(), 10);
}); });
it('inflate 100b result by 1b chunk', function () { it('inflate 100b result by 1b chunk', () => {
var buf = randomBuf(100); const buf = randomBuf(100);
var deflated = pako.deflate(buf); const deflated = pako.deflate(buf);
testChunk(deflated, buf, new pako.Inflate(), 1); testChunk(deflated, buf, new pako.Inflate(), 1);
}); });
it('inflate 20000b result by 10b chunk', function () { it('inflate 20000b result by 10b chunk', () => {
var buf = randomBuf(20000); const buf = randomBuf(20000);
var deflated = pako.deflate(buf); const deflated = pako.deflate(buf);
testChunk(deflated, buf, new pako.Inflate(), 10); testChunk(deflated, buf, new pako.Inflate(), 10);
}); });
}); });
describe('Dummy push (force end)', function () { describe('Dummy push (force end)', () => {
it('deflate end', function () { it('deflate end', () => {
var data = samples.lorem_utf_100k; const data = samples.lorem_utf_100k;
var deflator = new pako.Deflate(); const deflator = new pako.Deflate();
deflator.push(data); deflator.push(data);
deflator.push([], true); deflator.push([], true);
assert.deepStrictEqual(deflator.result, pako.deflate(data)); assert.deepStrictEqual(deflator.result, pako.deflate(data));
}); });
it('inflate end', function () { it('inflate end', () => {
var data = pako.deflate(samples.lorem_utf_100k); const data = pako.deflate(samples.lorem_utf_100k);
var inflator = new pako.Inflate(); const inflator = new pako.Inflate();
inflator.push(data); inflator.push(data);
inflator.push([], true); inflator.push([], true);
@ -100,19 +100,19 @@ describe('Dummy push (force end)', function () {
}); });
describe('Edge condition', function () { describe('Edge condition', () => {
it('should be ok on buffer border', function () { it('should be ok on buffer border', () => {
var i; let i;
var data = new Uint8Array(1024 * 16 + 1); const data = new Uint8Array(1024 * 16 + 1);
for (i = 0; i < data.length; i++) { for (i = 0; i < data.length; i++) {
data[i] = Math.floor(Math.random() * 255.999); data[i] = Math.floor(Math.random() * 255.999);
} }
var deflated = pako.deflate(data); const deflated = pako.deflate(data);
var inflator = new pako.Inflate(); const inflator = new pako.Inflate();
for (i = 0; i < deflated.length; i++) { for (i = 0; i < deflated.length; i++) {
inflator.push(deflated.subarray(i, i + 1), false); inflator.push(deflated.subarray(i, i + 1), false);

View file

@ -1,192 +1,191 @@
'use strict'; 'use strict';
var zlib = require('zlib'); const zlib = require('zlib');
var pako = require('../index'); const pako = require('../index');
var helpers = require('./helpers'); const { testSamples, loadSamples } = require('./helpers');
var testSamples = helpers.testSamples; const assert = require('assert');
var assert = require('assert'); const fs = require('fs');
var fs = require('fs'); const path = require('path');
var path = require('path');
var samples = helpers.loadSamples(); const samples = loadSamples();
describe('Deflate defaults', function () { describe('Deflate defaults', () => {
it('deflate, no options', function () { it('deflate, no options', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, {}); testSamples(zlib.deflateSync, pako.deflate, samples, {});
}); });
it('deflate raw, no options', function () { it('deflate raw, no options', () => {
testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, {}); testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, {});
}); });
// OS code in header can vary. Use hack flag to ignore it. // OS code in header can vary. Use hack flag to ignore it.
it('gzip, no options', function () { it('gzip, no options', () => {
testSamples(zlib.gzipSync, pako.gzip, samples, { ignore_os: true }); testSamples(zlib.gzipSync, pako.gzip, samples, { ignore_os: true });
}); });
}); });
describe('Deflate levels', function () { describe('Deflate levels', () => {
it('level 9', function () { it('level 9', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 9 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 9 });
}); });
it('level 8', function () { it('level 8', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 8 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 8 });
}); });
it('level 7', function () { it('level 7', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 7 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 7 });
}); });
it('level 6', function () { it('level 6', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 6 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 6 });
}); });
it('level 5', function () { it('level 5', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 5 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 5 });
}); });
it('level 4', function () { it('level 4', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 4 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 4 });
}); });
it('level 3', function () { it('level 3', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 3 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 3 });
}); });
it('level 2', function () { it('level 2', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 2 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 2 });
}); });
it('level 1', function () { it('level 1', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 1 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 1 });
}); });
it.skip('level 0', function () { it.skip('level 0', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: 0 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: 0 });
}); });
it('level -1 (implicit default)', function () { it('level -1 (implicit default)', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { level: -1 }); testSamples(zlib.deflateSync, pako.deflate, samples, { level: -1 });
}); });
}); });
describe('Deflate windowBits', function () { describe('Deflate windowBits', () => {
it('windowBits 15', function () { it('windowBits 15', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 15 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 15 });
}); });
it('windowBits 14', function () { it('windowBits 14', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 14 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 14 });
}); });
it('windowBits 13', function () { it('windowBits 13', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 13 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 13 });
}); });
it('windowBits 12', function () { it('windowBits 12', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 12 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 12 });
}); });
it('windowBits 11', function () { it('windowBits 11', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 11 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 11 });
}); });
it('windowBits 10', function () { it('windowBits 10', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 10 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 10 });
}); });
it('windowBits 9', function () { it('windowBits 9', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 9 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 9 });
}); });
it('windowBits 8', function () { it('windowBits 8', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 8 }); testSamples(zlib.deflateSync, pako.deflate, samples, { windowBits: 8 });
}); });
it('windowBits -15 (implicit raw)', function () { it('windowBits -15 (implicit raw)', () => {
testSamples(zlib.deflateRawSync, pako.deflate, samples, { windowBits: -15 }); testSamples(zlib.deflateRawSync, pako.deflate, samples, { windowBits: -15 });
}); });
}); });
describe('Deflate memLevel', function () { describe('Deflate memLevel', () => {
it('memLevel 9', function () { it('memLevel 9', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 9 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 9 });
}); });
it('memLevel 8', function () { it('memLevel 8', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 8 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 8 });
}); });
it('memLevel 7', function () { it('memLevel 7', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 7 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 7 });
}); });
it('memLevel 6', function () { it('memLevel 6', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 6 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 6 });
}); });
it('memLevel 5', function () { it('memLevel 5', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 5 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 5 });
}); });
it('memLevel 4', function () { it('memLevel 4', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 4 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 4 });
}); });
it('memLevel 3', function () { it('memLevel 3', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 3 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 3 });
}); });
it('memLevel 2', function () { it('memLevel 2', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 2 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 2 });
}); });
it('memLevel 1', function () { it('memLevel 1', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 1 }); testSamples(zlib.deflateSync, pako.deflate, samples, { memLevel: 1 });
}); });
}); });
describe('Deflate strategy', function () { describe('Deflate strategy', () => {
it('Z_DEFAULT_STRATEGY', function () { it('Z_DEFAULT_STRATEGY', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 0 }); testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 0 });
}); });
it('Z_FILTERED', function () { it('Z_FILTERED', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 1 }); testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 1 });
}); });
it('Z_HUFFMAN_ONLY', function () { it('Z_HUFFMAN_ONLY', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 2 }); testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 2 });
}); });
it('Z_RLE', function () { it('Z_RLE', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 3 }); testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 3 });
}); });
it('Z_FIXED', function () { it('Z_FIXED', () => {
testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 4 }); testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 4 });
}); });
}); });
describe('Deflate RAW', function () { describe('Deflate RAW', () => {
// Since difference is only in rwapper, test for store/fast/slow methods are enough // Since difference is only in rwapper, test for store/fast/slow methods are enough
it('level 4', function () { it('level 4', () => {
testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 4 }); testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 4 });
}); });
it('level 1', function () { it('level 1', () => {
testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 1 }); testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 1 });
}); });
it.skip('level 0', function () { it.skip('level 0', () => {
testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 0 }); testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 0 });
}); });
}); });
describe('Deflate dictionary', function () { describe('Deflate dictionary', () => {
it('trivial dictionary', function () { it('trivial dictionary', () => {
var dict = Buffer.from('abcdefghijklmnoprstuvwxyz'); const dict = Buffer.from('abcdefghijklmnoprstuvwxyz');
testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: dict }); testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: dict });
}); });
it('spdy dictionary', function () { it('spdy dictionary', () => {
var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt'));
testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: spdyDict }); testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: spdyDict });
}); });
it('handles multiple pushes', function () { it('handles multiple pushes', () => {
var dict = Buffer.from('abcd'); const dict = Buffer.from('abcd');
var deflate = new pako.Deflate({ dictionary: dict }); const deflate = new pako.Deflate({ dictionary: dict });
deflate.push(Buffer.from('hello'), false); deflate.push(Buffer.from('hello'), false);
deflate.push(Buffer.from('hello'), false); deflate.push(Buffer.from('hello'), false);
@ -194,7 +193,7 @@ describe('Deflate dictionary', function () {
if (deflate.err) { throw new Error(deflate.err); } if (deflate.err) { throw new Error(deflate.err); }
var uncompressed = pako.inflate(Buffer.from(deflate.result), { dictionary: dict }); const uncompressed = pako.inflate(Buffer.from(deflate.result), { dictionary: dict });
assert.deepStrictEqual( assert.deepStrictEqual(
new Uint8Array(Buffer.from('hellohello world')), new Uint8Array(Buffer.from('hellohello world')),
@ -204,12 +203,12 @@ describe('Deflate dictionary', function () {
}); });
describe('Deflate issues', function () { describe('Deflate issues', () => {
it('#78', function () { it('#78', () => {
var data = fs.readFileSync(path.join(__dirname, 'fixtures', 'issue_78.bin')); const data = fs.readFileSync(path.join(__dirname, 'fixtures', 'issue_78.bin'));
var deflatedPakoData = pako.deflate(data, { memLevel: 1 }); const deflatedPakoData = pako.deflate(data, { memLevel: 1 });
var inflatedPakoData = pako.inflate(deflatedPakoData); const inflatedPakoData = pako.inflate(deflatedPakoData);
assert.strictEqual(data.length, inflatedPakoData.length); assert.strictEqual(data.length, inflatedPakoData.length);
}); });

View file

@ -2,48 +2,48 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var c = require('../lib/zlib/constants'); const c = require('../lib/zlib/constants');
var msg = require('../lib/zlib/messages'); const msg = require('../lib/zlib/messages');
var zlib_deflate = require('../lib/zlib/deflate'); const zlib_deflate = require('../lib/zlib/deflate');
var ZStream = require('../lib/zlib/zstream'); const ZStream = require('../lib/zlib/zstream');
var pako = require('../index'); const pako = require('../index');
var short_sample = 'hello world'; const short_sample = 'hello world';
var long_sample = fs.readFileSync(path.join(__dirname, 'fixtures/samples/lorem_en_100k.txt')); const long_sample = fs.readFileSync(path.join(__dirname, 'fixtures/samples/lorem_en_100k.txt'));
function testDeflate(data, opts, flush) { function testDeflate(data, opts, flush) {
var deflator = new pako.Deflate(opts); const deflator = new pako.Deflate(opts);
deflator.push(data, flush); deflator.push(data, flush);
deflator.push(data, true); deflator.push(data, true);
assert.strictEqual(deflator.err, 0, msg[deflator.err]); assert.strictEqual(deflator.err, 0, msg[deflator.err]);
} }
describe('Deflate support', function () { describe('Deflate support', () => {
it('stored', function () { it('stored', () => {
testDeflate(short_sample, { level: 0, chunkSize: 200 }, 0); testDeflate(short_sample, { level: 0, chunkSize: 200 }, 0);
testDeflate(short_sample, { level: 0, chunkSize: 10 }, 5); testDeflate(short_sample, { level: 0, chunkSize: 10 }, 5);
}); });
it('fast', function () { it('fast', () => {
testDeflate(short_sample, { level: 1, chunkSize: 10 }, 5); testDeflate(short_sample, { level: 1, chunkSize: 10 }, 5);
testDeflate(long_sample, { level: 1, memLevel: 1, chunkSize: 10 }, 0); testDeflate(long_sample, { level: 1, memLevel: 1, chunkSize: 10 }, 0);
}); });
it('slow', function () { it('slow', () => {
testDeflate(short_sample, { level: 4, chunkSize: 10 }, 5); testDeflate(short_sample, { level: 4, chunkSize: 10 }, 5);
testDeflate(long_sample, { level: 9, memLevel: 1, chunkSize: 10 }, 0); testDeflate(long_sample, { level: 9, memLevel: 1, chunkSize: 10 }, 0);
}); });
it('rle', function () { it('rle', () => {
testDeflate(short_sample, { strategy: 3 }, 0); testDeflate(short_sample, { strategy: 3 }, 0);
testDeflate(short_sample, { strategy: 3, chunkSize: 10 }, 5); testDeflate(short_sample, { strategy: 3, chunkSize: 10 }, 5);
testDeflate(long_sample, { strategy: 3, chunkSize: 10 }, 0); testDeflate(long_sample, { strategy: 3, chunkSize: 10 }, 0);
}); });
it('huffman', function () { it('huffman', () => {
testDeflate(short_sample, { strategy: 2 }, 0); testDeflate(short_sample, { strategy: 2 }, 0);
testDeflate(short_sample, { strategy: 2, chunkSize: 10 }, 5); testDeflate(short_sample, { strategy: 2, chunkSize: 10 }, 5);
testDeflate(long_sample, { strategy: 2, chunkSize: 10 }, 0); testDeflate(long_sample, { strategy: 2, chunkSize: 10 }, 0);
@ -51,10 +51,10 @@ describe('Deflate support', function () {
}); });
}); });
describe('Deflate states', function () { describe('Deflate states', () => {
//in port checking input parameters was removed //in port checking input parameters was removed
it('inflate bad parameters', function () { it('inflate bad parameters', () => {
var ret, strm; let ret, strm;
ret = zlib_deflate.deflate(null, 0); ret = zlib_deflate.deflate(null, 0);
assert(ret === c.Z_STREAM_ERROR); assert(ret === c.Z_STREAM_ERROR);

View file

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var assert = require('assert'); const assert = require('assert');
var pako = require('../index'); const pako = require('../index');
function a2s(array) { function a2s(array) {
@ -13,11 +13,11 @@ function a2s(array) {
} }
describe('Gzip special cases', function () { describe('Gzip special cases', () => {
it('Read custom headers', function () { it('Read custom headers', () => {
var data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-headers.gz')); const data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-headers.gz'));
var inflator = new pako.Inflate(); const inflator = new pako.Inflate();
inflator.push(data, true); inflator.push(data, true);
assert.strictEqual(inflator.header.name, 'test name'); assert.strictEqual(inflator.header.name, 'test name');
@ -25,10 +25,10 @@ describe('Gzip special cases', function () {
assert.strictEqual(a2s(inflator.header.extra), 'test extra'); assert.strictEqual(a2s(inflator.header.extra), 'test extra');
}); });
it('Write custom headers', function () { it('Write custom headers', () => {
var data = ' '; const data = ' ';
var deflator = new pako.Deflate({ const deflator = new pako.Deflate({
gzip: true, gzip: true,
header: { header: {
hcrc: true, hcrc: true,
@ -41,13 +41,13 @@ describe('Gzip special cases', function () {
}); });
deflator.push(data, true); deflator.push(data, true);
var inflator = new pako.Inflate({ to: 'string' }); const inflator = new pako.Inflate({ to: 'string' });
inflator.push(deflator.result, true); inflator.push(deflator.result, true);
assert.strictEqual(inflator.err, 0); assert.strictEqual(inflator.err, 0);
assert.strictEqual(inflator.result, data); assert.strictEqual(inflator.result, data);
var header = inflator.header; const header = inflator.header;
assert.strictEqual(header.time, 1234567); assert.strictEqual(header.time, 1234567);
assert.strictEqual(header.os, 15); assert.strictEqual(header.os, 15);
assert.strictEqual(header.name, 'test name'); assert.strictEqual(header.name, 'test name');
@ -55,9 +55,9 @@ describe('Gzip special cases', function () {
assert.deepStrictEqual(header.extra, new Uint8Array([ 4, 5, 6 ])); assert.deepStrictEqual(header.extra, new Uint8Array([ 4, 5, 6 ]));
}); });
it('Read stream with SYNC marks', function () { it('Read stream with SYNC marks', () => {
var inflator, strm, _in, len, pos = 0, i = 0; let inflator, strm, _in, len, pos = 0, i = 0;
var data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-joined.gz')); const data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-joined.gz'));
do { do {
len = data.length - pos; len = data.length - pos;

View file

@ -1,24 +1,24 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var assert = require('assert'); const assert = require('assert');
var pako = require('../index'); const pako = require('../index');
// Load fixtures to test // Load fixtures to test
// return: { 'filename1': content1, 'filename2': content2, ...} // return: { 'filename1': content1, 'filename2': content2, ...}
// //
function loadSamples(subdir) { function loadSamples(subdir) {
var result = {}; const result = {};
var dir = path.join(__dirname, 'fixtures', subdir || 'samples'); const dir = path.join(__dirname, 'fixtures', subdir || 'samples');
fs.readdirSync(dir).sort().forEach(function (sample) { fs.readdirSync(dir).sort().forEach(function (sample) {
var filepath = path.join(dir, sample), const filepath = path.join(dir, sample);
extname = path.extname(filepath), const extname = path.extname(filepath);
basename = path.basename(filepath, extname), const basename = path.basename(filepath, extname);
content = new Uint8Array(fs.readFileSync(filepath)); const content = new Uint8Array(fs.readFileSync(filepath));
if (basename[0] === '_') { return; } // skip files with name, started with dash if (basename[0] === '_') { return; } // skip files with name, started with dash
@ -33,13 +33,13 @@ function loadSamples(subdir) {
// Use zlib streams, because it's the only way to define options. // Use zlib streams, because it's the only way to define options.
// //
function testSingle(zlib_method, pako_method, data, options) { function testSingle(zlib_method, pako_method, data, options) {
var zlib_options = Object.assign({}, options); const zlib_options = Object.assign({}, options);
// hack for testing negative windowBits // hack for testing negative windowBits
if (zlib_options.windowBits < 0) { zlib_options.windowBits = -zlib_options.windowBits; } if (zlib_options.windowBits < 0) { zlib_options.windowBits = -zlib_options.windowBits; }
var zlib_result = zlib_method(data, zlib_options); const zlib_result = zlib_method(data, zlib_options);
var pako_result = pako_method(data, options); const pako_result = pako_method(data, options);
// One more hack: gzip header contains OS code, that can vary. // One more hack: gzip header contains OS code, that can vary.
// Override OS code if requested. For simplicity, we assume it on fixed // Override OS code if requested. For simplicity, we assume it on fixed
@ -53,7 +53,7 @@ function testSingle(zlib_method, pako_method, data, options) {
function testSamples(zlib_method, pako_method, samples, options) { function testSamples(zlib_method, pako_method, samples, options) {
Object.keys(samples).forEach(function (name) { Object.keys(samples).forEach(function (name) {
var data = samples[name]; const data = samples[name];
testSingle(zlib_method, pako_method, data, options); testSingle(zlib_method, pako_method, data, options);
}); });
@ -61,7 +61,7 @@ function testSamples(zlib_method, pako_method, samples, options) {
function testInflate(samples, inflateOptions, deflateOptions) { function testInflate(samples, inflateOptions, deflateOptions) {
var name, data, deflated, inflated; let name, data, deflated, inflated;
// inflate options have windowBits = 0 to force autodetect window size // inflate options have windowBits = 0 to force autodetect window size
// //
@ -77,6 +77,6 @@ function testInflate(samples, inflateOptions, deflateOptions) {
} }
exports.testSamples = testSamples; module.exports.testSamples = testSamples;
exports.testInflate = testInflate; module.exports.testInflate = testInflate;
exports.loadSamples = loadSamples; module.exports.loadSamples = loadSamples;

View file

@ -1,209 +1,208 @@
'use strict'; 'use strict';
var zlib = require('zlib'); const zlib = require('zlib');
var assert = require('assert'); const assert = require('assert');
var pako = require('../index'); const pako = require('../index');
var helpers = require('./helpers'); const { testInflate, testSamples, loadSamples } = require('./helpers');
var testInflate = helpers.testInflate;
var samples = helpers.loadSamples(); const samples = loadSamples();
describe('Inflate defaults', function () { describe('Inflate defaults', () => {
it('inflate, no options', function () { it('inflate, no options', () => {
testInflate(samples, {}, {}); testInflate(samples, {}, {});
}); });
it('inflate raw, no options', function () { it('inflate raw, no options', () => {
testInflate(samples, { raw: true }, { raw: true }); testInflate(samples, { raw: true }, { raw: true });
}); });
it('inflate raw from compressed samples', function () { it('inflate raw from compressed samples', () => {
var compressed_samples = helpers.loadSamples('samples_deflated_raw'); const compressed_samples = loadSamples('samples_deflated_raw');
helpers.testSamples(zlib.inflateRawSync, pako.inflateRaw, compressed_samples, {}); testSamples(zlib.inflateRawSync, pako.inflateRaw, compressed_samples, {});
}); });
}); });
describe('Inflate ungzip', function () { describe('Inflate ungzip', () => {
it('with autodetect', function () { it('with autodetect', () => {
testInflate(samples, {}, { gzip: true }); testInflate(samples, {}, { gzip: true });
}); });
it('with method set directly', function () { it('with method set directly', () => {
testInflate(samples, { windowBits: 16 }, { gzip: true }); testInflate(samples, { windowBits: 16 }, { gzip: true });
}); });
}); });
describe('Inflate levels', function () { describe('Inflate levels', () => {
it('level 9', function () { it('level 9', () => {
testInflate(samples, {}, { level: 9 }); testInflate(samples, {}, { level: 9 });
}); });
it('level 8', function () { it('level 8', () => {
testInflate(samples, {}, { level: 8 }); testInflate(samples, {}, { level: 8 });
}); });
it('level 7', function () { it('level 7', () => {
testInflate(samples, {}, { level: 7 }); testInflate(samples, {}, { level: 7 });
}); });
it('level 6', function () { it('level 6', () => {
testInflate(samples, {}, { level: 6 }); testInflate(samples, {}, { level: 6 });
}); });
it('level 5', function () { it('level 5', () => {
testInflate(samples, {}, { level: 5 }); testInflate(samples, {}, { level: 5 });
}); });
it('level 4', function () { it('level 4', () => {
testInflate(samples, {}, { level: 4 }); testInflate(samples, {}, { level: 4 });
}); });
it('level 3', function () { it('level 3', () => {
testInflate(samples, {}, { level: 3 }); testInflate(samples, {}, { level: 3 });
}); });
it('level 2', function () { it('level 2', () => {
testInflate(samples, {}, { level: 2 }); testInflate(samples, {}, { level: 2 });
}); });
it('level 1', function () { it('level 1', () => {
testInflate(samples, {}, { level: 1 }); testInflate(samples, {}, { level: 1 });
}); });
it('level 0', function () { it('level 0', () => {
testInflate(samples, {}, { level: 0 }); testInflate(samples, {}, { level: 0 });
}); });
}); });
describe('Inflate windowBits', function () { describe('Inflate windowBits', () => {
it('windowBits 15', function () { it('windowBits 15', () => {
testInflate(samples, {}, { windowBits: 15 }); testInflate(samples, {}, { windowBits: 15 });
}); });
it('windowBits 14', function () { it('windowBits 14', () => {
testInflate(samples, {}, { windowBits: 14 }); testInflate(samples, {}, { windowBits: 14 });
}); });
it('windowBits 13', function () { it('windowBits 13', () => {
testInflate(samples, {}, { windowBits: 13 }); testInflate(samples, {}, { windowBits: 13 });
}); });
it('windowBits 12', function () { it('windowBits 12', () => {
testInflate(samples, {}, { windowBits: 12 }); testInflate(samples, {}, { windowBits: 12 });
}); });
it('windowBits 11', function () { it('windowBits 11', () => {
testInflate(samples, {}, { windowBits: 11 }); testInflate(samples, {}, { windowBits: 11 });
}); });
it('windowBits 10', function () { it('windowBits 10', () => {
testInflate(samples, {}, { windowBits: 10 }); testInflate(samples, {}, { windowBits: 10 });
}); });
it('windowBits 9', function () { it('windowBits 9', () => {
testInflate(samples, {}, { windowBits: 9 }); testInflate(samples, {}, { windowBits: 9 });
}); });
it('windowBits 8', function () { it('windowBits 8', () => {
testInflate(samples, {}, { windowBits: 8 }); testInflate(samples, {}, { windowBits: 8 });
}); });
}); });
describe('Inflate strategy', function () { describe('Inflate strategy', () => {
it('Z_DEFAULT_STRATEGY', function () { it('Z_DEFAULT_STRATEGY', () => {
testInflate(samples, {}, { strategy: 0 }); testInflate(samples, {}, { strategy: 0 });
}); });
it('Z_FILTERED', function () { it('Z_FILTERED', () => {
testInflate(samples, {}, { strategy: 1 }); testInflate(samples, {}, { strategy: 1 });
}); });
it('Z_HUFFMAN_ONLY', function () { it('Z_HUFFMAN_ONLY', () => {
testInflate(samples, {}, { strategy: 2 }); testInflate(samples, {}, { strategy: 2 });
}); });
it('Z_RLE', function () { it('Z_RLE', () => {
testInflate(samples, {}, { strategy: 3 }); testInflate(samples, {}, { strategy: 3 });
}); });
it('Z_FIXED', function () { it('Z_FIXED', () => {
testInflate(samples, {}, { strategy: 4 }); testInflate(samples, {}, { strategy: 4 });
}); });
}); });
describe('Inflate RAW', function () { describe('Inflate RAW', () => {
// Since difference is only in rwapper, test for store/fast/slow methods are enough // Since difference is only in rwapper, test for store/fast/slow methods are enough
it('level 9', function () { it('level 9', () => {
testInflate(samples, { raw: true }, { level: 9, raw: true }); testInflate(samples, { raw: true }, { level: 9, raw: true });
}); });
it('level 8', function () { it('level 8', () => {
testInflate(samples, { raw: true }, { level: 8, raw: true }); testInflate(samples, { raw: true }, { level: 8, raw: true });
}); });
it('level 7', function () { it('level 7', () => {
testInflate(samples, { raw: true }, { level: 7, raw: true }); testInflate(samples, { raw: true }, { level: 7, raw: true });
}); });
it('level 6', function () { it('level 6', () => {
testInflate(samples, { raw: true }, { level: 6, raw: true }); testInflate(samples, { raw: true }, { level: 6, raw: true });
}); });
it('level 5', function () { it('level 5', () => {
testInflate(samples, { raw: true }, { level: 5, raw: true }); testInflate(samples, { raw: true }, { level: 5, raw: true });
}); });
it('level 4', function () { it('level 4', () => {
testInflate(samples, { raw: true }, { level: 4, raw: true }); testInflate(samples, { raw: true }, { level: 4, raw: true });
}); });
it('level 3', function () { it('level 3', () => {
testInflate(samples, { raw: true }, { level: 3, raw: true }); testInflate(samples, { raw: true }, { level: 3, raw: true });
}); });
it('level 2', function () { it('level 2', () => {
testInflate(samples, { raw: true }, { level: 2, raw: true }); testInflate(samples, { raw: true }, { level: 2, raw: true });
}); });
it('level 1', function () { it('level 1', () => {
testInflate(samples, { raw: true }, { level: 1, raw: true }); testInflate(samples, { raw: true }, { level: 1, raw: true });
}); });
it('level 0', function () { it('level 0', () => {
testInflate(samples, { raw: true }, { level: 0, raw: true }); testInflate(samples, { raw: true }, { level: 0, raw: true });
}); });
}); });
describe('Inflate with dictionary', function () { describe('Inflate with dictionary', () => {
it('should throw on the wrong dictionary', function () { it('should throw on the wrong dictionary', () => {
// var zCompressed = helpers.deflateSync('world', { dictionary: Buffer.from('hello') }); // const zCompressed = helpers.deflateSync('world', { dictionary: Buffer.from('hello') });
var zCompressed = new Uint8Array([ 120, 187, 6, 44, 2, 21, 43, 207, 47, 202, 73, 1, 0, 6, 166, 2, 41 ]); const zCompressed = new Uint8Array([ 120, 187, 6, 44, 2, 21, 43, 207, 47, 202, 73, 1, 0, 6, 166, 2, 41 ]);
assert.throws(function () { assert.throws(function () {
pako.inflate(zCompressed, { dictionary: 'world' }); pako.inflate(zCompressed, { dictionary: 'world' });
}, /data error/); }, /data error/);
}); });
it('trivial dictionary', function () { it('trivial dictionary', () => {
var dict = 'abcdefghijklmnoprstuvwxyz'; const dict = 'abcdefghijklmnoprstuvwxyz';
testInflate(samples, { dictionary: dict }, { dictionary: dict }); testInflate(samples, { dictionary: dict }, { dictionary: dict });
}); });
it('spdy dictionary', function () { it('spdy dictionary', () => {
var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt'));
testInflate(samples, { dictionary: spdyDict }, { dictionary: spdyDict }); testInflate(samples, { dictionary: spdyDict }, { dictionary: spdyDict });
}); });
it('should throw if directory is not supplied to raw inflate', function () { it('should throw if directory is not supplied to raw inflate', () => {
var dict = 'abcdefghijklmnoprstuvwxyz'; const dict = 'abcdefghijklmnoprstuvwxyz';
assert.throws(function () { assert.throws(function () {
testInflate(samples, { raw: true }, { raw: true, dictionary: dict }); testInflate(samples, { raw: true }, { raw: true, dictionary: dict });
}); });
}); });
it('tests raw inflate with spdy dictionary', function () { it('tests raw inflate with spdy dictionary', () => {
var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt'));
testInflate(samples, { raw: true, dictionary: spdyDict }, { raw: true, dictionary: spdyDict }); testInflate(samples, { raw: true, dictionary: spdyDict }, { raw: true, dictionary: spdyDict });
}); });
it('tests dictionary as Uint8Array', function () { it('tests dictionary as Uint8Array', () => {
var dict = new Uint8Array(100); const dict = new Uint8Array(100);
for (var i = 0; i < 100; i++) dict[i] = Math.random() * 256; for (let i = 0; i < 100; i++) dict[i] = Math.random() * 256;
testInflate(samples, { dictionary: dict }, { dictionary: dict }); testInflate(samples, { dictionary: dict }, { dictionary: dict });
}); });
it('tests dictionary as ArrayBuffer', function () { it('tests dictionary as ArrayBuffer', () => {
var dict = new Uint8Array(100); const dict = new Uint8Array(100);
for (var i = 0; i < 100; i++) dict[i] = Math.random() * 256; for (let i = 0; i < 100; i++) dict[i] = Math.random() * 256;
testInflate(samples, { dictionary: dict.buffer }, { dictionary: dict }); testInflate(samples, { dictionary: dict.buffer }, { dictionary: dict });
}); });
}); });

View file

@ -2,15 +2,15 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var c = require('../lib/zlib/constants'); const c = require('../lib/zlib/constants');
var msg = require('../lib/zlib/messages'); const msg = require('../lib/zlib/messages');
//var zlib_stream = require('../lib/zlib/zstream'); //const zlib_stream = require('../lib/zlib/zstream');
var zlib_inflate = require('../lib/zlib/inflate'); const zlib_inflate = require('../lib/zlib/inflate');
var inflate_table = require('../lib/zlib/inftrees'); const inflate_table = require('../lib/zlib/inftrees');
var pako = require('../index'); const pako = require('../index');
function h2b(hex) { function h2b(hex) {
@ -21,7 +21,7 @@ function h2b(hex) {
//step argument from original tests is missing because it have no effect //step argument from original tests is missing because it have no effect
//we have similar behavior in chunks.js tests //we have similar behavior in chunks.js tests
function testInflate(hex, wbits, status) { function testInflate(hex, wbits, status) {
var inflator; let inflator;
try { try {
inflator = new pako.Inflate({ windowBits: wbits }); inflator = new pako.Inflate({ windowBits: wbits });
} catch (e) { } catch (e) {
@ -33,12 +33,11 @@ function testInflate(hex, wbits, status) {
} }
describe('Inflate states', function () { describe('Inflate states', () => {
//in port checking input parameters was removed //in port checking input parameters was removed
it('inflate bad parameters', function () { it('inflate bad parameters', () => {
var ret;
ret = zlib_inflate.inflate(null, 0); let ret = zlib_inflate.inflate(null, 0);
assert(ret === c.Z_STREAM_ERROR); assert(ret === c.Z_STREAM_ERROR);
ret = zlib_inflate.inflateEnd(null); ret = zlib_inflate.inflateEnd(null);
@ -48,115 +47,115 @@ describe('Inflate states', function () {
//ret = zlib_inflate.inflateCopy(null, null); //ret = zlib_inflate.inflateCopy(null, null);
//assert(ret == c.Z_STREAM_ERROR); //assert(ret == c.Z_STREAM_ERROR);
}); });
it('bad gzip method', function () { it('bad gzip method', () => {
testInflate('1f 8b 0 0', 31, c.Z_DATA_ERROR); testInflate('1f 8b 0 0', 31, c.Z_DATA_ERROR);
}); });
it('bad gzip flags', function () { it('bad gzip flags', () => {
testInflate('1f 8b 8 80', 31, c.Z_DATA_ERROR); testInflate('1f 8b 8 80', 31, c.Z_DATA_ERROR);
}); });
it('bad zlib method', function () { it('bad zlib method', () => {
testInflate('77 85', 15, c.Z_DATA_ERROR); testInflate('77 85', 15, c.Z_DATA_ERROR);
}); });
it('set window size from header', function () { it('set window size from header', () => {
testInflate('8 99', 0, c.Z_OK); testInflate('8 99', 0, c.Z_OK);
}); });
it('bad zlib window size', function () { it('bad zlib window size', () => {
testInflate('78 9c', 8, c.Z_DATA_ERROR); testInflate('78 9c', 8, c.Z_DATA_ERROR);
}); });
it('check adler32', function () { it('check adler32', () => {
testInflate('78 9c 63 0 0 0 1 0 1', 15, c.Z_OK); testInflate('78 9c 63 0 0 0 1 0 1', 15, c.Z_OK);
}); });
it('bad header crc', function () { it('bad header crc', () => {
testInflate('1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0', 47, c.Z_DATA_ERROR); testInflate('1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0', 47, c.Z_DATA_ERROR);
}); });
it('check gzip length', function () { it('check gzip length', () => {
testInflate('1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0', 47, c.Z_OK); testInflate('1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0', 47, c.Z_OK);
}); });
it('bad zlib header check', function () { it('bad zlib header check', () => {
testInflate('78 90', 47, c.Z_DATA_ERROR); testInflate('78 90', 47, c.Z_DATA_ERROR);
}); });
it('need dictionary', function () { it('need dictionary', () => {
testInflate('8 b8 0 0 0 1', 8, c.Z_NEED_DICT); testInflate('8 b8 0 0 0 1', 8, c.Z_NEED_DICT);
}); });
it('compute adler32', function () { it('compute adler32', () => {
testInflate('78 9c 63 0', 15, c.Z_OK); testInflate('78 9c 63 0', 15, c.Z_OK);
}); });
}); });
describe('Inflate cover', function () { describe('Inflate cover', () => {
it('invalid stored block lengths', function () { it('invalid stored block lengths', () => {
testInflate('0 0 0 0 0', -15, c.Z_DATA_ERROR); testInflate('0 0 0 0 0', -15, c.Z_DATA_ERROR);
}); });
it('fixed', function () { it('fixed', () => {
testInflate('3 0', -15, c.Z_OK); testInflate('3 0', -15, c.Z_OK);
}); });
it('invalid block type', function () { it('invalid block type', () => {
testInflate('6', -15, c.Z_DATA_ERROR); testInflate('6', -15, c.Z_DATA_ERROR);
}); });
it('stored', function () { it('stored', () => {
testInflate('1 1 0 fe ff 0', -15, c.Z_OK); testInflate('1 1 0 fe ff 0', -15, c.Z_OK);
}); });
it('too many length or distance symbols', function () { it('too many length or distance symbols', () => {
testInflate('fc 0 0', -15, c.Z_DATA_ERROR); testInflate('fc 0 0', -15, c.Z_DATA_ERROR);
}); });
it('invalid code lengths set', function () { it('invalid code lengths set', () => {
testInflate('4 0 fe ff', -15, c.Z_DATA_ERROR); testInflate('4 0 fe ff', -15, c.Z_DATA_ERROR);
}); });
it('invalid bit length repeat', function () { it('invalid bit length repeat', () => {
testInflate('4 0 24 49 0', -15, c.Z_DATA_ERROR); testInflate('4 0 24 49 0', -15, c.Z_DATA_ERROR);
}); });
it('invalid bit length repeat', function () { it('invalid bit length repeat', () => {
testInflate('4 0 24 e9 ff ff', -15, c.Z_DATA_ERROR); testInflate('4 0 24 e9 ff ff', -15, c.Z_DATA_ERROR);
}); });
it('invalid code -- missing end-of-block', function () { it('invalid code -- missing end-of-block', () => {
testInflate('4 0 24 e9 ff 6d', -15, c.Z_DATA_ERROR); testInflate('4 0 24 e9 ff 6d', -15, c.Z_DATA_ERROR);
}); });
it('invalid literal/lengths set', function () { it('invalid literal/lengths set', () => {
testInflate('4 80 49 92 24 49 92 24 71 ff ff 93 11 0', -15, c.Z_DATA_ERROR); testInflate('4 80 49 92 24 49 92 24 71 ff ff 93 11 0', -15, c.Z_DATA_ERROR);
}); });
it('invalid literal/length code', function () { it('invalid literal/length code', () => {
testInflate('4 80 49 92 24 49 92 24 f b4 ff ff c3 84', -15, c.Z_DATA_ERROR); testInflate('4 80 49 92 24 49 92 24 f b4 ff ff c3 84', -15, c.Z_DATA_ERROR);
}); });
it('invalid distance code', function () { it('invalid distance code', () => {
testInflate('2 7e ff ff', -15, c.Z_DATA_ERROR); testInflate('2 7e ff ff', -15, c.Z_DATA_ERROR);
}); });
it('invalid distance too far back', function () { it('invalid distance too far back', () => {
testInflate('c c0 81 0 0 0 0 0 90 ff 6b 4 0', -15, c.Z_DATA_ERROR); testInflate('c c0 81 0 0 0 0 0 90 ff 6b 4 0', -15, c.Z_DATA_ERROR);
}); });
it('incorrect data check', function () { it('incorrect data check', () => {
testInflate('1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1', 47, c.Z_DATA_ERROR); testInflate('1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1', 47, c.Z_DATA_ERROR);
}); });
it('incorrect length check', function () { it('incorrect length check', () => {
testInflate('1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1', 47, c.Z_DATA_ERROR); testInflate('1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1', 47, c.Z_DATA_ERROR);
}); });
it('pull 17', function () { it('pull 17', () => {
testInflate('5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c', -15, c.Z_OK); testInflate('5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c', -15, c.Z_OK);
}); });
it('long code', function () { it('long code', () => {
testInflate('5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f', -15, c.Z_OK); testInflate('5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f', -15, c.Z_OK);
}); });
it('length extra', function () { it('length extra', () => {
testInflate('ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f', -15, c.Z_OK); testInflate('ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f', -15, c.Z_OK);
}); });
it('long distance and extra', function () { it('long distance and extra', () => {
testInflate('ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c', -15, c.Z_OK); testInflate('ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c', -15, c.Z_OK);
}); });
it('window end', function () { it('window end', () => {
testInflate('ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6', testInflate('ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6',
-15, c.Z_OK); -15, c.Z_OK);
}); });
it('inflate_fast TYPE return', function () { it('inflate_fast TYPE return', () => {
testInflate('2 8 20 80 0 3 0', -15, c.Z_OK); testInflate('2 8 20 80 0 3 0', -15, c.Z_OK);
}); });
it('window wrap', function () { it('window wrap', () => {
testInflate('63 18 5 40 c 0', -8, c.Z_OK); testInflate('63 18 5 40 c 0', -8, c.Z_OK);
}); });
}); });
describe('cover trees', function () { describe('cover trees', () => {
it('inflate_table not enough errors', function () { it('inflate_table not enough errors', () => {
var ret, bits, next, table = [], lens = [], work = []; let ret, bits, next, table = [], lens = [], work = [];
var DISTS = 2; const DISTS = 2;
/* we need to call inflate_table() directly in order to manifest not- /* we need to call inflate_table() directly in order to manifest not-
enough errors, since zlib insures that enough is always enough */ enough errors, since zlib insures that enough is always enough */
for (bits = 0; bits < 15; bits++) { for (bits = 0; bits < 15; bits++) {
@ -174,37 +173,37 @@ describe('cover trees', function () {
}); });
}); });
describe('Inflate fast', function () { describe('Inflate fast', () => {
it('fast length extra bits', function () { it('fast length extra bits', () => {
testInflate('e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68' + testInflate('e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68' +
' ff 7f 0f 0 0 0', -8, c.Z_DATA_ERROR); ' ff 7f 0f 0 0 0', -8, c.Z_DATA_ERROR);
}); });
it('fast distance extra bits', function () { it('fast distance extra bits', () => {
testInflate('25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49' + testInflate('25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49' +
' 50 fe ff ff 3f 0 0', -8, c.Z_DATA_ERROR); ' 50 fe ff ff 3f 0 0', -8, c.Z_DATA_ERROR);
}); });
it('fast invalid literal/length code', function () { it('fast invalid literal/length code', () => {
testInflate('1b 7 0 0 0 0 0', -8, c.Z_DATA_ERROR); testInflate('1b 7 0 0 0 0 0', -8, c.Z_DATA_ERROR);
}); });
it('fast 2nd level codes and too far back', function () { it('fast 2nd level codes and too far back', () => {
testInflate('d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0', -8, c.Z_DATA_ERROR); testInflate('d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0', -8, c.Z_DATA_ERROR);
}); });
it('very common case', function () { it('very common case', () => {
testInflate('63 18 5 8c 10 8 0 0 0 0', -8, c.Z_OK); testInflate('63 18 5 8c 10 8 0 0 0 0', -8, c.Z_OK);
}); });
it('contiguous and wrap around window', function () { it('contiguous and wrap around window', () => {
testInflate('63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0', -8, c.Z_OK); testInflate('63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0', -8, c.Z_OK);
}); });
it('copy direct from output', function () { it('copy direct from output', () => {
testInflate('63 0 3 0 0 0 0 0', -8, c.Z_OK); testInflate('63 0 3 0 0 0 0 0', -8, c.Z_OK);
}); });
}); });
describe('Inflate support', function () { describe('Inflate support', () => {
// `inflatePrime` not implemented // `inflatePrime` not implemented
/*it('prime', function() { /*it('prime', function() {
var ret; let ret;
var strm = new zlib_stream(); const strm = new zlib_stream();
strm.avail_in = 0; strm.avail_in = 0;
strm.input = null; strm.input = null;
@ -224,19 +223,19 @@ describe('Inflate support', function () {
ret = zlib_inflate.inflateEnd(strm); ret = zlib_inflate.inflateEnd(strm);
assert(ret === c.Z_OK); assert(ret === c.Z_OK);
});*/ });*/
it('force window allocation', function () { it('force window allocation', () => {
testInflate('63 0', -15, c.Z_OK); testInflate('63 0', -15, c.Z_OK);
}); });
it('force window replacement', function () { it('force window replacement', () => {
testInflate('63 18 5', -15, c.Z_OK); testInflate('63 18 5', -15, c.Z_OK);
}); });
it('force split window update', function () { it('force split window update', () => {
testInflate('63 18 68 30 d0 0 0', -15, c.Z_OK); testInflate('63 18 68 30 d0 0 0', -15, c.Z_OK);
}); });
it('use fixed blocks', function () { it('use fixed blocks', () => {
testInflate('3 0', -15, c.Z_OK); testInflate('3 0', -15, c.Z_OK);
}); });
it('bad window size', function () { it('bad window size', () => {
testInflate('', -15, c.Z_OK); testInflate('', -15, c.Z_OK);
}); });
}); });

View file

@ -1,23 +1,23 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var assert = require('assert'); const assert = require('assert');
var pako = require('../index'); const pako = require('../index');
describe('ArrayBuffer', function () { describe('ArrayBuffer', () => {
var file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt'); const file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt');
var sample = new Uint8Array(fs.readFileSync(file)); const sample = new Uint8Array(fs.readFileSync(file));
var deflated = pako.deflate(sample); const deflated = pako.deflate(sample);
it('Deflate ArrayBuffer', function () { it('Deflate ArrayBuffer', () => {
assert.deepStrictEqual(deflated, pako.deflate(sample.buffer)); assert.deepStrictEqual(deflated, pako.deflate(sample.buffer));
}); });
it('Inflate ArrayBuffer', function () { it('Inflate ArrayBuffer', () => {
assert.deepStrictEqual(sample, pako.inflate(deflated.buffer)); assert.deepStrictEqual(sample, pako.inflate(deflated.buffer));
}); });
}); });

View file

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var assert = require('assert'); const assert = require('assert');
var pako = require('../index'); const pako = require('../index');
var strings = require('../lib/utils/strings'); const strings = require('../lib/utils/strings');
// fromCharCode, but understands right > 0xffff values // fromCharCode, but understands right > 0xffff values
function fixedFromCharCode(code) { function fixedFromCharCode(code) {
@ -14,8 +14,8 @@ function fixedFromCharCode(code) {
if (code > 0xffff) { if (code > 0xffff) {
code -= 0x10000; code -= 0x10000;
var surrogate1 = 0xd800 + (code >> 10), const surrogate1 = 0xd800 + (code >> 10);
surrogate2 = 0xdc00 + (code & 0x3ff); const surrogate2 = 0xdc00 + (code & 0x3ff);
return String.fromCharCode(surrogate1, surrogate2); return String.fromCharCode(surrogate1, surrogate2);
} }
@ -24,7 +24,7 @@ function fixedFromCharCode(code) {
// Converts array of codes / chars / strings to utf16 string // Converts array of codes / chars / strings to utf16 string
function a2utf16(arr) { function a2utf16(arr) {
var result = ''; let result = '';
arr.forEach(function (item) { arr.forEach(function (item) {
if (typeof item === 'string') { result += item; return; } if (typeof item === 'string') { result += item; return; }
result += fixedFromCharCode(item); result += fixedFromCharCode(item);
@ -33,15 +33,15 @@ function a2utf16(arr) {
} }
describe('Encode/Decode', function () { describe('Encode/Decode', () => {
// Create sample, that contains all types of utf8 (1-4byte) after conversion // Create sample, that contains all types of utf8 (1-4byte) after conversion
var utf16sample = a2utf16([ 0x1f3b5, 'a', 0x266a, 0x35, 0xe800, 0x10ffff, 0x0fffff ]); const utf16sample = a2utf16([ 0x1f3b5, 'a', 0x266a, 0x35, 0xe800, 0x10ffff, 0x0fffff ]);
// use node Buffer internal conversion as "done right" // use node Buffer internal conversion as "done right"
var utf8sample = new Uint8Array(Buffer.from(utf16sample)); const utf8sample = new Uint8Array(Buffer.from(utf16sample));
it('utf-8 border detect', function () { it('utf-8 border detect', () => {
var ub = strings.utf8border; const ub = strings.utf8border;
assert.strictEqual(ub(utf8sample, 1), 1); assert.strictEqual(ub(utf8sample, 1), 1);
assert.strictEqual(ub(utf8sample, 2), 2); assert.strictEqual(ub(utf8sample, 2), 2);
assert.strictEqual(ub(utf8sample, 3), 3); assert.strictEqual(ub(utf8sample, 3), 3);
@ -70,36 +70,36 @@ describe('Encode/Decode', function () {
assert.strictEqual(ub(utf8sample, 20), 20); assert.strictEqual(ub(utf8sample, 20), 20);
}); });
it('Encode string to utf8 buf', function () { it('Encode string to utf8 buf', () => {
assert.deepStrictEqual( assert.deepStrictEqual(
strings.string2buf(utf16sample), strings.string2buf(utf16sample),
utf8sample utf8sample
); );
}); });
it('Decode utf8 buf to string', function () { it('Decode utf8 buf to string', () => {
assert.ok(strings.buf2string(utf8sample), utf16sample); assert.ok(strings.buf2string(utf8sample), utf16sample);
}); });
}); });
describe('Deflate/Inflate strings', function () { describe('Deflate/Inflate strings', () => {
var file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt'); const file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt');
var sampleString = fs.readFileSync(file, 'utf8'); const sampleString = fs.readFileSync(file, 'utf8');
var sampleArray = new Uint8Array(fs.readFileSync(file)); const sampleArray = new Uint8Array(fs.readFileSync(file));
it('Deflate javascript string (utf16) on input', function () { it('Deflate javascript string (utf16) on input', () => {
assert.deepStrictEqual( assert.deepStrictEqual(
pako.deflate(sampleString), pako.deflate(sampleString),
pako.deflate(sampleArray) pako.deflate(sampleArray)
); );
}); });
it('Inflate with javascript string (utf16) output', function () { it('Inflate with javascript string (utf16) output', () => {
var deflatedArray = pako.deflate(sampleArray); const deflatedArray = pako.deflate(sampleArray);
var data = pako.inflate(deflatedArray, { to: 'string', chunkSize: 99 }); const data = pako.inflate(deflatedArray, { to: 'string', chunkSize: 99 });
assert.strictEqual(typeof data, 'string'); assert.strictEqual(typeof data, 'string');
assert.strictEqual(data, sampleString); assert.strictEqual(data, sampleString);