From 505e36d9f021a27f14e02d46a84db307a2f8150f Mon Sep 17 00:00:00 2001 From: Vitaly Puzrin Date: Sun, 8 Nov 2020 11:31:30 +0300 Subject: [PATCH] Move to es6 --- .eslintrc.yml | 11 +- CHANGELOG.md | 4 +- benchmark/benchmark.js | 46 +-- .../implementations/deflate-imaya/index.js | 4 +- .../implementations/deflate-pako/index.js | 4 +- .../implementations/deflate-zlib/index.js | 4 +- benchmark/implementations/gzip-pako/index.js | 4 +- .../implementations/inflate-imaya/index.js | 4 +- .../implementations/inflate-pako/index.js | 4 +- .../implementations/inflate-zlib/index.js | 4 +- .../implementations/ungzip-pako/index.js | 4 +- benchmark/profile.js | 12 +- examples/.eslintrc.yml | 3 - examples/server.js | 16 +- index.js | 10 +- lib/deflate.js | 55 ++- lib/inflate.js | 92 +++-- lib/utils/common.js | 27 +- lib/utils/strings.js | 35 +- lib/zlib/adler32.js | 6 +- lib/zlib/crc32.js | 18 +- lib/zlib/deflate.js | 374 ++++++++---------- lib/zlib/inffast.js | 53 ++- lib/zlib/inflate.js | 269 ++++++------- lib/zlib/inftrees.js | 83 ++-- lib/zlib/trees.js | 335 ++++++++-------- package.json | 2 + rollup.config.js | 41 ++ test/chunks.js | 70 ++-- test/deflate.js | 135 ++++--- test/deflate_cover.js | 40 +- test/gzip_specials.js | 32 +- test/helpers.js | 36 +- test/inflate.js | 139 ++++--- test/inflate_cover_ported.js | 131 +++--- test/misc.js | 20 +- test/strings.js | 46 +-- 37 files changed, 1091 insertions(+), 1082 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index 39836ae..b7543f7 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -1,10 +1,9 @@ env: - node: true + node: true + es6: true -globals: - Uint8Array: false - Uint16Array: false - Int32Array: false +parserOptions: + ecmaVersion: 2015 ignorePatterns: - coverage/ @@ -29,7 +28,7 @@ rules: dot-location: [ 2, 'property' ] eol-last: 2 eqeqeq: 2 - func-style: [ 2, declaration ] + # func-style: [ 2, declaration ] guard-for-in: 2 handle-callback-err: 2 indent: [ 2, 2, { VariableDeclarator: { var: 2, let: 2, const: 3 }, SwitchCase: 1, ignoreComments: true, MemberExpression: off, ignoredNodes: ["ConditionalExpression"] } ] diff --git a/CHANGELOG.md b/CHANGELOG.md index e075715..4446f83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 fallbacks for unsupported TypedArray methods (`.set()`, `.subarray()`). - 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 ### Fixed diff --git a/benchmark/benchmark.js b/benchmark/benchmark.js index 0fea9a0..a9123b3 100755 --- a/benchmark/benchmark.js +++ b/benchmark/benchmark.js @@ -2,26 +2,26 @@ 'use strict'; -var LEVEL = 6; +const LEVEL = 6; -var path = require('path'); -var fs = require('fs'); -var util = require('util'); -var Benchmark = require('benchmark'); -var ansi = require('ansi'); -var cursor = ansi(process.stdout); +const path = require('path'); +const fs = require('fs'); +const util = require('util'); +const Benchmark = require('benchmark'); +const ansi = require('ansi'); +const cursor = ansi(process.stdout); -var pako = require('../'); +const pako = require('../'); -var IMPLS_DIRECTORY = path.join(__dirname, 'implementations'); -var IMPLS_PATHS = {}; -var IMPLS = []; +const IMPLS_DIRECTORY = path.join(__dirname, 'implementations'); +const IMPLS_PATHS = {}; +const IMPLS = []; fs.readdirSync(IMPLS_DIRECTORY).sort().forEach(function (name) { - var file = path.join(IMPLS_DIRECTORY, name); - var code = require(file); + const file = path.join(IMPLS_DIRECTORY, name); + const code = require(file); IMPLS_PATHS[name] = file; IMPLS.push({ @@ -32,15 +32,15 @@ fs.readdirSync(IMPLS_DIRECTORY).sort().forEach(function (name) { /* eslint-disable no-console */ -var SAMPLES_DIRECTORY = path.join(__dirname, 'samples'); -var SAMPLES = []; +const SAMPLES_DIRECTORY = path.join(__dirname, 'samples'); +const SAMPLES = []; fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) { - var filepath = path.join(SAMPLES_DIRECTORY, sample), - extname = path.extname(filepath), - basename = path.basename(filepath, extname); + const filepath = path.join(SAMPLES_DIRECTORY, sample); + const extname = path.extname(filepath); + 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.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 }); - 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() { @@ -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() { console.log('\nSample: %s %s', sample, title); @@ -108,7 +108,7 @@ fs.readdirSync(SAMPLES_DIRECTORY).sort().forEach(function (sample) { function select(patterns) { - var result = []; + const result = []; if (!(patterns instanceof Array)) { patterns = [ patterns ]; @@ -131,7 +131,7 @@ function select(patterns) { function run(files) { - var selected = select(files); + const selected = select(files); if (selected.length > 0) { console.log('Selected samples: (%d of %d)', selected.length, SAMPLES.length); diff --git a/benchmark/implementations/deflate-imaya/index.js b/benchmark/implementations/deflate-imaya/index.js index 2cf80b4..8a8d66f 100644 --- a/benchmark/implementations/deflate-imaya/index.js +++ b/benchmark/implementations/deflate-imaya/index.js @@ -1,8 +1,8 @@ '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 return deflateSync(data.typed, { level: level }); }; diff --git a/benchmark/implementations/deflate-pako/index.js b/benchmark/implementations/deflate-pako/index.js index 038eb7e..dd98fc0 100644 --- a/benchmark/implementations/deflate-pako/index.js +++ b/benchmark/implementations/deflate-pako/index.js @@ -1,7 +1,7 @@ 'use strict'; -var pako = require('../../../'); +const pako = require('../../../'); -exports.run = function (data, level) { +exports.run = (data, level) => { return pako.deflate(data.typed, { level: level }); }; diff --git a/benchmark/implementations/deflate-zlib/index.js b/benchmark/implementations/deflate-zlib/index.js index 2d4d691..c7beeaf 100644 --- a/benchmark/implementations/deflate-zlib/index.js +++ b/benchmark/implementations/deflate-zlib/index.js @@ -1,7 +1,7 @@ '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 }); }; diff --git a/benchmark/implementations/gzip-pako/index.js b/benchmark/implementations/gzip-pako/index.js index 534840b..9e1fed8 100644 --- a/benchmark/implementations/gzip-pako/index.js +++ b/benchmark/implementations/gzip-pako/index.js @@ -1,7 +1,7 @@ 'use strict'; -var pako = require('../../../'); +const pako = require('../../../'); -exports.run = function (data, level) { +exports.run = (data, level) => { return pako.gzip(data.typed, { level: level }); }; diff --git a/benchmark/implementations/inflate-imaya/index.js b/benchmark/implementations/inflate-imaya/index.js index b07fe25..b4916aa 100644 --- a/benchmark/implementations/inflate-imaya/index.js +++ b/benchmark/implementations/inflate-imaya/index.js @@ -1,8 +1,8 @@ '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 return inflateSync(data.deflateTyped); }; diff --git a/benchmark/implementations/inflate-pako/index.js b/benchmark/implementations/inflate-pako/index.js index 64535f3..3b081fc 100644 --- a/benchmark/implementations/inflate-pako/index.js +++ b/benchmark/implementations/inflate-pako/index.js @@ -1,7 +1,7 @@ 'use strict'; -var pako = require('../../../'); +const pako = require('../../../'); -exports.run = function (data) { +exports.run = (data) => { return pako.inflate(data.deflateTyped, {}); }; diff --git a/benchmark/implementations/inflate-zlib/index.js b/benchmark/implementations/inflate-zlib/index.js index 5847e8d..7954018 100644 --- a/benchmark/implementations/inflate-zlib/index.js +++ b/benchmark/implementations/inflate-zlib/index.js @@ -1,7 +1,7 @@ 'use strict'; -var zlib = require('zlib'); +const zlib = require('zlib'); -exports.run = function (data) { +exports.run = (data) => { zlib.inflateSync(data.deflateTyped); }; diff --git a/benchmark/implementations/ungzip-pako/index.js b/benchmark/implementations/ungzip-pako/index.js index d9609cf..86b8df1 100644 --- a/benchmark/implementations/ungzip-pako/index.js +++ b/benchmark/implementations/ungzip-pako/index.js @@ -1,8 +1,8 @@ 'use strict'; -var pako = require('../../../'); +const pako = require('../../../'); -exports.run = function (data) { +exports.run = (data) => { return pako.ungzip(data.gzipTyped, { }); }; diff --git a/benchmark/profile.js b/benchmark/profile.js index 3a2f4c4..504e011 100644 --- a/benchmark/profile.js +++ b/benchmark/profile.js @@ -1,13 +1,13 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var pako = require('../'); +const fs = require('fs'); +const path = require('path'); +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' }); } diff --git a/examples/.eslintrc.yml b/examples/.eslintrc.yml index 4315849..1ddd632 100644 --- a/examples/.eslintrc.yml +++ b/examples/.eslintrc.yml @@ -1,5 +1,2 @@ -env: - es6: true - parserOptions: ecmaVersion: 2017 diff --git a/examples/server.js b/examples/server.js index 0872f0c..2c858c6 100644 --- a/examples/server.js +++ b/examples/server.js @@ -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'); @@ -35,7 +35,7 @@ const server = http.createServer(async function (req, res) { // // 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'); @@ -45,12 +45,12 @@ const server = http.createServer(async function (req, res) { let err = null; - let form = new multiparty.Form({ + const form = new multiparty.Form({ maxFieldsSize: MAX_FIELDS_SIZE, maxFilesSize: MAX_FILES_SIZE }); - let files = await new Promise(resolve => { + const files = await new Promise(resolve => { form.parse(req, function (e, fields, files) { if (e) err = e; resolve(files); @@ -62,21 +62,21 @@ const server = http.createServer(async function (req, res) { 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 fs.unlinkSync(files.binson[0].path); // Decompress binary content // 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) - let decoded = uncompressed.toString(); + const decoded = uncompressed.toString(); // Finally, create an object // Note! Can throw error on bad data - let obj = JSON.parse(decoded); + const obj = JSON.parse(decoded); console.log('--- received object is: ', obj); res.end('ok'); diff --git a/index.js b/index.js index cd07251..dc9c41f 100644 --- a/index.js +++ b/index.js @@ -1,13 +1,13 @@ // Top level file is just a mixin of submodules & constants 'use strict'; -var assign = require('./lib/utils/common').assign; +const assign = require('./lib/utils/common').assign; -var deflate = require('./lib/deflate'); -var inflate = require('./lib/inflate'); -var constants = require('./lib/zlib/constants'); +const deflate = require('./lib/deflate'); +const inflate = require('./lib/inflate'); +const constants = require('./lib/zlib/constants'); -var pako = {}; +let pako = {}; assign(pako, deflate, inflate, constants); diff --git a/lib/deflate.js b/lib/deflate.js index 569481d..97aad88 100644 --- a/lib/deflate.js +++ b/lib/deflate.js @@ -1,29 +1,24 @@ 'use strict'; -var zlib_deflate = require('./zlib/deflate'); -var utils = require('./utils/common'); -var strings = require('./utils/strings'); -var msg = require('./zlib/messages'); -var ZStream = require('./zlib/zstream'); +const zlib_deflate = require('./zlib/deflate'); +const utils = require('./utils/common'); +const strings = require('./utils/strings'); +const msg = require('./zlib/messages'); +const ZStream = require('./zlib/zstream'); -var toString = Object.prototype.toString; +const toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ -var Z_NO_FLUSH = 0; -var Z_FINISH = 4; - -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_SYNC_FLUSH = 2; - -var Z_DEFAULT_COMPRESSION = -1; - -var Z_DEFAULT_STRATEGY = 0; - -var Z_DEFLATED = 8; +const { + Z_NO_FLUSH, Z_FINISH, + Z_OK, Z_STREAM_END, Z_SYNC_FLUSH, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_STRATEGY, + Z_DEFLATED +} = require('./zlib/constants'); /* ===========================================================================*/ @@ -101,11 +96,11 @@ var Z_DEFLATED = 8; * ##### Example: * * ```javascript - * var pako = require('pako') + * const pako = require('pako') * , 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]); * - * var deflate = new pako.Deflate({ level: 3}); + * const deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk @@ -125,7 +120,7 @@ function Deflate(options) { strategy: Z_DEFAULT_STRATEGY }, options || {}); - var opt = this.options; + let opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; @@ -143,7 +138,7 @@ function Deflate(options) { this.strm = new ZStream(); this.strm.avail_out = 0; - var status = zlib_deflate.deflateInit2( + let status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, @@ -161,7 +156,7 @@ function Deflate(options) { } if (opt.dictionary) { - var dict; + let dict; // Convert data if needed if (typeof opt.dictionary === 'string') { // If we need to compress text, change encoding to utf8. @@ -209,13 +204,13 @@ function Deflate(options) { * ``` **/ Deflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var status, _mode; + const strm = this.strm; + const chunkSize = this.options.chunkSize; + let status; 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 if (typeof data === 'string') { @@ -326,14 +321,14 @@ Deflate.prototype.onEnd = function (status) { * ##### Example: * * ```javascript - * var pako = require('pako') - * , data = new Uint8Array([1,2,3,4,5,6,7,8,9]); + * const pako = require('pako') + * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { - var deflator = new Deflate(options); + const deflator = new Deflate(options); deflator.push(input, true); diff --git a/lib/inflate.js b/lib/inflate.js index 18af9eb..2a5cb88 100644 --- a/lib/inflate.js +++ b/lib/inflate.js @@ -1,15 +1,25 @@ 'use strict'; -var zlib_inflate = require('./zlib/inflate'); -var utils = require('./utils/common'); -var strings = require('./utils/strings'); -var c = require('./zlib/constants'); -var msg = require('./zlib/messages'); -var ZStream = require('./zlib/zstream'); -var GZheader = require('./zlib/gzheader'); +const zlib_inflate = require('./zlib/inflate'); +const utils = require('./utils/common'); +const strings = require('./utils/strings'); +const msg = require('./zlib/messages'); +const ZStream = require('./zlib/zstream'); +const 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 @@ -76,11 +86,11 @@ var toString = Object.prototype.toString; * ##### Example: * * ```javascript - * var pako = require('pako') - * , 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 pako = require('pako') + * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) + * 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(chunk2, true); // true -> last chunk @@ -97,7 +107,7 @@ function Inflate(options) { to: '' }, options || {}); - var opt = this.options; + const opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. @@ -130,12 +140,12 @@ function Inflate(options) { this.strm = new ZStream(); this.strm.avail_out = 0; - var status = zlib_inflate.inflateInit2( + let status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); - if (status !== c.Z_OK) { + if (status !== Z_OK) { 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 status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); - if (status !== c.Z_OK) { + if (status !== Z_OK) { throw new Error(msg[status]); } } @@ -186,18 +196,18 @@ function Inflate(options) { * ``` **/ Inflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var dictionary = this.options.dictionary; - var status, _mode; - var next_out_utf8, tail, utf8str; + const strm = this.strm; + const chunkSize = this.options.chunkSize; + const dictionary = this.options.dictionary; + let status, _mode; + let next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. - var allowBufError = false; + let allowBufError = 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 if (toString.call(data) === '[object ArrayBuffer]') { @@ -216,25 +226,25 @@ Inflate.prototype.push = function (data, mode) { 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); } - if (status === c.Z_BUF_ERROR && allowBufError === true) { - status = c.Z_OK; + if (status === Z_BUF_ERROR && allowBufError === true) { + status = Z_OK; allowBufError = false; } - if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } 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') { @@ -267,23 +277,23 @@ Inflate.prototype.push = function (data, mode) { 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) { - _mode = c.Z_FINISH; + if (status === Z_STREAM_END) { + _mode = Z_FINISH; } // Finalize on the last chunk. - if (_mode === c.Z_FINISH) { + if (_mode === Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; - return status === c.Z_OK; + return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. - if (_mode === c.Z_SYNC_FLUSH) { - this.onEnd(c.Z_OK); + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); strm.avail_out = 0; return true; } @@ -317,7 +327,7 @@ Inflate.prototype.onData = function (chunk) { **/ Inflate.prototype.onEnd = function (status) { // On success - join - if (status === c.Z_OK) { + if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { @@ -358,9 +368,9 @@ Inflate.prototype.onEnd = function (status) { * ##### Example: * * ```javascript - * var pako = require('pako') - * , input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])) - * , output; + * const pako = require('pako'); + * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])); + * let output; * * try { * output = pako.inflate(input); @@ -370,7 +380,7 @@ Inflate.prototype.onEnd = function (status) { * ``` **/ function inflate(input, options) { - var inflator = new Inflate(options); + const inflator = new Inflate(options); inflator.push(input, true); diff --git a/lib/utils/common.js b/lib/utils/common.js index 4d885af..9a6447a 100644 --- a/lib/utils/common.js +++ b/lib/utils/common.js @@ -1,21 +1,21 @@ 'use strict'; -function _has(obj, key) { +const _has = (obj, key) => { return Object.prototype.hasOwnProperty.call(obj, key); -} +}; 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) { - var source = sources.shift(); + const source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } - for (var p in source) { + for (const p in source) { if (_has(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. -module.exports.flattenChunks = function (chunks) { - var i, l, len, pos, chunk, result; - +module.exports.flattenChunks = (chunks) => { // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { + let len = 0; + + for (let i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks - result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; + const result = new Uint8Array(len); + + for (let i = 0, pos = 0, l = chunks.length; i < l; i++) { + let chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } diff --git a/lib/utils/strings.js b/lib/utils/strings.js index 75e5ad6..b48515e 100644 --- a/lib/utils/strings.js +++ b/lib/utils/strings.js @@ -7,7 +7,7 @@ // - apply(Array) can fail on Android 2.2 // - 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; } @@ -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) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff -var _utf8len = new Uint8Array(256); -for (var q = 0; q < 256; q++) { +const _utf8len = new Uint8Array(256); +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[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) -exports.string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; +module.exports.string2buf = (str) => { + let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { @@ -77,7 +77,7 @@ exports.string2buf = function (str) { }; // Helper -function buf2binstring(buf, len) { +const buf2binstring = (buf, len) => { // 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, // otherwise we will take a slower path. @@ -87,30 +87,30 @@ function buf2binstring(buf, len) { } } - var result = ''; - for (var i = 0; i < len; i++) { + let result = ''; + for (let i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; -} +}; // convert array to string -exports.buf2string = function (buf, max) { - var i, out, c, c_len; - var len = max || buf.length; +module.exports.buf2string = (buf, max) => { + let i, out; + const len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len * 2); + const utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { - c = buf[i++]; + let c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } - c_len = _utf8len[c]; + let c_len = _utf8len[c]; // skip 5 & 6 byte codes 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 // max - length limit (mandatory); -exports.utf8border = function (buf, max) { - var pos; +module.exports.utf8border = (buf, max) => { max = max || buf.length; if (max > buf.length) { max = buf.length; } // 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--; } // Very small and broken sequence, diff --git a/lib/zlib/adler32.js b/lib/zlib/adler32.js index d440a98..d65072a 100644 --- a/lib/zlib/adler32.js +++ b/lib/zlib/adler32.js @@ -23,8 +23,8 @@ // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. -function adler32(adler, buf, len, pos) { - var s1 = (adler & 0xffff) |0, +const adler32 = (adler, buf, len, pos) => { + let s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; @@ -45,7 +45,7 @@ function adler32(adler, buf, len, pos) { } return (s1 | (s2 << 16)) |0; -} +}; module.exports = adler32; diff --git a/lib/zlib/crc32.js b/lib/zlib/crc32.js index 6a96092..60cbd51 100644 --- a/lib/zlib/crc32.js +++ b/lib/zlib/crc32.js @@ -24,8 +24,8 @@ // 3. This notice may not be removed or altered from any source distribution. // Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; +const makeTable = () => { + let c, table = []; for (var n = 0; n < 256; n++) { c = n; @@ -36,24 +36,24 @@ function makeTable() { } return table; -} +}; // 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) { - var t = crcTable, - end = pos + len; +const crc32 = (crc, buf, len, pos) => { + const t = crcTable; + const end = pos + len; crc ^= -1; - for (var i = pos; i < end; i++) { + for (let i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; -} +}; module.exports = crc32; diff --git a/lib/zlib/deflate.js b/lib/zlib/deflate.js index 3fbab27..61cdfc8 100644 --- a/lib/zlib/deflate.js +++ b/lib/zlib/deflate.js @@ -19,118 +19,81 @@ // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. -var trees = require('./trees'); -var adler32 = require('./adler32'); -var crc32 = require('./crc32'); -var msg = require('./messages'); +const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = require('./trees'); +const adler32 = require('./adler32'); +const crc32 = require('./crc32'); +const msg = require('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ - -/* Allowed flush values; see deflate() and inflate() below for details */ -var Z_NO_FLUSH = 0; -var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -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; - - -/* 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; +const { + Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK, + Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR, + Z_DEFAULT_COMPRESSION, + Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY, + Z_UNKNOWN, + Z_DEFLATED +} = require('./constants'); /*============================================================================*/ -var MAX_MEM_LEVEL = 9; +const MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ -var MAX_WBITS = 15; +const MAX_WBITS = 15; /* 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 */ -var LITERALS = 256; +const LITERALS = 256; /* 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 */ -var D_CODES = 30; +const D_CODES = 30; /* number of distance codes */ -var BL_CODES = 19; +const BL_CODES = 19; /* 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 */ -var MAX_BITS = 15; +const MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ -var MIN_MATCH = 3; -var MAX_MATCH = 258; -var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); +const MIN_MATCH = 3; +const MAX_MATCH = 258; +const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); -var PRESET_DICT = 0x20; +const PRESET_DICT = 0x20; -var INIT_STATE = 42; -var EXTRA_STATE = 69; -var NAME_STATE = 73; -var COMMENT_STATE = 91; -var HCRC_STATE = 103; -var BUSY_STATE = 113; -var FINISH_STATE = 666; +const INIT_STATE = 42; +const EXTRA_STATE = 69; +const NAME_STATE = 73; +const COMMENT_STATE = 91; +const HCRC_STATE = 103; +const BUSY_STATE = 113; +const FINISH_STATE = 666; -var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -var BS_BLOCK_DONE = 2; /* block flush performed */ -var 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_NEED_MORE = 1; /* block not completed, need more input or more output */ +const BS_BLOCK_DONE = 2; /* block flush performed */ +const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +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]; return errorCode; -} +}; -function rank(f) { +const rank = (f) => { 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. * (See also read_buf()). */ -function flush_pending(strm) { - var s = strm.state; +const flush_pending = (strm) => { + const s = strm.state; //_tr_flush_bits(s); - var len = s.pending; + let len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } @@ -158,19 +121,19 @@ function flush_pending(strm) { if (s.pending === 0) { s.pending_out = 0; } -} +}; -function flush_block_only(s, last) { - trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); +const flush_block_only = (s, last) => { + _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); -} +}; -function put_byte(s, b) { +const put_byte = (s, 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 * pending_buf. */ -function putShortMSB(s, b) { -// put_byte(s, (Byte)(b >> 8)); +const putShortMSB = (s, b) => { + + // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 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. * (See also flush_pending()). */ -function read_buf(strm, buf, start, size) { - var len = strm.avail_in; +const read_buf = (strm, buf, start, size) => { + + let len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } @@ -215,7 +180,7 @@ function read_buf(strm, buf, start, size) { strm.total_in += 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 * OUT assertion: the match length is not greater than s->lookahead. */ -function longest_match(s, cur_match) { - var chain_length = s.max_chain_length; /* max hash chain length */ - var scan = s.strstart; /* current string */ - var match; /* matched string */ - var len; /* length of current match */ - var best_len = s.prev_length; /* best match length so far */ - var nice_match = s.nice_match; /* stop if match long enough */ - var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? +const longest_match = (s, cur_match) => { + + let chain_length = s.max_chain_length; /* max hash chain length */ + let scan = s.strstart; /* current string */ + let match; /* matched string */ + let len; /* length of current match */ + let best_len = s.prev_length; /* best match length so far */ + 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*/; - var _win = s.window; // shortcut + const _win = s.window; // shortcut - var wmask = s.w_mask; - var prev = s.prev; + const wmask = s.w_mask; + const prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ - var strend = s.strstart + MAX_MATCH; - var scan_end1 = _win[scan + best_len - 1]; - var scan_end = _win[scan + best_len]; + const strend = s.strstart + MAX_MATCH; + let scan_end1 = _win[scan + best_len - 1]; + let scan_end = _win[scan + best_len]; /* 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. @@ -327,7 +293,7 @@ function longest_match(s, cur_match) { return best_len; } 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 * option -- not supported here). */ -function fill_window(s) { - var _w_size = s.w_size; - var p, n, m, more, str; +const fill_window = (s) => { + + const _w_size = s.w_size; + let p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); @@ -384,6 +351,7 @@ function fill_window(s) { n = s.hash_size; p = n; + do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); @@ -391,6 +359,7 @@ function fill_window(s) { n = _w_size; p = n; + do { m = s.prev[--p]; 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. */ // if (s.high_water < s.window_size) { -// var curr = s.strstart + s.lookahead; -// var init = 0; +// const curr = s.strstart + s.lookahead; +// let init = 0; // // if (s.high_water < curr) { // /* 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, // "not enough room for search"); -} +}; /* =========================================================================== * 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 * 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 * 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) { max_block_size = s.pending_buf_size - 5; @@ -535,7 +505,7 @@ function deflate_stored(s, flush) { s.lookahead = 0; /* 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) { /* strstart == 0 is possible when wraparound on 16-bit machine */ @@ -585,7 +555,7 @@ function deflate_stored(s, flush) { } return BS_NEED_MORE; -} +}; /* =========================================================================== * 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 * matches. It is used only for the fast compression options. */ -function deflate_fast(s, flush) { - var hash_head; /* head of the hash chain */ - var bflush; /* set if current block must be flushed */ +const deflate_fast = (s, flush) => { + + let hash_head; /* head of the hash chain */ + let bflush; /* set if current block must be flushed */ for (;;) { /* 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, 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; @@ -682,7 +653,7 @@ function deflate_fast(s, flush) { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _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.strstart++; @@ -715,18 +686,19 @@ function deflate_fast(s, flush) { /***/ } return BS_BLOCK_DONE; -} +}; /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ -function deflate_slow(s, flush) { - var hash_head; /* head of hash chain */ - var bflush; /* set if current block must be flushed */ +const deflate_slow = (s, flush) => { - 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. */ for (;;) { @@ -790,7 +762,7 @@ function deflate_slow(s, flush) { /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, 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. * strstart-1 and strstart are already inserted. If there is not * 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])); /*** _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) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ @@ -852,7 +824,7 @@ function deflate_slow(s, flush) { if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _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; } @@ -876,7 +848,7 @@ function deflate_slow(s, flush) { } 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 * deflate switches away from Z_RLE.) */ -function 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 */ +const deflate_rle = (s, flush) => { - 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 (;;) { /* 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); /*** _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.strstart += s.match_length; @@ -940,7 +913,7 @@ function deflate_rle(s, flush) { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _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.strstart++; @@ -973,14 +946,15 @@ function deflate_rle(s, flush) { /***/ } return BS_BLOCK_DONE; -} +}; /* =========================================================================== * 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.) */ -function deflate_huff(s, flush) { - var bflush; /* set if current block must be flushed */ +const deflate_huff = (s, flush) => { + + let bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ @@ -998,7 +972,7 @@ function deflate_huff(s, flush) { s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _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.strstart++; if (bflush) { @@ -1029,7 +1003,7 @@ function deflate_huff(s, flush) { /***/ } return BS_BLOCK_DONE; -} +}; /* 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 @@ -1037,6 +1011,7 @@ function deflate_huff(s, flush) { * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; @@ -1044,9 +1019,7 @@ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.func = func; } -var configuration_table; - -configuration_table = [ +const configuration_table = [ /* good lazy nice chain */ 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 */ @@ -1065,7 +1038,8 @@ configuration_table = [ /* =========================================================================== * 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; /*** CLEAR_HASH(s); ***/ @@ -1085,7 +1059,7 @@ function lm_init(s) { s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; -} +}; function DeflateState() { @@ -1277,8 +1251,7 @@ function DeflateState() { } -function deflateResetKeep(strm) { - var s; +const deflateResetKeep = (strm) => { if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); @@ -1287,7 +1260,7 @@ function deflateResetKeep(strm) { strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; - s = strm.state; + const s = strm.state; s.pending = 0; s.pending_out = 0; @@ -1301,33 +1274,36 @@ function deflateResetKeep(strm) { : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; - trees._tr_init(s); + _tr_init(s); return Z_OK; -} +}; -function deflateReset(strm) { - var ret = deflateResetKeep(strm); +const deflateReset = (strm) => { + + const ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; -} +}; -function deflateSetHeader(strm, head) { +const deflateSetHeader = (strm, head) => { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; -} +}; -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { +const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => { + if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } - var wrap = 1; + let wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; @@ -1356,7 +1332,7 @@ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { } /* until 256-byte window bug fixed */ - var s = new DeflateState(); + const s = new DeflateState(); strm.state = s; s.strm = strm; @@ -1399,23 +1375,24 @@ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { s.method = method; 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); -} +}; -function deflate(strm, flush) { - var old_flush, s; - var beg, val; // for gzip header write only +const deflate = (strm, flush) => { + + let beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } - s = strm.state; + const s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || @@ -1424,7 +1401,7 @@ function deflate(strm, flush) { } s.strm = strm; /* just in case */ - old_flush = s.last_flush; + const old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ @@ -1475,8 +1452,8 @@ function deflate(strm, flush) { } else // DEFLATE header { - var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - var level_flags = -1; + let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + let level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; @@ -1659,7 +1636,7 @@ function deflate(strm, flush) { */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (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) : configuration_table[s.level].func(s, flush)); @@ -1682,11 +1659,11 @@ function deflate(strm, flush) { } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { - trees._tr_align(s); + _tr_align(s); } 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 * as a special marker by inflate_sync(). */ @@ -1738,16 +1715,16 @@ function deflate(strm, flush) { if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ 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*/) { return Z_STREAM_ERROR; } - status = strm.state.status; + const status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && @@ -1762,30 +1739,23 @@ function deflateEnd(strm) { strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} +}; /* ========================================================================= * Initializes the compression dictionary from the given byte * sequence without producing any compressed output. */ -function deflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; +const deflateSetDictionary = (strm, dictionary) => { - var s; - var str, n; - var wrap; - var avail; - var next; - var input; - var tmpDict; + let dictLength = dictionary.length; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } - s = strm.state; - wrap = s.wrap; + const s = strm.state; + const wrap = s.wrap; if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { return Z_STREAM_ERROR; @@ -1810,22 +1780,22 @@ function deflateSetDictionary(strm, dictionary) { } /* use the tail */ // 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); dictionary = tmpDict; dictLength = s.w_size; } /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; + const avail = strm.avail_in; + const next = strm.next_in; + const input = strm.input; strm.avail_in = dictLength; strm.next_in = 0; strm.input = dictionary; fill_window(s); while (s.lookahead >= MIN_MATCH) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH - 1); + let str = s.strstart; + let n = s.lookahead - (MIN_MATCH - 1); do { /* 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; @@ -1850,7 +1820,7 @@ function deflateSetDictionary(strm, dictionary) { strm.avail_in = avail; s.wrap = wrap; return Z_OK; -} +}; exports.deflateInit = deflateInit; diff --git a/lib/zlib/inffast.js b/lib/zlib/inffast.js index 4cc958f..44e5497 100644 --- a/lib/zlib/inffast.js +++ b/lib/zlib/inffast.js @@ -20,8 +20,8 @@ // 3. This notice may not be removed or altered from any source distribution. // See state defs from inflate.js -var BAD = 30; /* got a data error -- remain here until reset */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +const BAD = 30; /* got a data error -- remain here until reset */ +const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* 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. */ module.exports = function inflate_fast(strm, start) { - var state; - var _in; /* local strm.input */ - var last; /* have enough input while in < last */ - var _out; /* local strm.output */ - var beg; /* inflate()'s initial strm.output */ - var end; /* while out < end, enough space available */ + let _in; /* local strm.input */ + let last; /* have enough input while in < last */ + let _out; /* local strm.output */ + let beg; /* inflate()'s initial strm.output */ + let end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT - var dmax; /* maximum distance from zlib header */ + let dmax; /* maximum distance from zlib header */ //#endif - var wsize; /* window size or zero if not using window */ - var whave; /* valid bytes in the window */ - var wnext; /* window write index */ + let wsize; /* window size or zero if not using window */ + let whave; /* valid bytes in the window */ + let wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools - var s_window; /* allocated sliding window, if wsize != 0 */ - var hold; /* local strm.hold */ - var bits; /* local strm.bits */ - var lcode; /* local strm.lencode */ - var dcode; /* local strm.distcode */ - var lmask; /* mask for first level of length codes */ - var dmask; /* mask for first level of distance codes */ - var here; /* retrieved table entry */ - var op; /* code bits, operation, extra bits, or */ + let s_window; /* allocated sliding window, if wsize != 0 */ + let hold; /* local strm.hold */ + let bits; /* local strm.bits */ + let lcode; /* local strm.lencode */ + let dcode; /* local strm.distcode */ + let lmask; /* mask for first level of length codes */ + let dmask; /* mask for first level of distance codes */ + let here; /* retrieved table entry */ + let op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ - var len; /* match length, unused bytes */ - var dist; /* match distance */ - var from; /* where to copy match from */ - var from_source; + let len; /* match length, unused bytes */ + let dist; /* match distance */ + let from; /* where to copy match from */ + 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 */ - state = strm.state; + const state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; diff --git a/lib/zlib/inflate.js b/lib/zlib/inflate.js index 56f53b6..d3f1f9b 100644 --- a/lib/zlib/inflate.js +++ b/lib/zlib/inflate.js @@ -19,102 +19,82 @@ // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. -var adler32 = require('./adler32'); -var crc32 = require('./crc32'); -var inflate_fast = require('./inffast'); -var inflate_table = require('./inftrees'); +const adler32 = require('./adler32'); +const crc32 = require('./crc32'); +const inflate_fast = require('./inffast'); +const inflate_table = require('./inftrees'); -var CODES = 0; -var LENS = 1; -var DISTS = 2; +const CODES = 0; +const LENS = 1; +const DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ - -/* Allowed flush values; see deflate() and inflate() below for details */ -//var Z_NO_FLUSH = 0; -//var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -//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; +const { + Z_FINISH, Z_BLOCK, Z_TREES, + Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR, Z_BUF_ERROR, + Z_DEFLATED +} = require('./constants'); /* STATES ====================================================================*/ /* ===========================================================================*/ -var HEAD = 1; /* i: waiting for magic header */ -var FLAGS = 2; /* i: waiting for method and flags (gzip) */ -var TIME = 3; /* i: waiting for modification time (gzip) */ -var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -var EXLEN = 5; /* i: waiting for extra length (gzip) */ -var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -var NAME = 7; /* i: waiting for end of file name (gzip) */ -var COMMENT = 8; /* i: waiting for end of comment (gzip) */ -var HCRC = 9; /* i: waiting for header crc (gzip) */ -var DICTID = 10; /* i: waiting for dictionary check value */ -var DICT = 11; /* waiting for inflateSetDictionary() call */ -var 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 */ -var STORED = 14; /* i: waiting for stored size (length and complement) */ -var 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 */ -var TABLE = 17; /* i: waiting for dynamic block table lengths */ -var LENLENS = 18; /* i: waiting for code length code lengths */ -var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -var LEN_ = 20; /* i: same as LEN below, but only first time in */ -var LEN = 21; /* i: waiting for length/lit/eob code */ -var LENEXT = 22; /* i: waiting for length extra bits */ -var DIST = 23; /* i: waiting for distance code */ -var DISTEXT = 24; /* i: waiting for distance extra bits */ -var MATCH = 25; /* o: waiting for output space to copy string */ -var LIT = 26; /* o: waiting for output space to write literal */ -var CHECK = 27; /* i: waiting for 32-bit check value */ -var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -var DONE = 29; /* finished check, done -- remain here until reset */ -var BAD = 30; /* got a data error -- remain here until reset */ -var MEM = 31; /* got an inflate() memory error -- remain here until reset */ -var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ +const HEAD = 1; /* i: waiting for magic header */ +const FLAGS = 2; /* i: waiting for method and flags (gzip) */ +const TIME = 3; /* i: waiting for modification time (gzip) */ +const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +const EXLEN = 5; /* i: waiting for extra length (gzip) */ +const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +const NAME = 7; /* i: waiting for end of file name (gzip) */ +const COMMENT = 8; /* i: waiting for end of comment (gzip) */ +const HCRC = 9; /* i: waiting for header crc (gzip) */ +const DICTID = 10; /* i: waiting for dictionary check value */ +const DICT = 11; /* waiting for inflateSetDictionary() call */ +const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +const STORED = 14; /* i: waiting for stored size (length and complement) */ +const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +const COPY = 16; /* i/o: waiting for input or output to copy stored block */ +const TABLE = 17; /* i: waiting for dynamic block table lengths */ +const LENLENS = 18; /* i: waiting for code length code lengths */ +const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +const LEN_ = 20; /* i: same as LEN below, but only first time in */ +const LEN = 21; /* i: waiting for length/lit/eob code */ +const LENEXT = 22; /* i: waiting for length extra bits */ +const DIST = 23; /* i: waiting for distance code */ +const DISTEXT = 24; /* i: waiting for distance extra bits */ +const MATCH = 25; /* o: waiting for output space to copy string */ +const LIT = 26; /* o: waiting for output space to write literal */ +const CHECK = 27; /* i: waiting for 32-bit check value */ +const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +const DONE = 29; /* finished check, done -- remain here until reset */ +const BAD = 30; /* got a data error -- remain here until reset */ +const MEM = 31; /* got an inflate() memory error -- remain here until reset */ +const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); +const ENOUGH_LENS = 852; +const ENOUGH_DISTS = 592; +//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); -var MAX_WBITS = 15; +const MAX_WBITS = 15; /* 32K LZ77 window */ -var DEF_WBITS = MAX_WBITS; +const DEF_WBITS = MAX_WBITS; -function zswap32(q) { +const zswap32 = (q) => { + return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); -} +}; function InflateState() { @@ -175,11 +155,11 @@ function InflateState() { this.was = 0; /* initial length of match */ } -function inflateResetKeep(strm) { - var state; + +const inflateResetKeep = (strm) => { 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.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ @@ -200,27 +180,27 @@ function inflateResetKeep(strm) { state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; -} +}; -function inflateReset(strm) { - var state; + +const inflateReset = (strm) => { if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; + const state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); -} +}; -function inflateReset2(strm, windowBits) { - var wrap; - var state; + +const inflateReset2 = (strm, windowBits) => { + let wrap; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; + const state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { @@ -246,31 +226,32 @@ function inflateReset2(strm, windowBits) { state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); -} +}; -function inflateInit2(strm, windowBits) { - var ret; - var state; + +const inflateInit2 = (strm, windowBits) => { if (!strm) { return Z_STREAM_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; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); + const ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; -} +}; + + +const inflateInit = (strm) => { -function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); -} +}; /* @@ -283,20 +264,20 @@ function inflateInit(strm) { used for threaded applications, since the rewriting of the tables and virgin 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) */ if (virgin) { - var sym; - lenfix = new Int32Array(512); distfix = new Int32Array(32); /* literal/length table */ - sym = 0; + let sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } @@ -318,7 +299,7 @@ function fixedtables(state) { state.lenbits = 9; state.distcode = distfix; state.distbits = 5; -} +}; /* @@ -335,9 +316,10 @@ function fixedtables(state) { 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. */ -function updatewindow(strm, src, end, copy) { - var dist; - var state = strm.state; +const updatewindow = (strm, src, end, copy) => { + + let dist; + const state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { @@ -375,33 +357,35 @@ function updatewindow(strm, src, end, copy) { } } 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 */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + let state; + 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 || @@ -1467,42 +1451,44 @@ function inflate(strm, flush) { ret = Z_BUF_ERROR; } return ret; -} +}; -function inflateEnd(strm) { + +const inflateEnd = (strm) => { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } - var state = strm.state; + let state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; -} +}; -function inflateGetHeader(strm, head) { - var state; + +const inflateGetHeader = (strm, head) => { /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; + const state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; -} +}; -function inflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - var state; - var dictid; - var ret; +const inflateSetDictionary = (strm, dictionary) => { + const dictLength = dictionary.length; + + let state; + let dictid; + let ret; /* check state */ if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } @@ -1531,7 +1517,8 @@ function inflateSetDictionary(strm, dictionary) { state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; -} +}; + exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; diff --git a/lib/zlib/inftrees.js b/lib/zlib/inftrees.js index f29aa31..b5b29d3 100644 --- a/lib/zlib/inftrees.js +++ b/lib/zlib/inftrees.js @@ -19,66 +19,66 @@ // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. -var MAXBITS = 15; -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); +const MAXBITS = 15; +const ENOUGH_LENS = 852; +const ENOUGH_DISTS = 592; +//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); -var CODES = 0; -var LENS = 1; -var DISTS = 2; +const CODES = 0; +const LENS = 1; +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, 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, 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, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 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, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 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 */ - var len = 0; /* a code's length in bits */ - var sym = 0; /* index of code symbols */ - var min = 0, max = 0; /* minimum and maximum code lengths */ - var root = 0; /* number of index bits for root table */ - var curr = 0; /* number of index bits for current table */ - var drop = 0; /* code bits to drop for sub-table */ - var left = 0; /* number of prefix codes available */ - var used = 0; /* code entries in table used */ - var huff = 0; /* Huffman code */ - var incr; /* for incrementing code, index */ - var fill; /* index for replicating entries */ - var low; /* low bits for current root entry */ - var mask; /* mask for low root bits */ - var next; /* next available space in table */ - var base = null; /* base value table to use */ - var base_index = 0; -// var shoextra; /* extra bits table to use */ - var end; /* use base and extra for symbol > end */ - var 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 */ - var extra = null; - var extra_index = 0; + let len = 0; /* a code's length in bits */ + let sym = 0; /* index of code symbols */ + let min = 0, max = 0; /* minimum and maximum code lengths */ + let root = 0; /* number of index bits for root table */ + let curr = 0; /* number of index bits for current table */ + let drop = 0; /* code bits to drop for sub-table */ + let left = 0; /* number of prefix codes available */ + let used = 0; /* code entries in table used */ + let huff = 0; /* Huffman code */ + let incr; /* for incrementing code, index */ + let fill; /* index for replicating entries */ + let low; /* low bits for current root entry */ + let mask; /* mask for low root bits */ + let next; /* next available space in table */ + let base = null; /* base value table to use */ + let base_index = 0; +// let shoextra; /* extra bits table to use */ + let end; /* use base and extra for symbol > end */ + const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + let extra = null; + 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 @@ -339,3 +339,6 @@ module.exports = function inflate_table(type, lens, lens_index, codes, table, ta opts.bits = root; return 0; }; + + +module.exports = inflate_table; diff --git a/lib/zlib/trees.js b/lib/zlib/trees.js index 02ce472..7a72281 100644 --- a/lib/zlib/trees.js +++ b/lib/zlib/trees.js @@ -25,32 +25,32 @@ /* ===========================================================================*/ -//var Z_FILTERED = 1; -//var Z_HUFFMAN_ONLY = 2; -//var Z_RLE = 3; -var Z_FIXED = 4; -//var Z_DEFAULT_STRATEGY = 0; +//const Z_FILTERED = 1; +//const Z_HUFFMAN_ONLY = 2; +//const Z_RLE = 3; +const Z_FIXED = 4; +//const 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; +const Z_BINARY = 0; +const Z_TEXT = 1; +//const Z_ASCII = 1; // = Z_TEXT +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 -var STORED_BLOCK = 0; -var STATIC_TREES = 1; -var DYN_TREES = 2; +const STORED_BLOCK = 0; +const STATIC_TREES = 1; +const DYN_TREES = 2; /* The three kinds of block type */ -var MIN_MATCH = 3; -var MAX_MATCH = 258; +const MIN_MATCH = 3; +const MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h @@ -58,28 +58,28 @@ var MAX_MATCH = 258; * Internal compression state. */ -var LENGTH_CODES = 29; +const LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ -var LITERALS = 256; +const LITERALS = 256; /* 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 */ -var D_CODES = 30; +const D_CODES = 30; /* number of distance codes */ -var BL_CODES = 19; +const BL_CODES = 19; /* 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 */ -var MAX_BITS = 15; +const MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ -var Buf_size = 16; +const Buf_size = 16; /* size of bit buffer in bi_buf */ @@ -87,33 +87,33 @@ var Buf_size = 16; * Constants */ -var MAX_BL_BITS = 7; +const MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ -var END_BLOCK = 256; +const END_BLOCK = 256; /* 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) */ -var REPZ_3_10 = 17; +const REPZ_3_10 = 17; /* 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) */ /* eslint-disable comma-spacing,array-bracket-spacing */ -var 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]; +const extra_lbits = /* extra bits for each length code */ + 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 */ - [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]; +const extra_dbits = /* extra bits for each distance code */ + 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 */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; +const extra_blbits = /* extra bits for each bit length code */ + new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]); -var bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +const bl_order = + 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 */ /* 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 -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 -var static_ltree = new Array((L_CODES + 2) * 2); +const static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* 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 @@ -137,28 +137,28 @@ zero(static_ltree); * below). */ -var static_dtree = new Array(D_CODES * 2); +const static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ -var _dist_code = new Array(DIST_CODE_LEN); +const _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * 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); /* 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); /* 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); /* 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; -var static_d_desc; -var static_bl_desc; +let static_l_desc; +let static_d_desc; +let static_bl_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)]; -} +}; /* =========================================================================== * Output a short LSB first on the stream. * 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)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; -} +}; /* =========================================================================== * Send a value on a given number of 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)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; 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_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*/); -} +}; /* =========================================================================== @@ -233,21 +236,23 @@ function send_code(s, c, tree) { * method would use a table) * IN assertion: 1 <= len <= 15 */ -function bi_reverse(code, len) { - var res = 0; +const bi_reverse = (code, len) => { + + let res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; -} +}; /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ -function bi_flush(s) { +const bi_flush = (s) => { + if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; @@ -258,7 +263,7 @@ function bi_flush(s) { s.bi_buf >>= 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 * not null. */ -function gen_bitlen(s, desc) +const gen_bitlen = (s, desc) => // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { - var tree = desc.dyn_tree; - var max_code = desc.max_code; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var extra = desc.stat_desc.extra_bits; - var base = desc.stat_desc.extra_base; - var max_length = desc.stat_desc.max_length; - var h; /* heap index */ - var n, m; /* iterate over the tree elements */ - var bits; /* bit length */ - var xbits; /* extra bits */ - var f; /* frequency */ - var overflow = 0; /* number of elements with bit length too large */ + const tree = desc.dyn_tree; + const max_code = desc.max_code; + const stree = desc.stat_desc.static_tree; + const has_stree = desc.stat_desc.has_stree; + const extra = desc.stat_desc.extra_bits; + const base = desc.stat_desc.extra_base; + const max_length = desc.stat_desc.max_length; + let h; /* heap index */ + let n, m; /* iterate over the tree elements */ + let bits; /* bit length */ + let xbits; /* extra bits */ + let f; /* frequency */ + let overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; @@ -357,7 +362,7 @@ function gen_bitlen(s, desc) n--; } } -} +}; /* =========================================================================== @@ -368,15 +373,15 @@ function gen_bitlen(s, desc) * OUT assertion: the field code is set for all tree elements of non * 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 */ // int max_code; /* largest code with non zero frequency */ // 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 */ - var code = 0; /* running code value */ - var bits; /* bit index */ - var n; /* code index */ + const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + let code = 0; /* running code value */ + let bits; /* bit index */ + let n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. @@ -392,7 +397,7 @@ function gen_codes(tree, max_code, bl_count) //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); 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; } /* Now reverse the bits */ 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) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } -} +}; /* =========================================================================== * Initialize the various 'constant' tables. */ -function tr_static_init() { - var n; /* iterates over tree elements */ - var bits; /* bit counter */ - var length; /* length value */ - var code; /* code value */ - var dist; /* distance index */ - var bl_count = new Array(MAX_BITS + 1); +const tr_static_init = () => { + + let n; /* iterates over tree elements */ + let bits; /* bit counter */ + let length; /* length value */ + let code; /* code value */ + let dist; /* distance index */ + const bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // 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_init_done = true; -} +}; /* =========================================================================== * Initialize a new block. */ -function init_block(s) { - var n; /* iterates over tree elements */ +const init_block = (s) => { + + let n; /* iterates over tree elements */ /* Initialize the trees. */ 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.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; -} +}; /* =========================================================================== * 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) { put_short(s, s.bi_buf); @@ -537,13 +544,13 @@ function bi_windup(s) } s.bi_buf = 0; s.bi_valid = 0; -} +}; /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ -function copy_block(s, buf, len, header) +const copy_block = (s, buf, len, header) => //DeflateState *s; //charf *buf; /* the input data */ //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 += len; -} +}; /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ -function smaller(tree, n, m, depth) { - var _n2 = n * 2; - var _m2 = m * 2; +const smaller = (tree, n, m, depth) => { + + const _n2 = n * 2; + const _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); -} +}; /* =========================================================================== * 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 * two sons). */ -function pqdownheap(s, tree, k) +const pqdownheap = (s, tree, k) => // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { - var v = s.heap[k]; - var j = k << 1; /* left son of k */ + const v = s.heap[k]; + let j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && @@ -603,25 +611,25 @@ function pqdownheap(s, tree, k) j <<= 1; } s.heap[k] = v; -} +}; // inlined manually -// var SMALLEST = 1; +// const SMALLEST = 1; /* =========================================================================== * 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; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { - var dist; /* distance of matched string */ - var lc; /* match length or unmatched char (if dist == 0) */ - var lx = 0; /* running index in l_buf */ - var code; /* the code to send */ - var extra; /* number of extra bits to send */ + let dist; /* distance of matched string */ + let lc; /* match length or unmatched char (if dist == 0) */ + let lx = 0; /* running index in l_buf */ + let code; /* the code to send */ + let extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { @@ -661,7 +669,7 @@ function compress_block(s, ltree, dtree) } 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 * 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; // tree_desc *desc; /* the tree descriptor */ { - var tree = desc.dyn_tree; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var elems = desc.stat_desc.elems; - var n, m; /* iterate over heap elements */ - var max_code = -1; /* largest code with non zero frequency */ - var node; /* new node being created */ + const tree = desc.dyn_tree; + const stree = desc.stat_desc.static_tree; + const has_stree = desc.stat_desc.has_stree; + const elems = desc.stat_desc.elems; + let n, m; /* iterate over heap elements */ + let max_code = -1; /* largest code with non zero frequency */ + let node; /* new node being created */ /* 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]. @@ -761,27 +769,27 @@ function build_tree(s, desc) /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); -} +}; /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ -function scan_tree(s, tree, max_code) +const scan_tree = (s, tree, max_code) => // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ + let n; /* iterates over all tree elements */ + let prevlen = -1; /* last emitted length */ + 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 */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ + let count = 0; /* repeat count of the current code */ + let max_count = 7; /* max repeat count */ + let min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; @@ -827,27 +835,27 @@ function scan_tree(s, tree, max_code) min_count = 4; } } -} +}; /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ -function send_tree(s, tree, max_code) +const send_tree = (s, tree, max_code) => // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ + let n; /* iterates over all tree elements */ + let prevlen = -1; /* last emitted length */ + 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 */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ + let count = 0; /* repeat count of the current code */ + let max_count = 7; /* max repeat count */ + let min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { @@ -898,15 +906,16 @@ function send_tree(s, tree, max_code) min_count = 4; } } -} +}; /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ -function build_bl_tree(s) { - var max_blindex; /* index of last bit length code of non zero freq */ +const build_bl_tree = (s) => { + + let max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ 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)); 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. * 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; // 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 <= 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 */ //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}). * 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 * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ - var black_mask = 0xf3ffc07f; - var n; + let black_mask = 0xf3ffc07f; + let n; /* Check for non-textual ("black-listed") bytes. */ 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. */ return Z_BINARY; -} +}; -var static_init_done = false; +let static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ -function _tr_init(s) +const _tr_init = (s) => { if (!static_init_done) { @@ -1036,13 +1045,13 @@ function _tr_init(s) /* Initialize the first block of the first file: */ init_block(s); -} +}; /* =========================================================================== * Send a stored block */ -function _tr_stored_block(s, buf, stored_len, last) +const _tr_stored_block = (s, buf, stored_len, last) => //DeflateState *s; //charf *buf; /* 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 */ copy_block(s, buf, stored_len, true); /* with header */ -} +}; /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * 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_code(s, END_BLOCK, static_ltree); bi_flush(s); -} +}; /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * 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; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { - var 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 opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + let max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ 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, // s->compressed_len-7*last)); -} +}; /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ -function _tr_tally(s, dist, lc) +const _tr_tally = (s, dist, lc) => // deflate_state *s; // unsigned dist; /* distance of matched string */ // 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 + 1] = dist & 0xff; @@ -1211,7 +1220,7 @@ function _tr_tally(s, dist, lc) * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ -} +}; exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; diff --git a/package.json b/package.json index 82b92e1..f4ebf80 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,8 @@ "prepublishOnly": "npm run gh-doc" }, "devDependencies": { + "@babel/preset-env": "^7.12.1", + "@rollup/plugin-babel": "^5.2.1", "@rollup/plugin-commonjs": "^16.0.0", "@rollup/plugin-node-resolve": "^10.0.0", "eslint": "^7.13.0", diff --git a/rollup.config.js b/rollup.config.js index 39df778..9e34915 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -2,6 +2,8 @@ import nodeResolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import pkg from './package.json'; import { terser } from 'rollup-plugin-terser'; +import babel from '@rollup/plugin-babel'; + const banner = { banner() { @@ -10,8 +12,21 @@ const banner = { } const plugins = [ nodeResolve(), commonjs(), banner ]; +const plugins_es5 = [ + nodeResolve(), + commonjs(), + babel({ + babelHelpers: 'bundled', + presets: [ + [ "@babel/preset-env" ] + ] + }), + banner +]; + export default [ + // es6 { input: 'index.js', output: [ @@ -35,5 +50,31 @@ export default [ { file: 'dist/pako_inflate.min.js', format: 'umd', name: 'pako', plugins: [ terser() ] } ], 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 } + ]; diff --git a/test/chunks.js b/test/chunks.js index 57bb92d..c8acaa4 100644 --- a/test/chunks.js +++ b/test/chunks.js @@ -1,27 +1,27 @@ 'use strict'; -var assert = require('assert'); -var helpers = require('./helpers'); -var pako = require('../index'); +const assert = require('assert'); +const { loadSamples } = require('./helpers'); +const pako = require('../index'); -var samples = helpers.loadSamples(); +const samples = loadSamples(); function randomBuf(size) { - var buf = new Uint8Array(size); - for (var i = 0; i < size; i++) { + const buf = new Uint8Array(size); + for (let i = 0; i < size; i++) { buf[i] = Math.round(Math.random() * 256); } return buf; } function testChunk(buf, expected, packer, chunkSize) { - var i, _in, count, pos, size, expFlushCount; + let i, _in, count, pos, size, expFlushCount; - var onData = packer.onData; - var flushCount = 0; + let onData = packer.onData; + let flushCount = 0; packer.onData = function () { flushCount++; @@ -46,51 +46,51 @@ function testChunk(buf, expected, packer, chunkSize) { 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 () { - var buf = randomBuf(100); - var deflated = pako.deflate(buf); + it('deflate 100b by 1b chunk', () => { + const buf = randomBuf(100); + const deflated = pako.deflate(buf); testChunk(buf, deflated, new pako.Deflate(), 1); }); - it('deflate 20000b by 10b chunk', function () { - var buf = randomBuf(20000); - var deflated = pako.deflate(buf); + it('deflate 20000b by 10b chunk', () => { + const buf = randomBuf(20000); + const deflated = pako.deflate(buf); testChunk(buf, deflated, new pako.Deflate(), 10); }); - it('inflate 100b result by 1b chunk', function () { - var buf = randomBuf(100); - var deflated = pako.deflate(buf); + it('inflate 100b result by 1b chunk', () => { + const buf = randomBuf(100); + const deflated = pako.deflate(buf); testChunk(deflated, buf, new pako.Inflate(), 1); }); - it('inflate 20000b result by 10b chunk', function () { - var buf = randomBuf(20000); - var deflated = pako.deflate(buf); + it('inflate 20000b result by 10b chunk', () => { + const buf = randomBuf(20000); + const deflated = pako.deflate(buf); testChunk(deflated, buf, new pako.Inflate(), 10); }); }); -describe('Dummy push (force end)', function () { +describe('Dummy push (force end)', () => { - it('deflate end', function () { - var data = samples.lorem_utf_100k; + it('deflate end', () => { + const data = samples.lorem_utf_100k; - var deflator = new pako.Deflate(); + const deflator = new pako.Deflate(); deflator.push(data); deflator.push([], true); assert.deepStrictEqual(deflator.result, pako.deflate(data)); }); - it('inflate end', function () { - var data = pako.deflate(samples.lorem_utf_100k); + it('inflate end', () => { + const data = pako.deflate(samples.lorem_utf_100k); - var inflator = new pako.Inflate(); + const inflator = new pako.Inflate(); inflator.push(data); 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 () { - var i; - var data = new Uint8Array(1024 * 16 + 1); + it('should be ok on buffer border', () => { + let i; + const data = new Uint8Array(1024 * 16 + 1); for (i = 0; i < data.length; i++) { 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++) { inflator.push(deflated.subarray(i, i + 1), false); diff --git a/test/deflate.js b/test/deflate.js index e8fd619..fc96421 100644 --- a/test/deflate.js +++ b/test/deflate.js @@ -1,192 +1,191 @@ 'use strict'; -var zlib = require('zlib'); +const zlib = require('zlib'); -var pako = require('../index'); -var helpers = require('./helpers'); -var testSamples = helpers.testSamples; -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const pako = require('../index'); +const { testSamples, loadSamples } = require('./helpers'); +const assert = require('assert'); +const fs = require('fs'); +const 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, {}); }); - it('deflate raw, no options', function () { + it('deflate raw, no options', () => { testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, {}); }); // 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 }); }); }); -describe('Deflate levels', function () { +describe('Deflate levels', () => { - it('level 9', function () { + it('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 }); }); - it('level 7', function () { + it('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 }); }); - it('level 5', function () { + it('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 }); }); - it('level 3', function () { + it('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 }); }); - it('level 1', function () { + it('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 }); }); - it('level -1 (implicit default)', function () { + it('level -1 (implicit default)', () => { 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 }); }); - it('windowBits 14', function () { + it('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 }); }); - it('windowBits 12', function () { + it('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 }); }); - it('windowBits 10', function () { + it('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 }); }); - it('windowBits 8', function () { + it('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 }); }); }); -describe('Deflate memLevel', function () { +describe('Deflate memLevel', () => { - it('memLevel 9', function () { + it('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 }); }); - it('memLevel 7', function () { + it('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 }); }); - it('memLevel 5', function () { + it('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 }); }); - it('memLevel 3', function () { + it('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 }); }); - it('memLevel 1', function () { + it('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 }); }); - it('Z_FILTERED', function () { + it('Z_FILTERED', () => { 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 }); }); - it('Z_RLE', function () { + it('Z_RLE', () => { testSamples(zlib.deflateSync, pako.deflate, samples, { strategy: 3 }); }); - it('Z_FIXED', function () { + it('Z_FIXED', () => { 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 - it('level 4', function () { + it('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 }); }); - it.skip('level 0', function () { + it.skip('level 0', () => { testSamples(zlib.deflateRawSync, pako.deflateRaw, samples, { level: 0 }); }); }); -describe('Deflate dictionary', function () { +describe('Deflate dictionary', () => { - it('trivial dictionary', function () { - var dict = Buffer.from('abcdefghijklmnoprstuvwxyz'); + it('trivial dictionary', () => { + const dict = Buffer.from('abcdefghijklmnoprstuvwxyz'); testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: dict }); }); - it('spdy dictionary', function () { - var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); + it('spdy dictionary', () => { + const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); testSamples(zlib.deflateSync, pako.deflate, samples, { dictionary: spdyDict }); }); - it('handles multiple pushes', function () { - var dict = Buffer.from('abcd'); - var deflate = new pako.Deflate({ dictionary: dict }); + it('handles multiple pushes', () => { + const dict = Buffer.from('abcd'); + const deflate = new pako.Deflate({ dictionary: dict }); 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); } - var uncompressed = pako.inflate(Buffer.from(deflate.result), { dictionary: dict }); + const uncompressed = pako.inflate(Buffer.from(deflate.result), { dictionary: dict }); assert.deepStrictEqual( new Uint8Array(Buffer.from('hellohello world')), @@ -204,12 +203,12 @@ describe('Deflate dictionary', function () { }); -describe('Deflate issues', function () { +describe('Deflate issues', () => { - it('#78', function () { - var data = fs.readFileSync(path.join(__dirname, 'fixtures', 'issue_78.bin')); - var deflatedPakoData = pako.deflate(data, { memLevel: 1 }); - var inflatedPakoData = pako.inflate(deflatedPakoData); + it('#78', () => { + const data = fs.readFileSync(path.join(__dirname, 'fixtures', 'issue_78.bin')); + const deflatedPakoData = pako.deflate(data, { memLevel: 1 }); + const inflatedPakoData = pako.inflate(deflatedPakoData); assert.strictEqual(data.length, inflatedPakoData.length); }); diff --git a/test/deflate_cover.js b/test/deflate_cover.js index 0b7bc35..07ffc1f 100644 --- a/test/deflate_cover.js +++ b/test/deflate_cover.js @@ -2,48 +2,48 @@ 'use strict'; -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); -var c = require('../lib/zlib/constants'); -var msg = require('../lib/zlib/messages'); -var zlib_deflate = require('../lib/zlib/deflate'); -var ZStream = require('../lib/zlib/zstream'); +const c = require('../lib/zlib/constants'); +const msg = require('../lib/zlib/messages'); +const zlib_deflate = require('../lib/zlib/deflate'); +const ZStream = require('../lib/zlib/zstream'); -var pako = require('../index'); +const pako = require('../index'); -var short_sample = 'hello world'; -var long_sample = fs.readFileSync(path.join(__dirname, 'fixtures/samples/lorem_en_100k.txt')); +const short_sample = 'hello world'; +const long_sample = fs.readFileSync(path.join(__dirname, 'fixtures/samples/lorem_en_100k.txt')); function testDeflate(data, opts, flush) { - var deflator = new pako.Deflate(opts); + const deflator = new pako.Deflate(opts); deflator.push(data, flush); deflator.push(data, true); assert.strictEqual(deflator.err, 0, msg[deflator.err]); } -describe('Deflate support', function () { - it('stored', function () { +describe('Deflate support', () => { + it('stored', () => { testDeflate(short_sample, { level: 0, chunkSize: 200 }, 0); testDeflate(short_sample, { level: 0, chunkSize: 10 }, 5); }); - it('fast', function () { + it('fast', () => { testDeflate(short_sample, { level: 1, chunkSize: 10 }, 5); testDeflate(long_sample, { level: 1, memLevel: 1, chunkSize: 10 }, 0); }); - it('slow', function () { + it('slow', () => { testDeflate(short_sample, { level: 4, chunkSize: 10 }, 5); 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, chunkSize: 10 }, 5); testDeflate(long_sample, { strategy: 3, chunkSize: 10 }, 0); }); - it('huffman', function () { + it('huffman', () => { testDeflate(short_sample, { strategy: 2 }, 0); testDeflate(short_sample, { strategy: 2, chunkSize: 10 }, 5); 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 - it('inflate bad parameters', function () { - var ret, strm; + it('inflate bad parameters', () => { + let ret, strm; ret = zlib_deflate.deflate(null, 0); assert(ret === c.Z_STREAM_ERROR); diff --git a/test/gzip_specials.js b/test/gzip_specials.js index e1df7d3..4dbf8e8 100644 --- a/test/gzip_specials.js +++ b/test/gzip_specials.js @@ -1,11 +1,11 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); -var pako = require('../index'); +const pako = require('../index'); function a2s(array) { @@ -13,11 +13,11 @@ function a2s(array) { } -describe('Gzip special cases', function () { +describe('Gzip special cases', () => { - it('Read custom headers', function () { - var data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-headers.gz')); - var inflator = new pako.Inflate(); + it('Read custom headers', () => { + const data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-headers.gz')); + const inflator = new pako.Inflate(); inflator.push(data, true); assert.strictEqual(inflator.header.name, 'test name'); @@ -25,10 +25,10 @@ describe('Gzip special cases', function () { assert.strictEqual(a2s(inflator.header.extra), 'test extra'); }); - it('Write custom headers', function () { - var data = ' '; + it('Write custom headers', () => { + const data = ' '; - var deflator = new pako.Deflate({ + const deflator = new pako.Deflate({ gzip: true, header: { hcrc: true, @@ -41,13 +41,13 @@ describe('Gzip special cases', function () { }); deflator.push(data, true); - var inflator = new pako.Inflate({ to: 'string' }); + const inflator = new pako.Inflate({ to: 'string' }); inflator.push(deflator.result, true); assert.strictEqual(inflator.err, 0); assert.strictEqual(inflator.result, data); - var header = inflator.header; + const header = inflator.header; assert.strictEqual(header.time, 1234567); assert.strictEqual(header.os, 15); assert.strictEqual(header.name, 'test name'); @@ -55,9 +55,9 @@ describe('Gzip special cases', function () { assert.deepStrictEqual(header.extra, new Uint8Array([ 4, 5, 6 ])); }); - it('Read stream with SYNC marks', function () { - var inflator, strm, _in, len, pos = 0, i = 0; - var data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-joined.gz')); + it('Read stream with SYNC marks', () => { + let inflator, strm, _in, len, pos = 0, i = 0; + const data = fs.readFileSync(path.join(__dirname, 'fixtures/gzip-joined.gz')); do { len = data.length - pos; diff --git a/test/helpers.js b/test/helpers.js index 0483d2c..260fce8 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -1,24 +1,24 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); -var pako = require('../index'); +const pako = require('../index'); // Load fixtures to test // return: { 'filename1': content1, 'filename2': content2, ...} // function loadSamples(subdir) { - var result = {}; - var dir = path.join(__dirname, 'fixtures', subdir || 'samples'); + const result = {}; + const dir = path.join(__dirname, 'fixtures', subdir || 'samples'); fs.readdirSync(dir).sort().forEach(function (sample) { - var filepath = path.join(dir, sample), - extname = path.extname(filepath), - basename = path.basename(filepath, extname), - content = new Uint8Array(fs.readFileSync(filepath)); + const filepath = path.join(dir, sample); + const extname = path.extname(filepath); + const basename = path.basename(filepath, extname); + const content = new Uint8Array(fs.readFileSync(filepath)); 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. // 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 if (zlib_options.windowBits < 0) { zlib_options.windowBits = -zlib_options.windowBits; } - var zlib_result = zlib_method(data, zlib_options); - var pako_result = pako_method(data, options); + const zlib_result = zlib_method(data, zlib_options); + const pako_result = pako_method(data, options); // One more hack: gzip header contains OS code, that can vary. // 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) { Object.keys(samples).forEach(function (name) { - var data = samples[name]; + const data = samples[name]; testSingle(zlib_method, pako_method, data, options); }); @@ -61,7 +61,7 @@ function testSamples(zlib_method, pako_method, samples, options) { 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 // @@ -77,6 +77,6 @@ function testInflate(samples, inflateOptions, deflateOptions) { } -exports.testSamples = testSamples; -exports.testInflate = testInflate; -exports.loadSamples = loadSamples; +module.exports.testSamples = testSamples; +module.exports.testInflate = testInflate; +module.exports.loadSamples = loadSamples; diff --git a/test/inflate.js b/test/inflate.js index bf2f4ec..7a29c5b 100644 --- a/test/inflate.js +++ b/test/inflate.js @@ -1,209 +1,208 @@ 'use strict'; -var zlib = require('zlib'); -var assert = require('assert'); +const zlib = require('zlib'); +const assert = require('assert'); -var pako = require('../index'); -var helpers = require('./helpers'); -var testInflate = helpers.testInflate; +const pako = require('../index'); +const { testInflate, testSamples, loadSamples } = require('./helpers'); -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, {}, {}); }); - it('inflate raw, no options', function () { + it('inflate raw, no options', () => { testInflate(samples, { raw: true }, { raw: true }); }); - it('inflate raw from compressed samples', function () { - var compressed_samples = helpers.loadSamples('samples_deflated_raw'); - helpers.testSamples(zlib.inflateRawSync, pako.inflateRaw, compressed_samples, {}); + it('inflate raw from compressed samples', () => { + const compressed_samples = loadSamples('samples_deflated_raw'); + testSamples(zlib.inflateRawSync, pako.inflateRaw, compressed_samples, {}); }); }); -describe('Inflate ungzip', function () { - it('with autodetect', function () { +describe('Inflate ungzip', () => { + it('with autodetect', () => { testInflate(samples, {}, { gzip: true }); }); - it('with method set directly', function () { + it('with method set directly', () => { testInflate(samples, { windowBits: 16 }, { gzip: true }); }); }); -describe('Inflate levels', function () { +describe('Inflate levels', () => { - it('level 9', function () { + it('level 9', () => { testInflate(samples, {}, { level: 9 }); }); - it('level 8', function () { + it('level 8', () => { testInflate(samples, {}, { level: 8 }); }); - it('level 7', function () { + it('level 7', () => { testInflate(samples, {}, { level: 7 }); }); - it('level 6', function () { + it('level 6', () => { testInflate(samples, {}, { level: 6 }); }); - it('level 5', function () { + it('level 5', () => { testInflate(samples, {}, { level: 5 }); }); - it('level 4', function () { + it('level 4', () => { testInflate(samples, {}, { level: 4 }); }); - it('level 3', function () { + it('level 3', () => { testInflate(samples, {}, { level: 3 }); }); - it('level 2', function () { + it('level 2', () => { testInflate(samples, {}, { level: 2 }); }); - it('level 1', function () { + it('level 1', () => { testInflate(samples, {}, { level: 1 }); }); - it('level 0', function () { + it('level 0', () => { testInflate(samples, {}, { level: 0 }); }); }); -describe('Inflate windowBits', function () { +describe('Inflate windowBits', () => { - it('windowBits 15', function () { + it('windowBits 15', () => { testInflate(samples, {}, { windowBits: 15 }); }); - it('windowBits 14', function () { + it('windowBits 14', () => { testInflate(samples, {}, { windowBits: 14 }); }); - it('windowBits 13', function () { + it('windowBits 13', () => { testInflate(samples, {}, { windowBits: 13 }); }); - it('windowBits 12', function () { + it('windowBits 12', () => { testInflate(samples, {}, { windowBits: 12 }); }); - it('windowBits 11', function () { + it('windowBits 11', () => { testInflate(samples, {}, { windowBits: 11 }); }); - it('windowBits 10', function () { + it('windowBits 10', () => { testInflate(samples, {}, { windowBits: 10 }); }); - it('windowBits 9', function () { + it('windowBits 9', () => { testInflate(samples, {}, { windowBits: 9 }); }); - it('windowBits 8', function () { + it('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 }); }); - it('Z_FILTERED', function () { + it('Z_FILTERED', () => { testInflate(samples, {}, { strategy: 1 }); }); - it('Z_HUFFMAN_ONLY', function () { + it('Z_HUFFMAN_ONLY', () => { testInflate(samples, {}, { strategy: 2 }); }); - it('Z_RLE', function () { + it('Z_RLE', () => { testInflate(samples, {}, { strategy: 3 }); }); - it('Z_FIXED', function () { + it('Z_FIXED', () => { 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 - it('level 9', function () { + it('level 9', () => { testInflate(samples, { raw: true }, { level: 9, raw: true }); }); - it('level 8', function () { + it('level 8', () => { testInflate(samples, { raw: true }, { level: 8, raw: true }); }); - it('level 7', function () { + it('level 7', () => { testInflate(samples, { raw: true }, { level: 7, raw: true }); }); - it('level 6', function () { + it('level 6', () => { testInflate(samples, { raw: true }, { level: 6, raw: true }); }); - it('level 5', function () { + it('level 5', () => { testInflate(samples, { raw: true }, { level: 5, raw: true }); }); - it('level 4', function () { + it('level 4', () => { testInflate(samples, { raw: true }, { level: 4, raw: true }); }); - it('level 3', function () { + it('level 3', () => { testInflate(samples, { raw: true }, { level: 3, raw: true }); }); - it('level 2', function () { + it('level 2', () => { testInflate(samples, { raw: true }, { level: 2, raw: true }); }); - it('level 1', function () { + it('level 1', () => { testInflate(samples, { raw: true }, { level: 1, raw: true }); }); - it('level 0', function () { + it('level 0', () => { 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 () { - // var 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 ]); + it('should throw on the wrong dictionary', () => { + // const zCompressed = helpers.deflateSync('world', { dictionary: Buffer.from('hello') }); + const zCompressed = new Uint8Array([ 120, 187, 6, 44, 2, 21, 43, 207, 47, 202, 73, 1, 0, 6, 166, 2, 41 ]); assert.throws(function () { pako.inflate(zCompressed, { dictionary: 'world' }); }, /data error/); }); - it('trivial dictionary', function () { - var dict = 'abcdefghijklmnoprstuvwxyz'; + it('trivial dictionary', () => { + const dict = 'abcdefghijklmnoprstuvwxyz'; testInflate(samples, { dictionary: dict }, { dictionary: dict }); }); - it('spdy dictionary', function () { - var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); + it('spdy dictionary', () => { + const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); testInflate(samples, { dictionary: spdyDict }, { dictionary: spdyDict }); }); - it('should throw if directory is not supplied to raw inflate', function () { - var dict = 'abcdefghijklmnoprstuvwxyz'; + it('should throw if directory is not supplied to raw inflate', () => { + const dict = 'abcdefghijklmnoprstuvwxyz'; assert.throws(function () { testInflate(samples, { raw: true }, { raw: true, dictionary: dict }); }); }); - it('tests raw inflate with spdy dictionary', function () { - var spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); + it('tests raw inflate with spdy dictionary', () => { + const spdyDict = require('fs').readFileSync(require('path').join(__dirname, 'fixtures', 'spdy_dict.txt')); testInflate(samples, { raw: true, dictionary: spdyDict }, { raw: true, dictionary: spdyDict }); }); - it('tests dictionary as Uint8Array', function () { - var dict = new Uint8Array(100); - for (var i = 0; i < 100; i++) dict[i] = Math.random() * 256; + it('tests dictionary as Uint8Array', () => { + const dict = new Uint8Array(100); + for (let i = 0; i < 100; i++) dict[i] = Math.random() * 256; testInflate(samples, { dictionary: dict }, { dictionary: dict }); }); - it('tests dictionary as ArrayBuffer', function () { - var dict = new Uint8Array(100); - for (var i = 0; i < 100; i++) dict[i] = Math.random() * 256; + it('tests dictionary as ArrayBuffer', () => { + const dict = new Uint8Array(100); + for (let i = 0; i < 100; i++) dict[i] = Math.random() * 256; testInflate(samples, { dictionary: dict.buffer }, { dictionary: dict }); }); }); diff --git a/test/inflate_cover_ported.js b/test/inflate_cover_ported.js index ea6d7b8..ae82eee 100644 --- a/test/inflate_cover_ported.js +++ b/test/inflate_cover_ported.js @@ -2,15 +2,15 @@ 'use strict'; -var assert = require('assert'); +const assert = require('assert'); -var c = require('../lib/zlib/constants'); -var msg = require('../lib/zlib/messages'); -//var zlib_stream = require('../lib/zlib/zstream'); -var zlib_inflate = require('../lib/zlib/inflate'); -var inflate_table = require('../lib/zlib/inftrees'); +const c = require('../lib/zlib/constants'); +const msg = require('../lib/zlib/messages'); +//const zlib_stream = require('../lib/zlib/zstream'); +const zlib_inflate = require('../lib/zlib/inflate'); +const inflate_table = require('../lib/zlib/inftrees'); -var pako = require('../index'); +const pako = require('../index'); function h2b(hex) { @@ -21,7 +21,7 @@ function h2b(hex) { //step argument from original tests is missing because it have no effect //we have similar behavior in chunks.js tests function testInflate(hex, wbits, status) { - var inflator; + let inflator; try { inflator = new pako.Inflate({ windowBits: wbits }); } 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 - it('inflate bad parameters', function () { - var ret; + it('inflate bad parameters', () => { - ret = zlib_inflate.inflate(null, 0); + let ret = zlib_inflate.inflate(null, 0); assert(ret === c.Z_STREAM_ERROR); ret = zlib_inflate.inflateEnd(null); @@ -48,115 +47,115 @@ describe('Inflate states', function () { //ret = zlib_inflate.inflateCopy(null, null); //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); }); - it('bad gzip flags', function () { + it('bad gzip flags', () => { 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); }); - it('set window size from header', function () { + it('set window size from header', () => { 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); }); - it('check adler32', function () { + it('check adler32', () => { 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); }); - 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); }); - it('bad zlib header check', function () { + it('bad zlib header check', () => { 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); }); - it('compute adler32', function () { + it('compute adler32', () => { testInflate('78 9c 63 0', 15, c.Z_OK); }); }); -describe('Inflate cover', function () { - it('invalid stored block lengths', function () { +describe('Inflate cover', () => { + it('invalid stored block lengths', () => { testInflate('0 0 0 0 0', -15, c.Z_DATA_ERROR); }); - it('fixed', function () { + it('fixed', () => { testInflate('3 0', -15, c.Z_OK); }); - it('invalid block type', function () { + it('invalid block type', () => { testInflate('6', -15, c.Z_DATA_ERROR); }); - it('stored', function () { + it('stored', () => { 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); }); - it('invalid code lengths set', function () { + it('invalid code lengths set', () => { 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); }); - it('invalid bit length repeat', function () { + it('invalid bit length repeat', () => { 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); }); - 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); }); - 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); }); - it('invalid distance code', function () { + it('invalid distance code', () => { 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); }); - 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); }); - 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); }); - 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); }); - 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); }); - 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); }); - 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); }); - 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', -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); }); - it('window wrap', function () { + it('window wrap', () => { testInflate('63 18 5 40 c 0', -8, c.Z_OK); }); }); -describe('cover trees', function () { - it('inflate_table not enough errors', function () { - var ret, bits, next, table = [], lens = [], work = []; - var DISTS = 2; +describe('cover trees', () => { + it('inflate_table not enough errors', () => { + let ret, bits, next, table = [], lens = [], work = []; + const DISTS = 2; /* we need to call inflate_table() directly in order to manifest not- enough errors, since zlib insures that enough is always enough */ for (bits = 0; bits < 15; bits++) { @@ -174,37 +173,37 @@ describe('cover trees', function () { }); }); -describe('Inflate fast', function () { - it('fast length extra bits', function () { +describe('Inflate fast', () => { + 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' + ' 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' + ' 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); }); - 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); }); - it('very common case', function () { + it('very common case', () => { 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); }); - it('copy direct from output', function () { + it('copy direct from output', () => { testInflate('63 0 3 0 0 0 0 0', -8, c.Z_OK); }); }); -describe('Inflate support', function () { +describe('Inflate support', () => { // `inflatePrime` not implemented /*it('prime', function() { - var ret; - var strm = new zlib_stream(); + let ret; + const strm = new zlib_stream(); strm.avail_in = 0; strm.input = null; @@ -224,19 +223,19 @@ describe('Inflate support', function () { ret = zlib_inflate.inflateEnd(strm); assert(ret === c.Z_OK); });*/ - it('force window allocation', function () { + it('force window allocation', () => { testInflate('63 0', -15, c.Z_OK); }); - it('force window replacement', function () { + it('force window replacement', () => { 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); }); - it('use fixed blocks', function () { + it('use fixed blocks', () => { testInflate('3 0', -15, c.Z_OK); }); - it('bad window size', function () { + it('bad window size', () => { testInflate('', -15, c.Z_OK); }); }); diff --git a/test/misc.js b/test/misc.js index e6f5e17..e05536e 100644 --- a/test/misc.js +++ b/test/misc.js @@ -1,23 +1,23 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +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'); - var sample = new Uint8Array(fs.readFileSync(file)); - var deflated = pako.deflate(sample); + const file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt'); + const sample = new Uint8Array(fs.readFileSync(file)); + const deflated = pako.deflate(sample); - it('Deflate ArrayBuffer', function () { + it('Deflate ArrayBuffer', () => { assert.deepStrictEqual(deflated, pako.deflate(sample.buffer)); }); - it('Inflate ArrayBuffer', function () { + it('Inflate ArrayBuffer', () => { assert.deepStrictEqual(sample, pako.inflate(deflated.buffer)); }); }); diff --git a/test/strings.js b/test/strings.js index b68225f..9d9cf5c 100644 --- a/test/strings.js +++ b/test/strings.js @@ -1,12 +1,12 @@ 'use strict'; -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); -var pako = require('../index'); -var strings = require('../lib/utils/strings'); +const pako = require('../index'); +const strings = require('../lib/utils/strings'); // fromCharCode, but understands right > 0xffff values function fixedFromCharCode(code) { @@ -14,8 +14,8 @@ function fixedFromCharCode(code) { if (code > 0xffff) { code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10), - surrogate2 = 0xdc00 + (code & 0x3ff); + const surrogate1 = 0xd800 + (code >> 10); + const surrogate2 = 0xdc00 + (code & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } @@ -24,7 +24,7 @@ function fixedFromCharCode(code) { // Converts array of codes / chars / strings to utf16 string function a2utf16(arr) { - var result = ''; + let result = ''; arr.forEach(function (item) { if (typeof item === 'string') { result += item; return; } 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 - 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" - var utf8sample = new Uint8Array(Buffer.from(utf16sample)); + const utf8sample = new Uint8Array(Buffer.from(utf16sample)); - it('utf-8 border detect', function () { - var ub = strings.utf8border; + it('utf-8 border detect', () => { + const ub = strings.utf8border; assert.strictEqual(ub(utf8sample, 1), 1); assert.strictEqual(ub(utf8sample, 2), 2); assert.strictEqual(ub(utf8sample, 3), 3); @@ -70,36 +70,36 @@ describe('Encode/Decode', function () { assert.strictEqual(ub(utf8sample, 20), 20); }); - it('Encode string to utf8 buf', function () { + it('Encode string to utf8 buf', () => { assert.deepStrictEqual( strings.string2buf(utf16sample), utf8sample ); }); - it('Decode utf8 buf to string', function () { + it('Decode utf8 buf to string', () => { 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'); - var sampleString = fs.readFileSync(file, 'utf8'); - var sampleArray = new Uint8Array(fs.readFileSync(file)); + const file = path.join(__dirname, 'fixtures/samples/lorem_utf_100k.txt'); + const sampleString = fs.readFileSync(file, 'utf8'); + const sampleArray = new Uint8Array(fs.readFileSync(file)); - it('Deflate javascript string (utf16) on input', function () { + it('Deflate javascript string (utf16) on input', () => { assert.deepStrictEqual( pako.deflate(sampleString), pako.deflate(sampleArray) ); }); - it('Inflate with javascript string (utf16) output', function () { - var deflatedArray = pako.deflate(sampleArray); - var data = pako.inflate(deflatedArray, { to: 'string', chunkSize: 99 }); + it('Inflate with javascript string (utf16) output', () => { + const deflatedArray = pako.deflate(sampleArray); + const data = pako.inflate(deflatedArray, { to: 'string', chunkSize: 99 }); assert.strictEqual(typeof data, 'string'); assert.strictEqual(data, sampleString);