diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 375a6aa8a24eff..00000000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,23 +0,0 @@ - - -* **Version**: -* **Platform**: -* **Subsystem**: - - diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.md b/.github/ISSUE_TEMPLATE/1-bug-report.md index 69b9bf63250f7b..2a2e94d411fe2a 100644 --- a/.github/ISSUE_TEMPLATE/1-bug-report.md +++ b/.github/ISSUE_TEMPLATE/1-bug-report.md @@ -5,20 +5,47 @@ about: Create a report to help us improve --- * **Version**: * **Platform**: * **Subsystem**: - +### What steps will reproduce the bug? + + + +### How often does it reproduce? Is there a required condition? + +### What is the expected behavior? + + + +### What do you see instead? + + + +### Additional information + + diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 257e4abbc10aca..356a9f990e4290 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -3,14 +3,20 @@ name: CI on: [push, pull_request] jobs: - build-linux: + build-docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 + - name: Build + run: NODE=$(which node) make doc-only + - uses: actions/upload-artifact@v1 with: - node-version: 13.x + name: docs + path: out/doc + build-linux: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 - name: Environment Information run: npx envinfo - name: Build @@ -19,10 +25,6 @@ jobs: runs-on: windows-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 - with: - node-version: 13.x - name: Environment Information run: npx envinfo - name: Install deps @@ -33,10 +35,6 @@ jobs: runs-on: macos-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 - with: - node-version: 13.x - name: Environment Information run: npx envinfo - name: Build diff --git a/.gitignore b/.gitignore index db2597b042b84a..160b96f74a59ab 100644 --- a/.gitignore +++ b/.gitignore @@ -47,8 +47,8 @@ /config_fips.gypi # === Rules for MSVS artifacts === -/Debug -/Release +Debug/ +Release/ *.sln *.suo *.vcxproj* diff --git a/BUILDING.md b/BUILDING.md index 448b7711b4d4cc..4f24ebe06c0602 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -28,11 +28,12 @@ file a new issue. * [Running Coverage](#running-coverage) * [Building the documentation](#building-the-documentation) * [Building a debug build](#building-a-debug-build) + * [Troubleshooting Unix and macOS builds](#troubleshooting-unix-and-macos-builds) * [Windows](#windows) * [Prerequisites](#prerequisites) * [Option 1: Manual install](#option-1-manual-install) * [Option 2: Automated install with Boxstarter](#option-2-automated-install-with-boxstarter) - * [Building Node.js](#building-nodejs-1) + * [Building Node.js](#building-nodejs-2) * [Android/Android-based devices (e.g. Firefox OS)](#androidandroid-based-devices-eg-firefox-os) * [`Intl` (ECMA-402) support](#intl-ecma-402-support) * [Build with full ICU support (all locales supported by ICU)](#build-with-full-icu-support-all-locales-supported-by-icu) @@ -44,7 +45,7 @@ file a new issue. * [Building without Intl support](#building-without-intl-support) * [Unix/macOS](#unixmacos-2) * [Windows](#windows-3) - * [Use existing installed ICU (Unix/macOS only)](#use-existing-installed-icu-unixmacOS-only) + * [Use existing installed ICU (Unix/macOS only)](#use-existing-installed-icu-unixmacos-only) * [Build with a specific ICU](#build-with-a-specific-icu) * [Unix/macOS](#unixmacos-3) * [Windows](#windows-4) @@ -243,6 +244,7 @@ Installation via Linux package manager can be achieved with: * Fedora: `sudo dnf install python gcc-c++ make` * CentOS and RHEL: `sudo yum install python gcc-c++ make` * OpenSUSE: `sudo zypper install python gcc-c++ make` +* Arch Linux, Manjaro: `sudo pacman -S python gcc make` FreeBSD and OpenBSD users may also need to install `libexecinfo`. @@ -488,6 +490,17 @@ $ gdb /opt/node-debug/node core.node.8.1535359906 $ backtrace ``` +#### Troubleshooting Unix and macOS builds + +Stale builds can sometimes result in `file not found` errors while building. +This and some other problems can be resolved with `make distclean`. The +`distclean` recipe aggressively removes build artifacts. You will need to +build again (`make -j4`). Since all build artifacts have been removed, this +rebuild may take a lot more time than previous builds. Additionally, +`distclean` removes the file that stores the results of `./configure`. If you +ran `./configure` with non-default options (such as `--debug`), you will need +to run it again before invoking `make -j4`. + ### Windows #### Prerequisites diff --git a/CHANGELOG.md b/CHANGELOG.md index de6e21fed04a4b..4c48caa007f9f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,8 @@ release. -13.8.0
+13.9.0
+13.8.0
13.7.0
13.6.0
13.5.0
diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index a42c4c8b35f4fa..7e887d7543f50a 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -13,6 +13,7 @@ * [Waiting for Approvals](#waiting-for-approvals) * [Testing and CI](#testing-and-ci) * [Useful CI Jobs](#useful-ci-jobs) + * [Starting a CI Job](#starting-a-ci-job) * [Internal vs. Public API](#internal-vs-public-api) * [Breaking Changes](#breaking-changes) * [Breaking Changes and Deprecations](#breaking-changes-and-deprecations) @@ -191,12 +192,6 @@ everything else. Start a fresh CI if more than seven days have elapsed since the original failing CI as the compiled binaries for the Windows and ARM platforms are only kept for seven days. -Some of the CI Jobs may require `GIT_REMOTE_REF` which is the remote portion -of Git refspec. To specify the branch this way `refs/heads/BRANCH` is used -(i.e for `master` -> `refs/heads/master`). -For pull requests it will look like `refs/pull/PR_NUMBER/head` -(i.e. for PR#42 -> `refs/pull/42/head`). - #### Useful CI Jobs * [`node-test-pull-request`](https://ci.nodejs.org/job/node-test-pull-request/) @@ -216,12 +211,37 @@ that the tests are reliable. runs the standard V8 tests. Run it when updating V8 in Node.js or floating new patches on V8. -* [`node-test-commit-custom-suites`](https://ci.nodejs.org/job/node-test-commit-custom-suites/) +* [`node-test-commit-custom-suites-freestyle`](https://ci.nodejs.org/job/node-test-commit-custom-suites-freestyle/) enables customization of test suites and parameters. It can execute test suites not used in other CI test runs (such as tests in the `internet` or `pummel` directories). It can also make sure tests pass when provided with a flag not used in other CI test runs (such as `--worker`). +#### Starting a CI Job + +From the CI Job page, click "Build with Parameters" on the left side. + +You generally need to enter only one or both of the following options +in the form: + +* `GIT_REMOTE_REF`: Change to the remote portion of git refspec. +To specify the branch this way, `refs/heads/BRANCH` is used +(e.g. for `master` -> `refs/heads/master`). +For pull requests, it will look like `refs/pull/PR_NUMBER/head` +(e.g. for PR#42 -> `refs/pull/42/head`). +* `REBASE_ONTO`: Change that to `origin/master` so the pull request gets rebased +onto master. This can especially be important for pull requests that have been +open a while. + +Look at the list of jobs on the left hand side under "Build History" and copy +the link to the one you started (which will be the one on top, but click +through to make sure it says something like "Started 5 seconds ago" +(top right) and "Started by user ...". + +Copy/paste the URL for the job into a comment in the pull request. +[`node-test-pull-request`](https://ci.nodejs.org/job/node-test-pull-request/) +is an exception where the GitHub bot will automatically post for you. + ### Internal vs. Public API All functionality in the official Node.js documentation is part of the public diff --git a/README.md b/README.md index 6100568c1dce83..07d6ad4e7ed039 100644 --- a/README.md +++ b/README.md @@ -261,8 +261,6 @@ For information about the governance of the Node.js project, see **Ruben Bridgewater** <ruben@bridgewater.de> (he/him) * [bzoz](https://github.com/bzoz) - **Bartosz Sosnowski** <bartosz@janeasystems.com> -* [calvinmetcalf](https://github.com/calvinmetcalf) - -**Calvin Metcalf** <calvin.metcalf@gmail.com> * [cclauss](https://github.com/cclauss) - **Christian Clauss** <cclauss@me.com> (he/him) * [ChALkeR](https://github.com/ChALkeR) - @@ -353,7 +351,7 @@ For information about the governance of the Node.js project, see **Denys Otrishko** <shishugi@gmail.com> (he/him) * [maclover7](https://github.com/maclover7) - **Jon Moss** <me@jonathanmoss.me> (he/him) -* [mafintosh](https://github.com/mafintosh) +* [mafintosh](https://github.com/mafintosh) - **Mathias Buus** <mathiasbuus@gmail.com> (he/him) * [mcollina](https://github.com/mcollina) - **Matteo Collina** <matteo.collina@gmail.com> (he/him) @@ -375,8 +373,6 @@ For information about the governance of the Node.js project, see **Ali Ijaz Sheikh** <ofrobots@google.com> (he/him) * [oyyd](https://github.com/oyyd) - **Ouyang Yadong** <oyydoibh@gmail.com> (he/him) -* [princejwesley](https://github.com/princejwesley) - -**Prince John Wesley** <princejohnwesley@gmail.com> * [psmarshall](https://github.com/psmarshall) - **Peter Marshall** <petermarshall@chromium.org> (he/him) * [Qard](https://github.com/Qard) - @@ -385,6 +381,8 @@ For information about the governance of the Node.js project, see **Refael Ackermann (רפאל פלחי)** <refack@gmail.com> (he/him/הוא/אתה) * [richardlau](https://github.com/richardlau) - **Richard Lau** <riclau@uk.ibm.com> +* [ronag](https://github.com/ronag) - +**Robert Nagy** <ronagy@icloud.com> * [ronkorving](https://github.com/ronkorving) - **Ron Korving** <ron@ronkorving.nl> * [rubys](https://github.com/rubys) - @@ -392,7 +390,7 @@ For information about the governance of the Node.js project, see * [rvagg](https://github.com/rvagg) - **Rod Vagg** <rod@vagg.org> * [ryzokuken](https://github.com/ryzokuken) - -**Ujjwal Sharma** <usharma1998@gmail.com> (he/him) +**Ujjwal Sharma** <ryzokuken@disroot.org> (he/him) * [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** <saghul@gmail.com> * [sam-github](https://github.com/sam-github) - @@ -431,8 +429,6 @@ For information about the governance of the Node.js project, see **Rich Trott** <rtrott@gmail.com> (he/him) * [vdeturckheim](https://github.com/vdeturckheim) - **Vladimir de Turckheim** <vlad2t@hotmail.com> (he/him) -* [vkurchatkin](https://github.com/vkurchatkin) - -**Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com> * [watilde](https://github.com/watilde) - **Daijiro Wachi** <daijiro.wachi@gmail.com> (he/him) * [watson](https://github.com/watson) - @@ -456,12 +452,14 @@ For information about the governance of the Node.js project, see **Anna M. Kedzierska** <anna.m.kedzierska@gmail.com> * [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <brendan.ashworth@me.com> -* [estliberitas](https://github.com/estliberitas) - -**Alexander Makarenko** <estliberitas@gmail.com> +* [calvinmetcalf](https://github.com/calvinmetcalf) - +**Calvin Metcalf** <calvin.metcalf@gmail.com> * [chrisdickinson](https://github.com/chrisdickinson) - **Chris Dickinson** <christopher.s.dickinson@gmail.com> * [DavidCai1993](https://github.com/DavidCai1993) - **David Cai** <davidcai1993@yahoo.com> (he/him) +* [estliberitas](https://github.com/estliberitas) - +**Alexander Makarenko** <estliberitas@gmail.com> * [firedfox](https://github.com/firedfox) - **Daniel Wang** <wangyang0123@gmail.com> * [imran-iq](https://github.com/imran-iq) - @@ -504,6 +502,8 @@ For information about the governance of the Node.js project, see **Bert Belder** <bertbelder@gmail.com> * [pmq20](https://github.com/pmq20) - **Minqi Pan** <pmq2001@gmail.com> +* [princejwesley](https://github.com/princejwesley) - +**Prince John Wesley** <princejohnwesley@gmail.com> * [rlidwka](https://github.com/rlidwka) - **Alex Kocharin** <alex@kocharin.ru> * [rmg](https://github.com/rmg) - @@ -522,6 +522,8 @@ For information about the governance of the Node.js project, see **Thorsten Lorenz** <thlorenz@gmx.de> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> +* [vkurchatkin](https://github.com/vkurchatkin) - +**Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com> * [vsemozhetbyt](https://github.com/vsemozhetbyt) - **Vse Mozhet Byt** <vsemozhetbyt@gmail.com> (he/him) * [whitlockjc](https://github.com/whitlockjc) - diff --git a/benchmark/async_hooks/async-resource-vs-destroy.js b/benchmark/async_hooks/async-resource-vs-destroy.js new file mode 100644 index 00000000000000..4464dd5f93e7de --- /dev/null +++ b/benchmark/async_hooks/async-resource-vs-destroy.js @@ -0,0 +1,151 @@ +'use strict'; + +const { promisify } = require('util'); +const { readFile } = require('fs'); +const sleep = promisify(setTimeout); +const read = promisify(readFile); +const common = require('../common.js'); +const { + createHook, + executionAsyncResource, + executionAsyncId +} = require('async_hooks'); +const { createServer } = require('http'); + +// Configuration for the http server +// there is no need for parameters in this test +const connections = 500; +const path = '/'; + +const bench = common.createBenchmark(main, { + type: ['async-resource', 'destroy'], + asyncMethod: ['callbacks', 'async'], + n: [1e6] +}); + +function buildCurrentResource(getServe) { + const server = createServer(getServe(getCLS, setCLS)); + const hook = createHook({ init }); + const cls = Symbol('cls'); + hook.enable(); + + return { + server, + close + }; + + function getCLS() { + const resource = executionAsyncResource(); + if (resource === null || !resource[cls]) { + return null; + } + return resource[cls].state; + } + + function setCLS(state) { + const resource = executionAsyncResource(); + if (resource === null) { + return; + } + if (!resource[cls]) { + resource[cls] = { state }; + } else { + resource[cls].state = state; + } + } + + function init(asyncId, type, triggerAsyncId, resource) { + var cr = executionAsyncResource(); + if (cr !== null) { + resource[cls] = cr[cls]; + } + } + + function close() { + hook.disable(); + server.close(); + } +} + +function buildDestroy(getServe) { + const transactions = new Map(); + const server = createServer(getServe(getCLS, setCLS)); + const hook = createHook({ init, destroy }); + hook.enable(); + + return { + server, + close + }; + + function getCLS() { + const asyncId = executionAsyncId(); + return transactions.has(asyncId) ? transactions.get(asyncId) : null; + } + + function setCLS(value) { + const asyncId = executionAsyncId(); + transactions.set(asyncId, value); + } + + function init(asyncId, type, triggerAsyncId, resource) { + transactions.set(asyncId, getCLS()); + } + + function destroy(asyncId) { + transactions.delete(asyncId); + } + + function close() { + hook.disable(); + server.close(); + } +} + +function getServeAwait(getCLS, setCLS) { + return async function serve(req, res) { + setCLS(Math.random()); + await sleep(10); + await read(__filename); + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ cls: getCLS() })); + }; +} + +function getServeCallbacks(getCLS, setCLS) { + return function serve(req, res) { + setCLS(Math.random()); + setTimeout(() => { + readFile(__filename, () => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ cls: getCLS() })); + }); + }, 10); + }; +} + +const types = { + 'async-resource': buildCurrentResource, + 'destroy': buildDestroy +}; + +const asyncMethods = { + 'callbacks': getServeCallbacks, + 'async': getServeAwait +}; + +function main({ type, asyncMethod }) { + const { server, close } = types[type](asyncMethods[asyncMethod]); + + server + .listen(common.PORT) + .on('listening', () => { + + bench.http({ + path, + connections + }, () => { + close(); + }); + }); +} diff --git a/benchmark/buffers/buffer-concat-fill.js b/benchmark/buffers/buffer-concat-fill.js new file mode 100644 index 00000000000000..8fb389fe6c8639 --- /dev/null +++ b/benchmark/buffers/buffer-concat-fill.js @@ -0,0 +1,23 @@ +'use strict'; +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + extraSize: [1, 256, 4 * 256], + n: [8e5] +}); + +function main({ n, extraSize }) { + const pieces = 4; + const pieceSize = 256; + + const list = Array.from({ length: pieces }) + .fill(Buffer.allocUnsafe(pieceSize)); + + const totalLength = (pieces * pieceSize) + extraSize; + + bench.start(); + for (let i = 0; i < n; i++) { + Buffer.concat(list, totalLength); + } + bench.end(n); +} diff --git a/benchmark/buffers/buffer-from.js b/benchmark/buffers/buffer-from.js index 1df1b5b362fefa..d0f7d42f5e4369 100644 --- a/benchmark/buffers/buffer-from.js +++ b/benchmark/buffers/buffer-from.js @@ -12,37 +12,37 @@ const bench = common.createBenchmark(main, { 'string-utf8', 'string-base64', 'object', + 'uint8array', + 'uint16array', ], len: [100, 2048], n: [8e5] }); function main({ len, n, source }) { - const array = new Array(len).fill(42); - const arrayBuf = new ArrayBuffer(len); - const str = 'a'.repeat(len); - const buffer = Buffer.allocUnsafe(len); - const uint8array = new Uint8Array(len); - const obj = { length: null }; // Results in a new, empty Buffer - let i = 0; switch (source) { - case 'array': + case 'array': { + const array = new Array(len).fill(42); bench.start(); for (i = 0; i < n; i++) { Buffer.from(array); } bench.end(n); break; - case 'arraybuffer': + } + case 'arraybuffer': { + const arrayBuf = new ArrayBuffer(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(arrayBuf); } bench.end(n); break; - case 'arraybuffer-middle': + } + case 'arraybuffer-middle': { + const arrayBuf = new ArrayBuffer(len); const offset = ~~(len / 4); const length = ~~(len / 2); bench.start(); @@ -51,48 +51,70 @@ function main({ len, n, source }) { } bench.end(n); break; - case 'buffer': + } + case 'buffer': { + const buffer = Buffer.allocUnsafe(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(buffer); } bench.end(n); break; - case 'uint8array': + } + case 'uint8array': { + const uint8array = new Uint8Array(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(uint8array); } bench.end(n); break; - case 'string': + } + case 'uint16array': { + const uint16array = new Uint16Array(len); + bench.start(); + for (i = 0; i < n; i++) { + Buffer.from(uint16array); + } + bench.end(n); + break; + } + case 'string': { + const str = 'a'.repeat(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(str); } bench.end(n); break; - case 'string-utf8': + } + case 'string-utf8': { + const str = 'a'.repeat(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(str, 'utf8'); } bench.end(n); break; - case 'string-base64': + } + case 'string-base64': { + const str = 'a'.repeat(len); bench.start(); for (i = 0; i < n; i++) { Buffer.from(str, 'base64'); } bench.end(n); break; - case 'object': + } + case 'object': { + const obj = { length: null }; // Results in a new, empty Buffer bench.start(); for (i = 0; i < n; i++) { Buffer.from(obj); } bench.end(n); break; + } default: assert.fail('Should not get here'); } diff --git a/benchmark/common.js b/benchmark/common.js index 6a3be4fc376920..c5791c2bacfd5d 100644 --- a/benchmark/common.js +++ b/benchmark/common.js @@ -33,6 +33,7 @@ function Benchmark(fn, configs, options) { this._time = [0, 0]; // Used to make sure a benchmark only start a timer once this._started = false; + this._ended = false; // this._run will use fork() to create a new process for each configuration // combination. @@ -197,6 +198,9 @@ Benchmark.prototype.end = function(operations) { if (!this._started) { throw new Error('called end without start'); } + if (this._ended) { + throw new Error('called end multiple times'); + } if (typeof operations !== 'number') { throw new Error('called end() without specifying operation count'); } @@ -210,6 +214,7 @@ Benchmark.prototype.end = function(operations) { elapsed[1] = 1; } + this._ended = true; const time = elapsed[0] + elapsed[1] / 1e9; const rate = operations / time; this.report(rate, elapsed); diff --git a/benchmark/crypto/randomBytes.js b/benchmark/crypto/randomBytes.js new file mode 100644 index 00000000000000..50ad3f08387566 --- /dev/null +++ b/benchmark/crypto/randomBytes.js @@ -0,0 +1,16 @@ +'use strict'; + +const common = require('../common.js'); +const { randomBytes } = require('crypto'); + +const bench = common.createBenchmark(main, { + size: [64, 1024, 8192, 512 * 1024], + n: [1e3], +}); + +function main({ n, size }) { + bench.start(); + for (let i = 0; i < n; ++i) + randomBytes(size); + bench.end(n); +} diff --git a/benchmark/domain/domain-fn-args.js b/benchmark/domain/domain-fn-args.js index c889b35442d046..18906a9ce64099 100644 --- a/benchmark/domain/domain-fn-args.js +++ b/benchmark/domain/domain-fn-args.js @@ -15,7 +15,7 @@ function main({ n, args }) { bench.start(); bdomain.enter(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (myArguments.length >= 2) { const args = Array.prototype.slice.call(myArguments, 1); fn.apply(this, args); diff --git a/benchmark/es/defaultparams-bench.js b/benchmark/es/defaultparams-bench.js index c568c12ae03fda..ab9cc45749c996 100644 --- a/benchmark/es/defaultparams-bench.js +++ b/benchmark/es/defaultparams-bench.js @@ -22,14 +22,14 @@ function defaultParams(x = 1, y = 2) { function runOldStyleDefaults(n) { bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) oldStyleDefaults(); bench.end(n); } function runDefaultParams(n) { bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) defaultParams(); bench.end(n); } diff --git a/benchmark/es/destructuring-bench.js b/benchmark/es/destructuring-bench.js index 37f3fd9ad3d601..f1b484bd47e08f 100644 --- a/benchmark/es/destructuring-bench.js +++ b/benchmark/es/destructuring-bench.js @@ -9,9 +9,9 @@ const bench = common.createBenchmark(main, { }); function runSwapManual(n) { - var x, y, r; + let x, y, r; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { x = 1, y = 2; r = x; x = y; @@ -23,9 +23,9 @@ function runSwapManual(n) { } function runSwapDestructured(n) { - var x, y; + let x, y; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { x = 1, y = 2; [x, y] = [y, x]; assert.strictEqual(x, 2); diff --git a/benchmark/es/destructuring-object-bench.js b/benchmark/es/destructuring-object-bench.js index 0c5615fd1e667b..68dc17073badc2 100644 --- a/benchmark/es/destructuring-object-bench.js +++ b/benchmark/es/destructuring-object-bench.js @@ -8,10 +8,9 @@ const bench = common.createBenchmark(main, { }); function runNormal(n) { - var i = 0; const o = { x: 0, y: 1 }; bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { /* eslint-disable no-unused-vars */ const x = o.x; const y = o.y; @@ -22,10 +21,9 @@ function runNormal(n) { } function runDestructured(n) { - var i = 0; const o = { x: 0, y: 1 }; bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { /* eslint-disable no-unused-vars */ const { x, y, r = 2 } = o; /* eslint-enable no-unused-vars */ diff --git a/benchmark/es/foreach-bench.js b/benchmark/es/foreach-bench.js index f424ca7a2552b2..88bfed00fbc27c 100644 --- a/benchmark/es/foreach-bench.js +++ b/benchmark/es/foreach-bench.js @@ -10,8 +10,8 @@ const bench = common.createBenchmark(main, { function useFor(n, items, count) { bench.start(); - for (var i = 0; i < n; i++) { - for (var j = 0; j < count; j++) { + for (let i = 0; i < n; i++) { + for (let j = 0; j < count; j++) { // eslint-disable-next-line no-unused-vars const item = items[j]; } @@ -21,7 +21,7 @@ function useFor(n, items, count) { function useForOf(n, items) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { // eslint-disable-next-line no-unused-vars for (const item of items) {} } @@ -30,8 +30,8 @@ function useForOf(n, items) { function useForIn(n, items) { bench.start(); - for (var i = 0; i < n; i++) { - for (var j in items) { + for (let i = 0; i < n; i++) { + for (const j in items) { // eslint-disable-next-line no-unused-vars const item = items[j]; } @@ -41,7 +41,7 @@ function useForIn(n, items) { function useForEach(n, items) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { items.forEach((item) => {}); } bench.end(n); @@ -49,8 +49,8 @@ function useForEach(n, items) { function main({ n, count, method }) { const items = new Array(count); - var fn; - for (var i = 0; i < count; i++) + let fn; + for (let i = 0; i < count; i++) items[i] = i; switch (method) { diff --git a/benchmark/es/map-bench.js b/benchmark/es/map-bench.js index a2f9e2450a1f23..1b3ba4789db073 100644 --- a/benchmark/es/map-bench.js +++ b/benchmark/es/map-bench.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { function runObject(n) { const m = {}; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m[`i${i}`] = i; m[`s${i}`] = String(i); assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); @@ -27,7 +27,7 @@ function runObject(n) { function runNullProtoObject(n) { const m = Object.create(null); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m[`i${i}`] = i; m[`s${i}`] = String(i); assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); @@ -40,7 +40,7 @@ function runNullProtoObject(n) { function runNullProtoLiteralObject(n) { const m = { __proto__: null }; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m[`i${i}`] = i; m[`s${i}`] = String(i); assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); @@ -56,7 +56,7 @@ StorageObject.prototype = Object.create(null); function runStorageObject(n) { const m = new StorageObject(); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m[`i${i}`] = i; m[`s${i}`] = String(i); assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); @@ -79,7 +79,7 @@ function fakeMap() { function runFakeMap(n) { const m = fakeMap(); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m.set(`i${i}`, i); m.set(`s${i}`, String(i)); assert.strictEqual(String(m.get(`i${i}`)), m.get(`s${i}`)); @@ -92,7 +92,7 @@ function runFakeMap(n) { function runMap(n) { const m = new Map(); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { m.set(`i${i}`, i); m.set(`s${i}`, String(i)); assert.strictEqual(String(m.get(`i${i}`)), m.get(`s${i}`)); diff --git a/benchmark/es/restparams-bench.js b/benchmark/es/restparams-bench.js index d9b4878cb316a0..d568e28744541f 100644 --- a/benchmark/es/restparams-bench.js +++ b/benchmark/es/restparams-bench.js @@ -11,7 +11,7 @@ const bench = common.createBenchmark(main, { function copyArguments() { const len = arguments.length; const args = new Array(len); - for (var i = 0; i < len; i++) + for (let i = 0; i < len; i++) args[i] = arguments[i]; assert.strictEqual(args[0], 1); assert.strictEqual(args[1], 2); @@ -34,22 +34,22 @@ function useArguments() { } function runCopyArguments(n) { - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) copyArguments(1, 2, 'a', 'b'); } function runRestArguments(n) { - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) restArguments(1, 2, 'a', 'b'); } function runUseArguments(n) { - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) useArguments(1, 2, 'a', 'b'); } function main({ n, method }) { - var fn; + let fn; switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. diff --git a/benchmark/es/spread-assign.js b/benchmark/es/spread-assign.js index bbe07e02e15110..97a5c5458e396b 100644 --- a/benchmark/es/spread-assign.js +++ b/benchmark/es/spread-assign.js @@ -16,26 +16,25 @@ function main({ n, context, count, rest, method }) { src[`p${n}`] = n; let obj; // eslint-disable-line no-unused-vars - let i; switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case '_extend': bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) obj = util._extend({}, src); bench.end(n); break; case 'assign': bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) obj = Object.assign({}, src); bench.end(n); break; case 'spread': bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) obj = { ...src }; bench.end(n); break; diff --git a/benchmark/es/spread-bench.js b/benchmark/es/spread-bench.js index 97c7596b6b732b..fc56c9433f2add 100644 --- a/benchmark/es/spread-bench.js +++ b/benchmark/es/spread-bench.js @@ -25,10 +25,10 @@ function makeTest(count, rest) { function main({ n, context, count, rest, method }) { const ctx = context === 'context' ? {} : null; - var fn = makeTest(count, rest); + let fn = makeTest(count, rest); const args = new Array(count); - var i; - for (i = 0; i < count; i++) + + for (let i = 0; i < count; i++) args[i] = i; switch (method) { @@ -36,7 +36,7 @@ function main({ n, context, count, rest, method }) { // Empty string falls through to next line as default, mostly for tests. case 'apply': bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) fn.apply(ctx, args); bench.end(n); break; @@ -44,13 +44,13 @@ function main({ n, context, count, rest, method }) { if (ctx !== null) fn = fn.bind(ctx); bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) fn(...args); bench.end(n); break; case 'call-spread': bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) fn.call(ctx, ...args); bench.end(n); break; diff --git a/benchmark/events/ee-add-remove.js b/benchmark/events/ee-add-remove.js index 2d20736b057568..715eab29a59c4c 100644 --- a/benchmark/events/ee-add-remove.js +++ b/benchmark/events/ee-add-remove.js @@ -8,17 +8,16 @@ function main({ n }) { const ee = new events.EventEmitter(); const listeners = []; - var k; - for (k = 0; k < 10; k += 1) + for (let k = 0; k < 10; k += 1) listeners.push(() => {}); bench.start(); - for (var i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1'; - for (k = listeners.length; --k >= 0; /* empty */) { + for (let k = listeners.length; --k >= 0; /* empty */) { ee.on(dummy, listeners[k]); } - for (k = listeners.length; --k >= 0; /* empty */) { + for (let k = listeners.length; --k >= 0; /* empty */) { ee.removeListener(dummy, listeners[k]); } } diff --git a/benchmark/events/ee-emit.js b/benchmark/events/ee-emit.js index 8f1c2761ffd4ba..39bcbb937d6c56 100644 --- a/benchmark/events/ee-emit.js +++ b/benchmark/events/ee-emit.js @@ -11,35 +11,34 @@ const bench = common.createBenchmark(main, { function main({ n, argc, listeners }) { const ee = new EventEmitter(); - for (var k = 0; k < listeners; k += 1) + for (let k = 0; k < listeners; k += 1) ee.on('dummy', () => {}); - var i; switch (argc) { case 2: bench.start(); - for (i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { ee.emit('dummy', true, 5); } bench.end(n); break; case 4: bench.start(); - for (i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { ee.emit('dummy', true, 5, 10, false); } bench.end(n); break; case 10: bench.start(); - for (i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { ee.emit('dummy', true, 5, 10, false, 5, 'string', true, false, 11, 20); } bench.end(n); break; default: bench.start(); - for (i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { ee.emit('dummy'); } bench.end(n); diff --git a/benchmark/events/ee-listener-count-on-prototype.js b/benchmark/events/ee-listener-count-on-prototype.js index d48e96a46aafe2..04cadc8dcb64da 100644 --- a/benchmark/events/ee-listener-count-on-prototype.js +++ b/benchmark/events/ee-listener-count-on-prototype.js @@ -7,13 +7,13 @@ const bench = common.createBenchmark(main, { n: [5e7] }); function main({ n }) { const ee = new EventEmitter(); - for (var k = 0; k < 5; k += 1) { + for (let k = 0; k < 5; k += 1) { ee.on('dummy0', () => {}); ee.on('dummy1', () => {}); } bench.start(); - for (var i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1'; ee.listenerCount(dummy); } diff --git a/benchmark/events/ee-listeners-many.js b/benchmark/events/ee-listeners-many.js index 7f9099c41790ea..bd3f3538d63c92 100644 --- a/benchmark/events/ee-listeners-many.js +++ b/benchmark/events/ee-listeners-many.js @@ -8,13 +8,13 @@ function main({ n }) { const ee = new EventEmitter(); ee.setMaxListeners(101); - for (var k = 0; k < 50; k += 1) { + for (let k = 0; k < 50; k += 1) { ee.on('dummy0', () => {}); ee.on('dummy1', () => {}); } bench.start(); - for (var i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1'; ee.listeners(dummy); } diff --git a/benchmark/events/ee-listeners.js b/benchmark/events/ee-listeners.js index 74b88b043401b5..867393efffcb04 100644 --- a/benchmark/events/ee-listeners.js +++ b/benchmark/events/ee-listeners.js @@ -7,13 +7,13 @@ const bench = common.createBenchmark(main, { n: [5e6] }); function main({ n }) { const ee = new EventEmitter(); - for (var k = 0; k < 5; k += 1) { + for (let k = 0; k < 5; k += 1) { ee.on('dummy0', () => {}); ee.on('dummy1', () => {}); } bench.start(); - for (var i = 0; i < n; i += 1) { + for (let i = 0; i < n; i += 1) { const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1'; ee.listeners(dummy); } diff --git a/benchmark/fixtures/simple-http-server.js b/benchmark/fixtures/simple-http-server.js index 2b4f1ea956d7cc..fb5b0d87c16e0d 100644 --- a/benchmark/fixtures/simple-http-server.js +++ b/benchmark/fixtures/simple-http-server.js @@ -31,14 +31,14 @@ module.exports = http.createServer((req, res) => { // URL format: /////chunkedEnc const params = req.url.split('/'); const command = params[1]; - var body = ''; + let body = ''; const arg = params[2]; const n_chunks = parseInt(params[3], 10); const resHow = params.length >= 5 ? params[4] : 'normal'; const chunkedEnc = params.length >= 6 && params[5] === '0' ? false : true; - var status = 200; + let status = 200; - var n, i; + let n, i; if (command === 'bytes') { n = ~~arg; if (n <= 0) diff --git a/benchmark/fs/bench-readdirSync.js b/benchmark/fs/bench-readdirSync.js index 5d0e97399a33ff..c0144d3460f8ff 100644 --- a/benchmark/fs/bench-readdirSync.js +++ b/benchmark/fs/bench-readdirSync.js @@ -15,7 +15,7 @@ function main({ n, dir, withFileTypes }) { withFileTypes = withFileTypes === 'true'; const fullPath = path.resolve(__dirname, '../../', dir); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fs.readdirSync(fullPath, { withFileTypes }); } bench.end(n); diff --git a/benchmark/fs/bench-realpathSync.js b/benchmark/fs/bench-realpathSync.js index 7a01bd18cb72bf..d0dbd7f891f126 100644 --- a/benchmark/fs/bench-realpathSync.js +++ b/benchmark/fs/bench-realpathSync.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { function main({ n, pathType }) { const path = pathType === 'relative' ? relative_path : resolved_path; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fs.realpathSync(path); } bench.end(n); diff --git a/benchmark/fs/bench-stat.js b/benchmark/fs/bench-stat.js index 0b2e1972e2cb80..e1f51c762c8e5f 100644 --- a/benchmark/fs/bench-stat.js +++ b/benchmark/fs/bench-stat.js @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, { function main({ n, statType }) { - var arg; + let arg; if (statType === 'fstat') arg = fs.openSync(__filename, 'r'); else diff --git a/benchmark/fs/bench-statSync.js b/benchmark/fs/bench-statSync.js index bd8754a6c3d0e3..0c9366a402cb71 100644 --- a/benchmark/fs/bench-statSync.js +++ b/benchmark/fs/bench-statSync.js @@ -16,7 +16,7 @@ function main({ n, statSyncType }) { const fn = fs[statSyncType]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fn(arg); } bench.end(n); diff --git a/benchmark/fs/read-stream-throughput.js b/benchmark/fs/read-stream-throughput.js index 4c8de582418960..34c25760ea9c38 100644 --- a/benchmark/fs/read-stream-throughput.js +++ b/benchmark/fs/read-stream-throughput.js @@ -52,7 +52,7 @@ function runTest() { bench.start(); }); - var bytes = 0; + let bytes = 0; rs.on('data', (chunk) => { bytes += chunk.length; }); @@ -68,7 +68,7 @@ function makeFile() { const buf = Buffer.allocUnsafe(filesize / 1024); if (encoding === 'utf8') { // ü - for (var i = 0; i < buf.length; i++) { + for (let i = 0; i < buf.length; i++) { buf[i] = i % 2 === 0 ? 0xC3 : 0xBC; } } else if (encoding === 'ascii') { @@ -78,7 +78,7 @@ function makeFile() { } try { fs.unlinkSync(filename); } catch {} - var w = 1024; + let w = 1024; const ws = fs.createWriteStream(filename); ws.on('close', runTest); ws.on('drain', write); diff --git a/benchmark/fs/readFileSync.js b/benchmark/fs/readFileSync.js index c28adeb229b358..47d210b7aa0463 100644 --- a/benchmark/fs/readFileSync.js +++ b/benchmark/fs/readFileSync.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) fs.readFileSync(__filename); bench.end(n); } diff --git a/benchmark/fs/readfile-partitioned.js b/benchmark/fs/readfile-partitioned.js index 90af3754ce3de2..51700cfd649dfd 100644 --- a/benchmark/fs/readfile-partitioned.js +++ b/benchmark/fs/readfile-partitioned.js @@ -22,25 +22,24 @@ const bench = common.createBenchmark(main, { concurrent: [1, 10] }); -function main(conf) { - const len = +conf.len; +function main({ len, dur, concurrent }) { try { fs.unlinkSync(filename); } catch {} - var data = Buffer.alloc(len, 'x'); + let data = Buffer.alloc(len, 'x'); fs.writeFileSync(filename, data); data = null; const zipData = Buffer.alloc(1024, 'a'); - var reads = 0; - var zips = 0; - var benchEnded = false; + let reads = 0; + let zips = 0; + let benchEnded = false; bench.start(); setTimeout(() => { const totalOps = reads + zips; benchEnded = true; bench.end(totalOps); try { fs.unlinkSync(filename); } catch {} - }, +conf.dur * 1000); + }, dur * 1000); function read() { fs.readFile(filename, afterRead); @@ -78,8 +77,7 @@ function main(conf) { } // Start reads - var cur = +conf.concurrent; - while (cur--) read(); + while (concurrent-- > 0) read(); // Start a competing zip zip(); diff --git a/benchmark/fs/readfile.js b/benchmark/fs/readfile.js index 7460c8e233e59f..361ffbff597d6e 100644 --- a/benchmark/fs/readfile.js +++ b/benchmark/fs/readfile.js @@ -21,12 +21,12 @@ const bench = common.createBenchmark(main, { function main({ len, dur, concurrent }) { try { fs.unlinkSync(filename); } catch {} - var data = Buffer.alloc(len, 'x'); + let data = Buffer.alloc(len, 'x'); fs.writeFileSync(filename, data); data = null; - var reads = 0; - var benchEnded = false; + let reads = 0; + let benchEnded = false; bench.start(); setTimeout(() => { benchEnded = true; diff --git a/benchmark/fs/write-stream-throughput.js b/benchmark/fs/write-stream-throughput.js index 44de0900d8ed15..44a3bb23b041d1 100644 --- a/benchmark/fs/write-stream-throughput.js +++ b/benchmark/fs/write-stream-throughput.js @@ -17,9 +17,9 @@ const bench = common.createBenchmark(main, { }); function main({ dur, encodingType, size }) { - var encoding; + let encoding; - var chunk; + let chunk; switch (encodingType) { case 'buf': chunk = Buffer.alloc(size, 'b'); @@ -38,8 +38,8 @@ function main({ dur, encodingType, size }) { try { fs.unlinkSync(filename); } catch {} - var started = false; - var ended = false; + let started = false; + let ended = false; const f = fs.createWriteStream(filename); f.on('drain', write); diff --git a/benchmark/http/_chunky_http_client.js b/benchmark/http/_chunky_http_client.js index 1bf7fa284a835b..1ab95a2b9706c1 100644 --- a/benchmark/http/_chunky_http_client.js +++ b/benchmark/http/_chunky_http_client.js @@ -12,7 +12,7 @@ const bench = common.createBenchmark(main, { function main({ len, n }) { - var todo = []; + let todo = []; const headers = []; // Chose 7 because 9 showed "Connection error" / "Connection closed" // An odd number could result in a better length dispersion. @@ -48,19 +48,19 @@ function main({ len, n }) { } const min = 10; - var size = 0; + let size = 0; const mod = 317; const mult = 17; const add = 11; - var count = 0; + let count = 0; const PIPE = process.env.PIPE_NAME; const socket = net.connect(PIPE, () => { bench.start(); WriteHTTPHeaders(socket, 1, len); socket.setEncoding('utf8'); socket.on('data', (d) => { - var did = false; - var pattern = 'HTTP/1.1 200 OK\r\n'; + let did = false; + let pattern = 'HTTP/1.1 200 OK\r\n'; if ((d.length === pattern.length && d === pattern) || (d.length > pattern.length && d.slice(0, pattern.length) === pattern)) { diff --git a/benchmark/http/client-request-body.js b/benchmark/http/client-request-body.js index b5ac2828c6ff1f..6e2323b3f07e8a 100644 --- a/benchmark/http/client-request-body.js +++ b/benchmark/http/client-request-body.js @@ -12,8 +12,8 @@ const bench = common.createBenchmark(main, { }); function main({ dur, len, type, method }) { - var encoding; - var chunk; + let encoding; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -27,7 +27,7 @@ function main({ dur, len, type, method }) { break; } - var nreqs = 0; + let nreqs = 0; const options = { headers: { 'Connection': 'keep-alive', 'Transfer-Encoding': 'chunked' }, agent: new http.Agent({ maxSockets: 1 }), diff --git a/benchmark/http/cluster.js b/benchmark/http/cluster.js index c2d6d8e1a70c90..3bcd061a0894c5 100644 --- a/benchmark/http/cluster.js +++ b/benchmark/http/cluster.js @@ -18,7 +18,7 @@ if (cluster.isMaster) { function main({ type, len, c }) { process.env.PORT = PORT; - var workers = 0; + let workers = 0; const w1 = cluster.fork(); const w2 = cluster.fork(); diff --git a/benchmark/http/end-vs-write-end.js b/benchmark/http/end-vs-write-end.js index b4ca560b9a897c..38e9b89a97a6b4 100644 --- a/benchmark/http/end-vs-write-end.js +++ b/benchmark/http/end-vs-write-end.js @@ -19,7 +19,7 @@ const bench = common.createBenchmark(main, { function main({ len, type, method, c }) { const http = require('http'); - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); diff --git a/benchmark/http/set_header.js b/benchmark/http/set_header.js index 470d4b008187bc..f2236696f1c7df 100644 --- a/benchmark/http/set_header.js +++ b/benchmark/http/set_header.js @@ -16,10 +16,7 @@ const bench = common.createBenchmark(main, { n: [1e6], }); -function main(conf) { - const n = +conf.n; - const value = conf.value; - +function main({ n, value }) { const og = new OutgoingMessage(); bench.start(); diff --git a/benchmark/http2/headers.js b/benchmark/http2/headers.js index f18a73b95e2421..56799da1987e53 100644 --- a/benchmark/http2/headers.js +++ b/benchmark/http2/headers.js @@ -24,7 +24,7 @@ function main({ n, nheaders }) { 'user-agent': 'SuperBenchmarker 3000' }; - for (var i = 0; i < nheaders; i++) { + for (let i = 0; i < nheaders; i++) { headersObject[`foo${i}`] = `some header value ${i}`; } diff --git a/benchmark/misc/arguments.js b/benchmark/misc/arguments.js index 5b0cb0e2ca1488..8fefe617a51d56 100644 --- a/benchmark/misc/arguments.js +++ b/benchmark/misc/arguments.js @@ -32,7 +32,7 @@ function usingPredefined() { } function main({ n, method, args }) { - var fn; + let fn; switch (method) { // '' is a default case for tests case '': @@ -53,7 +53,7 @@ function main({ n, method, args }) { } bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) fn('part 1', 'part', 2, 'part 3', 'part', 4); bench.end(n); } diff --git a/benchmark/misc/freelist.js b/benchmark/misc/freelist.js index e6868fae1ce8c5..d03c3674fdbfac 100644 --- a/benchmark/misc/freelist.js +++ b/benchmark/misc/freelist.js @@ -14,7 +14,7 @@ function main({ n }) { FreeList = FreeList.FreeList; const poolSize = 1000; const list = new FreeList('test', poolSize, Object); - var j; + let j; const used = []; // First, alloc `poolSize` items @@ -24,7 +24,7 @@ function main({ n }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { // Return all the items to the pool for (j = 0; j < poolSize; j++) { list.free(used[j]); diff --git a/benchmark/misc/getstringwidth.js b/benchmark/misc/getstringwidth.js index 97532bf2a7b50f..c10f7af8483cf9 100644 --- a/benchmark/misc/getstringwidth.js +++ b/benchmark/misc/getstringwidth.js @@ -12,7 +12,7 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { // Default value for testing purposes. type = type || 'ascii'; - const { getStringWidth } = require('internal/readline/utils'); + const { getStringWidth } = require('internal/util/inspect'); const str = ({ ascii: 'foobar'.repeat(100), diff --git a/benchmark/misc/object-property-bench.js b/benchmark/misc/object-property-bench.js index fae11119b6fe23..0a4d004999ed23 100644 --- a/benchmark/misc/object-property-bench.js +++ b/benchmark/misc/object-property-bench.js @@ -11,9 +11,9 @@ const bench = common.createBenchmark(main, { function runProperty(n) { const object = {}; - var i = 0; + bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { object.p1 = 21; object.p2 = 21; object.p1 += object.p2; @@ -23,9 +23,9 @@ function runProperty(n) { function runString(n) { const object = {}; - var i = 0; + bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { object['p1'] = 21; object['p2'] = 21; object['p1'] += object['p2']; @@ -37,9 +37,9 @@ function runVariable(n) { const object = {}; const var1 = 'p1'; const var2 = 'p2'; - var i = 0; + bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { object[var1] = 21; object[var2] = 21; object[var1] += object[var2]; @@ -51,9 +51,9 @@ function runSymbol(n) { const object = {}; const symbol1 = Symbol('p1'); const symbol2 = Symbol('p2'); - var i = 0; + bench.start(); - for (; i < n; i++) { + for (let i = 0; i < n; i++) { object[symbol1] = 21; object[symbol2] = 21; object[symbol1] += object[symbol2]; diff --git a/benchmark/misc/punycode.js b/benchmark/misc/punycode.js index 18023419709ee5..5f85df758ef7e3 100644 --- a/benchmark/misc/punycode.js +++ b/benchmark/misc/punycode.js @@ -45,18 +45,17 @@ function usingICU(val) { } function runPunycode(n, val) { - var i = 0; - for (; i < n; i++) + for (let i = 0; i < n; i++) usingPunycode(val); bench.start(); - for (i = 0; i < n; i++) + for (let i = 0; i < n; i++) usingPunycode(val); bench.end(n); } function runICU(n, val) { bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) usingICU(val); bench.end(n); } diff --git a/benchmark/misc/trace.js b/benchmark/misc/trace.js index d76f53cf04e82d..bdbf547007e72e 100644 --- a/benchmark/misc/trace.js +++ b/benchmark/misc/trace.js @@ -15,7 +15,7 @@ const { function doTrace(n, trace) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { trace(kBeforeEvent, 'foo', 'test', 0, 'test'); } bench.end(n); @@ -23,7 +23,7 @@ function doTrace(n, trace) { function doIsTraceCategoryEnabled(n, isTraceCategoryEnabled) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { isTraceCategoryEnabled('foo'); isTraceCategoryEnabled('bar'); } diff --git a/benchmark/misc/util-extend-vs-object-assign.js b/benchmark/misc/util-extend-vs-object-assign.js index 3880711b660fe1..b3d95f0e2d97a4 100644 --- a/benchmark/misc/util-extend-vs-object-assign.js +++ b/benchmark/misc/util-extend-vs-object-assign.js @@ -22,13 +22,13 @@ function main({ n, type }) { // Force-optimize the method to test so that the benchmark doesn't // get disrupted by the optimizer kicking in halfway through. - for (var i = 0; i < type.length * 10; i += 1) + for (let i = 0; i < type.length * 10; i += 1) fn({}, process.env); const obj = new Proxy({}, { set: function(a, b, c) { return true; } }); bench.start(); - for (var j = 0; j < n; j += 1) + for (let j = 0; j < n; j += 1) fn(obj, process.env); bench.end(n); } diff --git a/benchmark/module/module-loader-deep.js b/benchmark/module/module-loader-deep.js index f686b8df47dfba..5b4f4b907a7ce6 100644 --- a/benchmark/module/module-loader-deep.js +++ b/benchmark/module/module-loader-deep.js @@ -19,7 +19,7 @@ function main({ ext, cache, files }) { `${benchmarkDirectory}/a.js`, 'module.exports = {};' ); - for (var i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { fs.mkdirSync(`${benchmarkDirectory}/${i}`); fs.writeFileSync( `${benchmarkDirectory}/${i}/package.json`, @@ -37,14 +37,13 @@ function main({ ext, cache, files }) { } function measureDir(cache, files) { - var i; if (cache) { - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}/${i}`); } } bench.start(); - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}/${i}`); } bench.end(files); diff --git a/benchmark/module/module-loader.js b/benchmark/module/module-loader.js index 3b8e9be2d60636..f31ac8722cb208 100644 --- a/benchmark/module/module-loader.js +++ b/benchmark/module/module-loader.js @@ -21,7 +21,7 @@ const bench = common.createBenchmark(main, { function main({ n, name, cache, files, dir }) { tmpdir.refresh(); fs.mkdirSync(benchmarkDirectory); - for (var i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { fs.mkdirSync(`${benchmarkDirectory}${i}`); fs.writeFileSync( `${benchmarkDirectory}${i}/package.json`, @@ -42,15 +42,14 @@ function main({ n, name, cache, files, dir }) { } function measureDir(n, cache, files, name) { - var i; if (cache) { - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}${i}${name}`); } } bench.start(); - for (i = 0; i <= files; i++) { - for (var j = 0; j < n; j++) + for (let i = 0; i <= files; i++) { + for (let j = 0; j < n; j++) require(`${benchmarkDirectory}${i}${name}`); // Pretend mixed input (otherwise the results are less representative due to // highly specialized code). diff --git a/benchmark/napi/function_args/index.js b/benchmark/napi/function_args/index.js index 8f13454944772e..8ce9fa9d528f5c 100644 --- a/benchmark/napi/function_args/index.js +++ b/benchmark/napi/function_args/index.js @@ -89,7 +89,7 @@ function main({ n, engine, type }) { const args = generateArgs(type); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fn.apply(null, args); } bench.end(n); diff --git a/benchmark/napi/function_call/index.js b/benchmark/napi/function_call/index.js index 3eebf9c05acdb1..1e1d159c8ad83a 100644 --- a/benchmark/napi/function_call/index.js +++ b/benchmark/napi/function_call/index.js @@ -29,7 +29,7 @@ try { } const napi = napi_binding.hello; -var c = 0; +let c = 0; function js() { return c++; } @@ -44,7 +44,7 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const fn = type === 'cxx' ? cxx : type === 'napi' ? napi : js; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fn(); } bench.end(n); diff --git a/benchmark/net/net-c2s-cork.js b/benchmark/net/net-c2s-cork.js index 12d15fe0795e57..1493cae68d0069 100644 --- a/benchmark/net/net-c2s-cork.js +++ b/benchmark/net/net-c2s-cork.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 4b64cbeca18124..cacd6815630b2e 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index 06426129f7f271..d86ff73041d845 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index d8c26db9bdb035..789eadf0a18dba 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -12,10 +12,10 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var chunk; -var encoding; -var recvbuf; -var received = 0; +let chunk; +let encoding; +let recvbuf; +let received = 0; function main({ dur, sendchunklen, type, recvbuflen, recvbufgenfn }) { if (isFinite(recvbuflen) && recvbuflen > 0) @@ -38,8 +38,8 @@ function main({ dur, sendchunklen, type, recvbuflen, recvbufgenfn }) { } const reader = new Reader(); - var writer; - var socketOpts; + let writer; + let socketOpts; if (recvbuf === undefined) { writer = new Writer(); socketOpts = { port: PORT }; diff --git a/benchmark/net/net-wrap-js-stream-passthrough.js b/benchmark/net/net-wrap-js-stream-passthrough.js index 1e8a1ee1c5a092..0d7be36c6aa545 100644 --- a/benchmark/net/net-wrap-js-stream-passthrough.js +++ b/benchmark/net/net-wrap-js-stream-passthrough.js @@ -12,8 +12,8 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { // Can only require internals inside main(). diff --git a/benchmark/net/tcp-raw-c2s.js b/benchmark/net/tcp-raw-c2s.js index fe320ddaa2716b..b8af124a7f40fc 100644 --- a/benchmark/net/tcp-raw-c2s.js +++ b/benchmark/net/tcp-raw-c2s.js @@ -24,7 +24,7 @@ function main({ dur, len, type }) { const PORT = common.PORT; const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -38,7 +38,7 @@ function main({ dur, len, type }) { // The meat of the benchmark is right here: bench.start(); - var bytes = 0; + let bytes = 0; setTimeout(() => { // report in Gb/sec @@ -67,7 +67,7 @@ function main({ dur, len, type }) { } function client(type, len) { - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -102,7 +102,7 @@ function main({ dur, len, type }) { function write() { const writeReq = new WriteWrap(); writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); diff --git a/benchmark/net/tcp-raw-pipe.js b/benchmark/net/tcp-raw-pipe.js index 4420cc2e6dcc17..249b61046a84cf 100644 --- a/benchmark/net/tcp-raw-pipe.js +++ b/benchmark/net/tcp-raw-pipe.js @@ -31,7 +31,7 @@ function main({ dur, len, type }) { // Server const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -66,7 +66,7 @@ function main({ dur, len, type }) { }; // Client - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -83,7 +83,7 @@ function main({ dur, len, type }) { const clientHandle = new TCP(TCPConstants.SOCKET); const connectReq = new TCPConnectWrap(); - var bytes = 0; + let bytes = 0; err = clientHandle.connect(connectReq, '127.0.0.1', PORT); if (err) @@ -118,7 +118,7 @@ function main({ dur, len, type }) { function write() { const writeReq = new WriteWrap(); writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); diff --git a/benchmark/net/tcp-raw-s2c.js b/benchmark/net/tcp-raw-s2c.js index cc2f69019fff61..393cf060489cb8 100644 --- a/benchmark/net/tcp-raw-s2c.js +++ b/benchmark/net/tcp-raw-s2c.js @@ -26,7 +26,7 @@ function main({ dur, len, type }) { const PORT = common.PORT; const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -38,7 +38,7 @@ function main({ dur, len, type }) { if (err) fail(err, 'connect'); - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -62,7 +62,7 @@ function main({ dur, len, type }) { const writeReq = new WriteWrap(); writeReq.async = false; writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); @@ -108,7 +108,7 @@ function main({ dur, len, type }) { fail(err, 'connect'); connectReq.oncomplete = function() { - var bytes = 0; + let bytes = 0; clientHandle.onread = function(buffer) { // We're not expecting to ever get an EOF from the client. // Just lots of data forever. diff --git a/benchmark/os/cpus.js b/benchmark/os/cpus.js index da158a1b061c7f..a8aa3ab6cbf46f 100644 --- a/benchmark/os/cpus.js +++ b/benchmark/os/cpus.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) cpus(); bench.end(n); } diff --git a/benchmark/os/loadavg.js b/benchmark/os/loadavg.js index 2cd38316b24bdd..802e3c99ec0a59 100644 --- a/benchmark/os/loadavg.js +++ b/benchmark/os/loadavg.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) loadavg(); bench.end(n); } diff --git a/benchmark/os/networkInterfaces.js b/benchmark/os/networkInterfaces.js index 3fa6073ae5c69e..12e956b7f05ddc 100644 --- a/benchmark/os/networkInterfaces.js +++ b/benchmark/os/networkInterfaces.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) networkInterfaces(); bench.end(n); } diff --git a/benchmark/path/basename-posix.js b/benchmark/path/basename-posix.js index 45cad1e25660dc..6600068d4c53f6 100644 --- a/benchmark/path/basename-posix.js +++ b/benchmark/path/basename-posix.js @@ -19,7 +19,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, pathext }) { - var ext; + let ext; const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { ext = pathext.slice(extIdx + 1); @@ -27,7 +27,7 @@ function main({ n, pathext }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.basename(i % 3 === 0 ? `${pathext}${i}` : pathext, ext); } bench.end(n); diff --git a/benchmark/path/basename-win32.js b/benchmark/path/basename-win32.js index 30d65f3ac6a4c9..dc26a134e29252 100644 --- a/benchmark/path/basename-win32.js +++ b/benchmark/path/basename-win32.js @@ -19,7 +19,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, pathext }) { - var ext; + let ext; const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { ext = pathext.slice(extIdx + 1); @@ -27,7 +27,7 @@ function main({ n, pathext }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.basename(i % 3 === 0 ? `${pathext}${i}` : pathext, ext); } bench.end(n); diff --git a/benchmark/path/dirname-posix.js b/benchmark/path/dirname-posix.js index 93f2f32c012695..c98753562fbc93 100644 --- a/benchmark/path/dirname-posix.js +++ b/benchmark/path/dirname-posix.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.dirname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/dirname-win32.js b/benchmark/path/dirname-win32.js index 510595d721ace1..9eb5478b3b4d3b 100644 --- a/benchmark/path/dirname-win32.js +++ b/benchmark/path/dirname-win32.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.dirname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/extname-posix.js b/benchmark/path/extname-posix.js index ee1ea07eebc010..0e01d59a745883 100644 --- a/benchmark/path/extname-posix.js +++ b/benchmark/path/extname-posix.js @@ -20,7 +20,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.extname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/extname-win32.js b/benchmark/path/extname-win32.js index 1de4bca28a2988..6d8437e5c5d819 100644 --- a/benchmark/path/extname-win32.js +++ b/benchmark/path/extname-win32.js @@ -20,7 +20,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.extname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/format-posix.js b/benchmark/path/format-posix.js index 9c555f232c0099..7720bbc3b705ed 100644 --- a/benchmark/path/format-posix.js +++ b/benchmark/path/format-posix.js @@ -20,7 +20,7 @@ function main({ n, props }) { }; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { obj.base = `a${i}${props[2] || ''}`; obj.name = `a${i}${props[4] || ''}`; posix.format(obj); diff --git a/benchmark/path/format-win32.js b/benchmark/path/format-win32.js index 65315c4dd638f1..fab7599ab58386 100644 --- a/benchmark/path/format-win32.js +++ b/benchmark/path/format-win32.js @@ -20,7 +20,7 @@ function main({ n, props }) { }; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { obj.base = `a${i}${props[2] || ''}`; obj.name = `a${i}${props[4] || ''}`; win32.format(obj); diff --git a/benchmark/path/isAbsolute-posix.js b/benchmark/path/isAbsolute-posix.js index dd0dfd1964e0fb..90d06502d1fb02 100644 --- a/benchmark/path/isAbsolute-posix.js +++ b/benchmark/path/isAbsolute-posix.js @@ -15,7 +15,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.isAbsolute(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/isAbsolute-win32.js b/benchmark/path/isAbsolute-win32.js index ff03f2628a328c..15da64f5e973a3 100644 --- a/benchmark/path/isAbsolute-win32.js +++ b/benchmark/path/isAbsolute-win32.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.isAbsolute(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/join-posix.js b/benchmark/path/join-posix.js index e573166d7ae078..6619e4dea852db 100644 --- a/benchmark/path/join-posix.js +++ b/benchmark/path/join-posix.js @@ -15,7 +15,7 @@ function main({ n, paths }) { const orig = copy[1]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[1] = `${orig}${i}`; posix.join(...copy); diff --git a/benchmark/path/join-win32.js b/benchmark/path/join-win32.js index cd69836c006e23..958dee706d499a 100644 --- a/benchmark/path/join-win32.js +++ b/benchmark/path/join-win32.js @@ -15,7 +15,7 @@ function main({ n, paths }) { const orig = copy[1]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[1] = `${orig}${i}`; win32.join(...copy); diff --git a/benchmark/path/makeLong-win32.js b/benchmark/path/makeLong-win32.js index 45d0d8de60d7e0..864a9cfffe63b9 100644 --- a/benchmark/path/makeLong-win32.js +++ b/benchmark/path/makeLong-win32.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32._makeLong(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/normalize-posix.js b/benchmark/path/normalize-posix.js index 4383cff4a588f7..e0722097025020 100644 --- a/benchmark/path/normalize-posix.js +++ b/benchmark/path/normalize-posix.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.normalize(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/normalize-win32.js b/benchmark/path/normalize-win32.js index 319c391d17a712..84e16ca3c2d0e9 100644 --- a/benchmark/path/normalize-win32.js +++ b/benchmark/path/normalize-win32.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.normalize(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/relative-posix.js b/benchmark/path/relative-posix.js index 2c4dd31d2778c7..0285c2c968dcb2 100644 --- a/benchmark/path/relative-posix.js +++ b/benchmark/path/relative-posix.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, paths }) { - var to = ''; + let to = ''; const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { to = paths.slice(delimIdx + 1); diff --git a/benchmark/path/relative-win32.js b/benchmark/path/relative-win32.js index 5f34fdf8fd5842..401919aa20d802 100644 --- a/benchmark/path/relative-win32.js +++ b/benchmark/path/relative-win32.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, paths }) { - var to = ''; + let to = ''; const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { to = paths.slice(delimIdx + 1); diff --git a/benchmark/path/resolve-posix.js b/benchmark/path/resolve-posix.js index 3cdf1cd49a0754..dbae350c62a35f 100644 --- a/benchmark/path/resolve-posix.js +++ b/benchmark/path/resolve-posix.js @@ -18,7 +18,7 @@ function main({ n, paths }) { const orig = copy[0]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[0] = `${orig}${i}`; posix.resolve(...copy); diff --git a/benchmark/path/resolve-win32.js b/benchmark/path/resolve-win32.js index cf8144ef2c57cd..7def7aa1025d50 100644 --- a/benchmark/path/resolve-win32.js +++ b/benchmark/path/resolve-win32.js @@ -18,7 +18,7 @@ function main({ n, paths }) { const orig = copy[0]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[0] = `${orig}${i}`; win32.resolve(...copy); diff --git a/benchmark/process/bench-hrtime.js b/benchmark/process/bench-hrtime.js index d73ed7aae4336e..2da9035f806cf9 100644 --- a/benchmark/process/bench-hrtime.js +++ b/benchmark/process/bench-hrtime.js @@ -10,27 +10,26 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const hrtime = process.hrtime; - var noDead = type === 'bigint' ? hrtime.bigint() : hrtime(); - var i; + let noDead = type === 'bigint' ? hrtime.bigint() : hrtime(); switch (type) { case 'raw': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime(); } bench.end(n); break; case 'diff': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime(noDead); } bench.end(n); break; case 'bigint': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime.bigint(); } bench.end(n); diff --git a/benchmark/process/memoryUsage.js b/benchmark/process/memoryUsage.js index f9b969ab885d8b..1c743d81f1f465 100644 --- a/benchmark/process/memoryUsage.js +++ b/benchmark/process/memoryUsage.js @@ -7,7 +7,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.memoryUsage(); } bench.end(n); diff --git a/benchmark/process/next-tick-breadth-args.js b/benchmark/process/next-tick-breadth-args.js index 03651dbdbb4eea..bd3b24ddc29fc5 100644 --- a/benchmark/process/next-tick-breadth-args.js +++ b/benchmark/process/next-tick-breadth-args.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb1(arg1) { j++; @@ -33,7 +33,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); else if (i % 3 === 0) diff --git a/benchmark/process/next-tick-breadth.js b/benchmark/process/next-tick-breadth.js index 297bf43495d2e6..eb34ea830acfe7 100644 --- a/benchmark/process/next-tick-breadth.js +++ b/benchmark/process/next-tick-breadth.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb() { j++; @@ -15,7 +15,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.nextTick(cb); } } diff --git a/benchmark/process/next-tick-exec-args.js b/benchmark/process/next-tick-exec-args.js index ec172ea8931e3f..7893e2c70903e5 100644 --- a/benchmark/process/next-tick-exec-args.js +++ b/benchmark/process/next-tick-exec-args.js @@ -10,7 +10,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) process.nextTick(onNextTick, i, true, 10, 'test'); else if (i % 3 === 0) diff --git a/benchmark/process/next-tick-exec.js b/benchmark/process/next-tick-exec.js index 14fce9cccf8d6a..eefe2b7ceb765f 100644 --- a/benchmark/process/next-tick-exec.js +++ b/benchmark/process/next-tick-exec.js @@ -10,7 +10,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.nextTick(onNextTick, i); } diff --git a/benchmark/process/queue-microtask-breadth.js b/benchmark/process/queue-microtask-breadth.js index 8bb33f6fdee6cc..610dfc584ef738 100644 --- a/benchmark/process/queue-microtask-breadth.js +++ b/benchmark/process/queue-microtask-breadth.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb() { j++; @@ -15,7 +15,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { queueMicrotask(cb); } } diff --git a/benchmark/querystring/querystring-parse.js b/benchmark/querystring/querystring-parse.js index ca4dca13bc14eb..2a5f3048de46b9 100644 --- a/benchmark/querystring/querystring-parse.js +++ b/benchmark/querystring/querystring-parse.js @@ -10,23 +10,23 @@ const bench = common.createBenchmark(main, { function main({ type, n }) { const input = inputs[type]; - var i; + // Execute the function a "sufficient" number of times before the timed // loop to ensure the function is optimized just once. if (type === 'multicharsep') { - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input, '&&&&&&&&&&'); bench.start(); - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input, '&&&&&&&&&&'); bench.end(n); } else { - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input); bench.start(); - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input); bench.end(n); } diff --git a/benchmark/querystring/querystring-stringify.js b/benchmark/querystring/querystring-stringify.js index 6c5da0f464034f..be81f67fa826d7 100644 --- a/benchmark/querystring/querystring-stringify.js +++ b/benchmark/querystring/querystring-stringify.js @@ -38,7 +38,7 @@ function main({ type, n }) { querystring.stringify(inputs[name]); bench.start(); - for (var i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.stringify(input); bench.end(n); } diff --git a/benchmark/querystring/querystring-unescapebuffer.js b/benchmark/querystring/querystring-unescapebuffer.js index 39dd085eda938c..e6b842b3f94127 100644 --- a/benchmark/querystring/querystring-unescapebuffer.js +++ b/benchmark/querystring/querystring-unescapebuffer.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { function main({ input, n }) { bench.start(); - for (var i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.unescapeBuffer(input); bench.end(n); } diff --git a/benchmark/streams/creation.js b/benchmark/streams/creation.js index 46a0a547907c45..760ab5c89dca96 100644 --- a/benchmark/streams/creation.js +++ b/benchmark/streams/creation.js @@ -13,14 +13,13 @@ const bench = common.createBenchmark(main, { }); function main({ n, kind }) { - var i = 0; switch (kind) { case 'duplex': new Duplex({}); new Duplex(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Duplex(); bench.end(n); break; @@ -29,7 +28,7 @@ function main({ n, kind }) { new Readable(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Readable(); bench.end(n); break; @@ -38,7 +37,7 @@ function main({ n, kind }) { new Writable(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Writable(); bench.end(n); break; @@ -47,7 +46,7 @@ function main({ n, kind }) { new Transform(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Transform(); bench.end(n); break; diff --git a/benchmark/streams/pipe-object-mode.js b/benchmark/streams/pipe-object-mode.js index d52b2238780ccb..33588819f00a6c 100644 --- a/benchmark/streams/pipe-object-mode.js +++ b/benchmark/streams/pipe-object-mode.js @@ -12,7 +12,7 @@ function main({ n }) { const r = new Readable({ objectMode: true }); const w = new Writable({ objectMode: true }); - var i = 0; + let i = 0; r._read = () => r.push(i++ === n ? null : b); w._write = (data, enc, cb) => cb(); diff --git a/benchmark/streams/pipe.js b/benchmark/streams/pipe.js index 4baeeb2d2e7706..0df1afdbe10134 100644 --- a/benchmark/streams/pipe.js +++ b/benchmark/streams/pipe.js @@ -12,7 +12,7 @@ function main({ n }) { const r = new Readable(); const w = new Writable(); - var i = 0; + let i = 0; r._read = () => r.push(i++ === n ? null : b); w._write = (data, enc, cb) => cb(); diff --git a/benchmark/streams/readable-bigread.js b/benchmark/streams/readable-bigread.js index c3cff3d933d915..1bd1dab4edb07f 100644 --- a/benchmark/streams/readable-bigread.js +++ b/benchmark/streams/readable-bigread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(128)); } diff --git a/benchmark/streams/readable-bigunevenread.js b/benchmark/streams/readable-bigunevenread.js index 95a4139c069e87..684986a778aba2 100644 --- a/benchmark/streams/readable-bigunevenread.js +++ b/benchmark/streams/readable-bigunevenread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(106)); } diff --git a/benchmark/streams/readable-boundaryread.js b/benchmark/streams/readable-boundaryread.js index 835c7d18b51285..edc90d04de161d 100644 --- a/benchmark/streams/readable-boundaryread.js +++ b/benchmark/streams/readable-boundaryread.js @@ -10,14 +10,14 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const s = new Readable(); - var data = 'a'.repeat(32); + let data = 'a'.repeat(32); if (type === 'buffer') data = Buffer.from(data); s._read = function() {}; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(data); while (s.read(32)); } diff --git a/benchmark/streams/readable-readall.js b/benchmark/streams/readable-readall.js index 3c177ec4c39988..d14fd7756586e9 100644 --- a/benchmark/streams/readable-readall.js +++ b/benchmark/streams/readable-readall.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read()); } diff --git a/benchmark/streams/readable-unevenread.js b/benchmark/streams/readable-unevenread.js index 690f1f420838c6..9da8410131bfff 100644 --- a/benchmark/streams/readable-unevenread.js +++ b/benchmark/streams/readable-unevenread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(12)); } diff --git a/benchmark/streams/writable-manywrites.js b/benchmark/streams/writable-manywrites.js index 049bf8eb281db2..e4ae9ab91e5f4a 100644 --- a/benchmark/streams/writable-manywrites.js +++ b/benchmark/streams/writable-manywrites.js @@ -35,8 +35,10 @@ function main({ n, sync, writev, callback }) { let k = 0; function run() { while (k++ < n && s.write(b, cb)); - if (k >= n) + if (k >= n) { bench.end(n); + s.removeListener('drain', run); + } } s.on('drain', run); run(); diff --git a/benchmark/string_decoder/string-decoder-create.js b/benchmark/string_decoder/string-decoder-create.js index fad727222e1870..f7fa5e0246b860 100644 --- a/benchmark/string_decoder/string-decoder-create.js +++ b/benchmark/string_decoder/string-decoder-create.js @@ -11,7 +11,7 @@ const bench = common.createBenchmark(main, { function main({ encoding, n }) { bench.start(); - for (var i = 0; i < n; ++i) { + for (let i = 0; i < n; ++i) { const sd = new StringDecoder(encoding); !!sd.encoding; } diff --git a/benchmark/string_decoder/string-decoder.js b/benchmark/string_decoder/string-decoder.js index 0e34effbc7d964..afc0dde62e7937 100644 --- a/benchmark/string_decoder/string-decoder.js +++ b/benchmark/string_decoder/string-decoder.js @@ -14,12 +14,11 @@ const ASC_ALPHA = 'Blueberry jam'; const UTF16_BUF = Buffer.from('Blåbærsyltetøy', 'utf16le'); function main({ encoding, inLen, chunkLen, n }) { - var alpha; - var buf; + let alpha; + let buf; const chunks = []; - var str = ''; + let str = ''; const isBase64 = (encoding === 'base64-ascii' || encoding === 'base64-utf8'); - var i; if (encoding === 'ascii' || encoding === 'base64-ascii') alpha = ASC_ALPHA; @@ -33,7 +32,7 @@ function main({ encoding, inLen, chunkLen, n }) { const sd = new StringDecoder(isBase64 ? 'base64' : encoding); - for (i = 0; i < inLen; ++i) { + for (let i = 0; i < inLen; ++i) { if (i > 0 && (i % chunkLen) === 0 && !isBase64) { if (alpha) { chunks.push(Buffer.from(str, encoding)); @@ -46,8 +45,8 @@ function main({ encoding, inLen, chunkLen, n }) { if (alpha) str += alpha[i % alpha.length]; else { - var start = i; - var end = i + 2; + let start = i; + let end = i + 2; if (i % 2 !== 0) { ++start; ++end; @@ -77,8 +76,8 @@ function main({ encoding, inLen, chunkLen, n }) { const nChunks = chunks.length; bench.start(); - for (i = 0; i < n; ++i) { - for (var j = 0; j < nChunks; ++j) + for (let i = 0; i < n; ++i) { + for (let j = 0; j < nChunks; ++j) sd.write(chunks[j]); } bench.end(n); diff --git a/benchmark/timers/immediate.js b/benchmark/timers/immediate.js index ba50f961daa6aa..d12106a0e030fc 100644 --- a/benchmark/timers/immediate.js +++ b/benchmark/timers/immediate.js @@ -66,7 +66,7 @@ function breadth(N) { if (n === N) bench.end(N); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb); } } @@ -80,7 +80,7 @@ function breadth1(N) { if (n === N) bench.end(n); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb, 1); } } @@ -95,7 +95,7 @@ function breadth4(N) { if (n === N) bench.end(n); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb, 1, 2, 3, 4); } } @@ -107,7 +107,7 @@ function clear(N) { if (a1 === 2) bench.end(N); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { clearImmediate(setImmediate(cb, 1)); } setImmediate(cb, 2); diff --git a/benchmark/timers/timers-breadth-args.js b/benchmark/timers/timers-breadth-args.js index bdb3adbbec6b7a..63a301dc9bc7dc 100644 --- a/benchmark/timers/timers-breadth-args.js +++ b/benchmark/timers/timers-breadth-args.js @@ -32,7 +32,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) setTimeout(cb4, 1, 3.14, 1024, true, false); else if (i % 3 === 0) diff --git a/benchmark/timers/timers-breadth.js b/benchmark/timers/timers-breadth.js index 8cd77f4fab2852..78bd5a97ae84b8 100644 --- a/benchmark/timers/timers-breadth.js +++ b/benchmark/timers/timers-breadth.js @@ -13,7 +13,7 @@ function main({ n }) { if (j === n) bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(cb, 1); } } diff --git a/benchmark/timers/timers-cancel-pooled.js b/benchmark/timers/timers-cancel-pooled.js index 6f16f3c91da8a8..5045983210263e 100644 --- a/benchmark/timers/timers-cancel-pooled.js +++ b/benchmark/timers/timers-cancel-pooled.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { var timer = setTimeout(() => {}, 1); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(cb, 1); } var next = timer._idlePrev; @@ -17,7 +17,7 @@ function main({ n }) { bench.start(); - for (var j = 0; j < n; j++) { + for (let j = 0; j < n; j++) { timer = next; next = timer._idlePrev; clearTimeout(timer); diff --git a/benchmark/timers/timers-cancel-unpooled.js b/benchmark/timers/timers-cancel-unpooled.js index 1daf68bde0ed51..df203ee4810b1d 100644 --- a/benchmark/timers/timers-cancel-unpooled.js +++ b/benchmark/timers/timers-cancel-unpooled.js @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, { function main({ n, direction }) { const timersList = []; - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { timersList.push(setTimeout(cb, i + 1)); } diff --git a/benchmark/timers/timers-insert-pooled.js b/benchmark/timers/timers-insert-pooled.js index a7441a9eaf76f6..91b69d34514a86 100644 --- a/benchmark/timers/timers-insert-pooled.js +++ b/benchmark/timers/timers-insert-pooled.js @@ -9,7 +9,7 @@ function main({ n }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(() => {}, 1); } diff --git a/benchmark/timers/timers-insert-unpooled.js b/benchmark/timers/timers-insert-unpooled.js index 232cc7c31aff16..11d25d5fe79670 100644 --- a/benchmark/timers/timers-insert-unpooled.js +++ b/benchmark/timers/timers-insert-unpooled.js @@ -23,7 +23,7 @@ function main({ direction, n }) { } bench.end(n); - for (var j = 0; j < n; j++) { + for (let j = 0; j < n; j++) { clearTimeout(timersList[j]); } } diff --git a/benchmark/timers/timers-timeout-nexttick.js b/benchmark/timers/timers-timeout-nexttick.js index 638d8aec149cd5..784c8e0168dd28 100644 --- a/benchmark/timers/timers-timeout-nexttick.js +++ b/benchmark/timers/timers-timeout-nexttick.js @@ -30,7 +30,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(i % 2 ? cb : cb2, 1); } diff --git a/benchmark/timers/timers-timeout-pooled.js b/benchmark/timers/timers-timeout-pooled.js index 1cdae07dc98bdc..eb54d3c7a0082a 100644 --- a/benchmark/timers/timers-timeout-pooled.js +++ b/benchmark/timers/timers-timeout-pooled.js @@ -27,7 +27,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(i % 2 ? cb : cb2, 1); } diff --git a/benchmark/timers/timers-timeout-unpooled.js b/benchmark/timers/timers-timeout-unpooled.js index fecb73a36013b0..a7820805082047 100644 --- a/benchmark/timers/timers-timeout-unpooled.js +++ b/benchmark/timers/timers-timeout-unpooled.js @@ -27,7 +27,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { // unref().ref() will cause each of these timers to // allocate their own handle setTimeout(i % 2 ? cb : cb2, 1).unref().ref(); diff --git a/benchmark/tls/convertprotocols.js b/benchmark/tls/convertprotocols.js index 0ba6c6dd0873b5..74bb942bfcec4f 100644 --- a/benchmark/tls/convertprotocols.js +++ b/benchmark/tls/convertprotocols.js @@ -16,7 +16,7 @@ function main({ n }) { m = {}; } bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) tls.convertALPNProtocols(input, m); bench.end(n); } diff --git a/benchmark/tls/tls-connect.js b/benchmark/tls/tls-connect.js index 4300f6841f0cd6..1cb04d98a52721 100644 --- a/benchmark/tls/tls-connect.js +++ b/benchmark/tls/tls-connect.js @@ -31,7 +31,7 @@ function main(conf) { function onListening() { setTimeout(done, dur * 1000); bench.start(); - for (var i = 0; i < concurrency; i++) + for (let i = 0; i < concurrency; i++) makeConnection(); } diff --git a/benchmark/url/legacy-vs-whatwg-url-get-prop.js b/benchmark/url/legacy-vs-whatwg-url-get-prop.js index 16bcd226324ef8..fe0c464f52b3c9 100644 --- a/benchmark/url/legacy-vs-whatwg-url-get-prop.js +++ b/benchmark/url/legacy-vs-whatwg-url-get-prop.js @@ -71,9 +71,8 @@ function useWHATWG(data) { } function main({ type, method, e }) { - e = +e; - var data; - var noDead; // Avoid dead code elimination. + let data; + let noDead; // Avoid dead code elimination. switch (method) { case 'legacy': data = common.bakeUrlData(type, e, false, false); diff --git a/benchmark/url/legacy-vs-whatwg-url-parse.js b/benchmark/url/legacy-vs-whatwg-url-parse.js index 7c49654b47d8e2..6e5e25d231242f 100644 --- a/benchmark/url/legacy-vs-whatwg-url-parse.js +++ b/benchmark/url/legacy-vs-whatwg-url-parse.js @@ -46,7 +46,6 @@ function useWHATWGWithoutBase(data) { } function main({ e, method, type, withBase }) { - e = +e; withBase = withBase === 'true'; var noDead; // Avoid dead code elimination. var data; diff --git a/benchmark/url/legacy-vs-whatwg-url-serialize.js b/benchmark/url/legacy-vs-whatwg-url-serialize.js index d6d8c8a4e71152..5523e549ceb233 100644 --- a/benchmark/url/legacy-vs-whatwg-url-serialize.js +++ b/benchmark/url/legacy-vs-whatwg-url-serialize.js @@ -35,7 +35,6 @@ function useWHATWG(data) { } function main({ type, e, method }) { - e = +e; const data = common.bakeUrlData(type, e, false, false); var noDead; // Avoid dead code elimination. diff --git a/benchmark/url/whatwg-url-properties.js b/benchmark/url/whatwg-url-properties.js index 60f573e27a8fe2..ac71ff4f636d66 100644 --- a/benchmark/url/whatwg-url-properties.js +++ b/benchmark/url/whatwg-url-properties.js @@ -34,7 +34,6 @@ function get(data, prop) { } function main({ e, type, prop, withBase }) { - e = +e; withBase = withBase === 'true'; const data = common.bakeUrlData(type, e, withBase, true); switch (prop) { diff --git a/benchmark/v8/get-stats.js b/benchmark/v8/get-stats.js index aa1f0516811983..d5ce102774df6e 100644 --- a/benchmark/v8/get-stats.js +++ b/benchmark/v8/get-stats.js @@ -13,7 +13,7 @@ const bench = common.createBenchmark(main, { function main({ method, n }) { bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) v8[method](); bench.end(n); } diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js index 9b57067a19c9ac..980a08e7e56e8c 100644 --- a/benchmark/vm/run-in-context.js +++ b/benchmark/vm/run-in-context.js @@ -20,7 +20,7 @@ function main({ n, breakOnSigint, withSigintListener }) { const contextifiedSandbox = vm.createContext(); bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) vm.runInContext('0', contextifiedSandbox, options); bench.end(n); } diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js index 0754287376d58c..c612c1ea49ecf6 100644 --- a/benchmark/vm/run-in-this-context.js +++ b/benchmark/vm/run-in-this-context.js @@ -18,7 +18,7 @@ function main({ n, breakOnSigint, withSigintListener }) { process.on('SIGINT', () => {}); bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) vm.runInThisContext('0', options); bench.end(n); } diff --git a/benchmark/worker/echo.js b/benchmark/worker/echo.js index 3e729d0e26fa04..8d45a1f76b5eac 100644 --- a/benchmark/worker/echo.js +++ b/benchmark/worker/echo.js @@ -1,6 +1,7 @@ 'use strict'; const common = require('../common.js'); +const { Worker } = require('worker_threads'); const path = require('path'); const bench = common.createBenchmark(main, { workers: [1], @@ -11,19 +12,14 @@ const bench = common.createBenchmark(main, { const workerPath = path.resolve(__dirname, '..', 'fixtures', 'echo.worker.js'); -function main(conf) { - const { Worker } = require('worker_threads'); - - const n = +conf.n; - const workers = +conf.workers; - const sends = +conf.sendsPerBroadcast; +function main({ n, workers, sendsPerBroadcast: sends, payload: payloadType }) { const expectedPerBroadcast = sends * workers; - var payload; - var readies = 0; - var broadcasts = 0; - var msgCount = 0; + let payload; + let readies = 0; + let broadcasts = 0; + let msgCount = 0; - switch (conf.payload) { + switch (payloadType) { case 'string': payload = 'hello world!'; break; @@ -36,7 +32,7 @@ function main(conf) { const workerObjs = []; - for (var i = 0; i < workers; ++i) { + for (let i = 0; i < workers; ++i) { const worker = new Worker(workerPath); workerObjs.push(worker); worker.on('online', onOnline); diff --git a/benchmark/worker/messageport.js b/benchmark/worker/messageport.js new file mode 100644 index 00000000000000..8e2ddae73ff3ab --- /dev/null +++ b/benchmark/worker/messageport.js @@ -0,0 +1,42 @@ +'use strict'; + +const common = require('../common.js'); +const { MessageChannel } = require('worker_threads'); +const bench = common.createBenchmark(main, { + payload: ['string', 'object'], + n: [1e6] +}); + +function main(conf) { + const n = conf.n; + let payload; + + switch (conf.payload) { + case 'string': + payload = 'hello world!'; + break; + case 'object': + payload = { action: 'pewpewpew', powerLevel: 9001 }; + break; + default: + throw new Error('Unsupported payload type'); + } + + const { port1, port2 } = new MessageChannel(); + + let messages = 0; + port2.onmessage = () => { + if (messages++ === n) { + bench.end(n); + port1.close(); + } else { + write(); + } + }; + bench.start(); + write(); + + function write() { + port1.postMessage(payload); + } +} diff --git a/benchmark/zlib/createInflate.js b/benchmark/zlib/createInflate.js new file mode 100644 index 00000000000000..30ccaef7a14fb2 --- /dev/null +++ b/benchmark/zlib/createInflate.js @@ -0,0 +1,32 @@ +'use strict'; +const common = require('../common.js'); +const zlib = require('zlib'); + +const bench = common.createBenchmark(main, { + inputLen: [16 * 1024 * 1024], + chunkLen: [1024], + n: [1e2] +}); + +function main({ n, inputLen, chunkLen }) { + const input = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); + + let i = 0; + bench.start(); + (function next() { + let p = 0; + const inflater = zlib.createInflate(); + inflater.resume(); + inflater.on('finish', () => { + if (i++ === n) + return bench.end(n); + next(); + }); + + (function nextChunk() { + if (p >= input.length) + return inflater.end(); + inflater.write(input.slice(p, p += chunkLen), nextChunk); + })(); + })(); +} diff --git a/benchmark/zlib/deflate.js b/benchmark/zlib/deflate.js index 5e86d659803747..6d3bda90c6fdfa 100644 --- a/benchmark/zlib/deflate.js +++ b/benchmark/zlib/deflate.js @@ -9,6 +9,8 @@ const bench = common.createBenchmark(main, { }); function main({ n, method, inputLen }) { + // Default method value for testing. + method = method || 'deflate'; const chunk = Buffer.alloc(inputLen, 'a'); var i = 0; diff --git a/benchmark/zlib/inflate.js b/benchmark/zlib/inflate.js new file mode 100644 index 00000000000000..09379c00c1250b --- /dev/null +++ b/benchmark/zlib/inflate.js @@ -0,0 +1,39 @@ +'use strict'; +const common = require('../common.js'); +const zlib = require('zlib'); + +const bench = common.createBenchmark(main, { + method: ['inflate', 'inflateSync'], + inputLen: [1024], + n: [4e5] +}); + +function main({ n, method, inputLen }) { + // Default method value for tests. + method = method || 'inflate'; + const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); + + let i = 0; + switch (method) { + // Performs `n` single inflate operations + case 'inflate': + const inflate = zlib.inflate; + bench.start(); + (function next(err, result) { + if (i++ === n) + return bench.end(n); + inflate(chunk, next); + })(); + break; + // Performs `n` single inflateSync operations + case 'inflateSync': + const inflateSync = zlib.inflateSync; + bench.start(); + for (; i < n; ++i) + inflateSync(chunk); + bench.end(n); + break; + default: + throw new Error('Unsupported inflate method'); + } +} diff --git a/common.gypi b/common.gypi index ab28ca65e7676d..b8a37491893c91 100644 --- a/common.gypi +++ b/common.gypi @@ -202,7 +202,10 @@ 'RuntimeLibrary': '<(MSVC_runtimeType)', 'RuntimeTypeInfo': 'false', } - } + }, + 'xcode_settings': { + 'GCC_OPTIMIZATION_LEVEL': '3', # stop gyp from defaulting to -Os + }, } }, diff --git a/configure.py b/configure.py index 682feb44e459a3..beb08df0884f76 100755 --- a/configure.py +++ b/configure.py @@ -89,6 +89,11 @@ dest='debug', help='also build debug build') +parser.add_option('--debug-node', + action='store_true', + dest='debug_node', + help='build the Node.js part of the binary with debugging symbols') + parser.add_option('--dest-cpu', action='store', dest='dest_cpu', @@ -609,6 +614,12 @@ default=False, help='compile V8 with minimal optimizations and with runtime checks') +parser.add_option('--node-builtin-modules-path', + action='store', + dest='node_builtin_modules_path', + default=False, + help='node will load builtin modules from disk instead of from binary') + # Create compile_commands.json in out/Debug and out/Release. parser.add_option('-C', action='store_true', @@ -969,6 +980,7 @@ def configure_node(o): o['variables']['node_prefix'] = options.prefix o['variables']['node_install_npm'] = b(not options.without_npm) o['variables']['node_report'] = b(not options.without_report) + o['variables']['debug_node'] = b(options.debug_node) o['default_configuration'] = 'Debug' if options.debug else 'Release' host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc() @@ -992,18 +1004,18 @@ def configure_node(o): o['variables']['want_separate_host_toolset'] = int(cross_compiling) - if not options.without_node_snapshot: + if options.without_node_snapshot or options.node_builtin_modules_path: + o['variables']['node_use_node_snapshot'] = 'false' + else: o['variables']['node_use_node_snapshot'] = b( not cross_compiling and not options.shared) - else: - o['variables']['node_use_node_snapshot'] = 'false' - if not options.without_node_code_cache: + if options.without_node_code_cache or options.node_builtin_modules_path: + o['variables']['node_use_node_code_cache'] = 'false' + else: # TODO(refack): fix this when implementing embedded code-cache when cross-compiling. o['variables']['node_use_node_code_cache'] = b( not cross_compiling and not options.shared) - else: - o['variables']['node_use_node_code_cache'] = 'false' if target_arch == 'arm': configure_arm(o) @@ -1145,6 +1157,10 @@ def configure_node(o): else: o['variables']['node_target_type'] = 'executable' + if options.node_builtin_modules_path: + print('Warning! Loading builtin modules from disk is for development') + o['variables']['node_builtin_modules_path'] = options.node_builtin_modules_path + def configure_napi(output): version = getnapibuildversion.get_napi_version() output['variables']['napi_build_version'] = version diff --git a/test/fixtures/bluebird/node_modules/bluebird/js/release/bluebird.js b/deps/npm/.npmrc similarity index 100% rename from test/fixtures/bluebird/node_modules/bluebird/js/release/bluebird.js rename to deps/npm/.npmrc diff --git a/deps/npm/AUTHORS b/deps/npm/AUTHORS index 5b2f0f9c2e176a..3e75785db4763a 100644 --- a/deps/npm/AUTHORS +++ b/deps/npm/AUTHORS @@ -681,3 +681,4 @@ Felix Yan Zhenya Vinogradov Rafael Hengles Jan-Philip Gehrcke +Caleb Sacks <16855387+clabe45@users.noreply.github.com> diff --git a/deps/npm/CHANGELOG.md b/deps/npm/CHANGELOG.md index 8c7105645973eb..3abd37703a4d02 100644 --- a/deps/npm/CHANGELOG.md +++ b/deps/npm/CHANGELOG.md @@ -1,3 +1,23 @@ +## 6.13.7 (2020-01-28) + +### BUG FIXES +* [`7dbb91438`](https://github.com/npm/cli/commit/7dbb914382ecd2074fffb7eba81d93262e2d23c6) + [#655](https://github.com/npm/cli/pull/655) + Update CI detection cases + ([@isaacs](https://github.com/isaacs)) + +### DEPENDENCIES +* [`0fb1296c7`](https://github.com/npm/cli/commit/0fb1296c7d6d4bb9e78c96978c433cd65e55c0ea) + `libnpx@10.2.2` + ([@mikemimik](https://github.com/mikemimik)) +* [`c9b69d569`](https://github.com/npm/cli/commit/c9b69d569fec7944375a746e9c08a6fa9bec96ff) + `node-gyp@5.0.7` + ([@mikemimik](https://github.com/mikemimik)) +* [`e8dbaf452`](https://github.com/npm/cli/commit/e8dbaf452a1f6c5350bb0c37059b89a7448e7986) + `bin-links@1.1.7` + ([@mikemimik](https://github.com/mikemimik)) + * [#613](https://github.com/npm/cli/issues/613) Fixes bin entry for package + ## 6.13.6 (2020-01-09) ### DEPENDENCIES diff --git a/deps/npm/CONTRIBUTING.md b/deps/npm/CONTRIBUTING.md index 3fc4ff5dc7a828..981f0457d5c6bf 100644 --- a/deps/npm/CONTRIBUTING.md +++ b/deps/npm/CONTRIBUTING.md @@ -3,80 +3,190 @@ ## Table of Contents * [Introduction](#introduction) -* [Roles](#roles) - * [Community Members](#community-members) - * [Collaborators](#collaborators) - * [npm, Inc Employees](#npm-inc-employees) - +* [Code Structure](#code-structure) +* [Running Tests](#running-tests) +* [Debugging](#debugging) +* [Coverage](#coverage) +* [Benchmarking](#benchmarking) +* [Types of Contributions](#types-of-contributions) + * [Contributing an Issue?](#contributing-an-issue) + * [Contributing a Question?](#contributing-a-question) + * [Contributing a Bug Fix?](#contributing-a-bug-fix) + * [Contributing a Feature?](#contributing-a-bug-feature) +* [Development Dependencies](#development-dependencies) +* [Dependencies](#dependencies) ## Introduction -Welcome to the npm CLI Contributor Guide! This document outlines the npm CLI repository's process for community interaction and contribution. This includes the issue tracker, pull requests, wiki pages, and, to a certain extent, outside communication in the context of the npm CLI. It defines roles, responsibilities, and procedures, and is an entry point for anyone wishing to contribute their time and effort to making npm a better tool for the JavaScript community! +Welcome to the npm CLI Contributor Guide! This document outlines the npm CLI repository's process for community interaction and contribution. This includes the issue tracker, pull requests, wiki pages, and, to a certain extent, outside communication in the context of the npm CLI. This is an entry point for anyone wishing to contribute their time and effort to making npm a better tool for the JavaScript community! All interactions in the npm repository are covered by the [npm Code of Conduct](https://www.npmjs.com/policies/conduct) -## Roles -There are three main roles for people participating in the npm issue tracker. Each has a specific set of abilities and responsibilities: [Community members](#community-members), [Collaborators](#collaborators), and [npm, Inc employees](#npm-inc-employees). +## Code Structure +``` +/ +├── bin/ +│ │ # Directory for executable files. It's very rare that you +│ │ # will need to update a file in this directory. +│ │ +│ ├── npm # npm-cli entrypoint for bourne shell +│ ├── npm-cli.js # npm-cli entrypoint for node +│ ├── npm.cmd # npm-cli entrypoint for windows +│ ├── npx # npx entrypoint for bourne shell +│ ├── npx-cli.js # npx entrypoint for node +│ └── npx.cmd # npx entrypoint for windows +│ +├── docs/ 📖 +│ │ # Directory that contains the documentation website for +│ │ # the npm-cli. You can run this website locally, and have +│ │ # offline docs! 🔥📖🤓 +│ │ +│ ├── content/ # Markdown files for site content +│ ├── src/ # Source files for the website; gatsby related +│ └── package.json # Site manifest; scripts and dependencies +│ +├── lib/ 📦 +│ # All the Good Bits(tm) of the CLI project live here +│ +├── node_modules/ 🔋 +│ # Vendored dependencies for the CLI project (See the +│ # dependencies section below for more details). +│ +├── scripts/ 📜 +│ # We've created some helper scripts for working with the +│ # CLI project, specifically around managing our vendored +│ # dependencies, merging in pull-requests, and publishing +│ # releases. +│ +├── test/ 🧪 +│ # All the tests for the CLI live in this folder. We've +│ # got a lot of tests 🤓🧪🩺 +│ +├── CONTRIBUTING.md # This file! 🎉 +└── package.json # The projects main manifest file 📃 +``` + +## Running Tests + +``` +# Make sure you install the dependencies first before running tests. +$ npm install + +# Run tests for the CLI (it could take awhile). +$ npm run test +``` + +## Debugging + +It can be tricky to track down issues in the CLI. It's a large code base that has been evolving for over a decade. There is a handy `make` command that will connect the **cloned repository** you have on your machine with the global command, so you can add `console.log` statements or debug any other way you feel most comfortable with. + +``` +# Clone the repository to start with +$ git clone git@github.com:npm/cli.git + +# Change working directories into the repository +$ cd cli + +# Make sure you have the latest code (if that's what you're trying to debug) +$ git fetch origin latest + +# Connect repository to the global namespace +$ make link + +################# +# ALTERNATIVELY +################# +# If ou're working on a feature or bug, you can run the same command on your +# working branch and link that code. + +# Create new branch to work from (there are many ways) +$ git checkout -b feature/awesome-feature + +# Connect repository to global namespace +$ make link +``` + +## Coverage + +We try and make sure that each new feature or bug fix has tests to go along with them in order to keep code coverages consistent and increasing. We are actively striving for 100% code coverage! + +``` +# You can run the following command to find out coverage +$ npm run test-coverage +``` + +## Benchmarking + +We often want to know if the bug we've fixed for the feature we've added has any sort of performance impact. We've created a [benchmark suite](https://github.com/npm/benchmarks) to run against the CLI project from pull-requests. If you would like to know if there are any performance impacts to the work you're contributing, simply do the following: + +1. Make a pull-request against this repository +2. Add the following comment to the pull-request: "`test this please ✅`" + +This will trigger the [benmark suite](https://github.com/npm/benchmarks) to run against your pull-request, and when it's finished running it will post a comment on your pull-request just like bellow. You'll be able to see the results from the suite inline in your pull-request. + +> You'll notice that the bot-user will also add a 🚀 reaction to your comment to +let you know that it's sent the request to start the benchmark suite. + +![image](https://user-images.githubusercontent.com/2818462/72312698-e2e57f80-3656-11ea-9fcf-4a8f6b97b0d1.png) + +If you've updated your pull-reuqest and you'd like to run the the benchmark suite again, simple update your original comment, by adding `test this please ✅` again, or simply just adding another emoji to the **end**. _(The trigger is the phrase "test this please ✅" at the beginning of a comment. Updates will trigger as well, so long as the phrase stays at the beginning.)_. + +![image](https://user-images.githubusercontent.com/2818462/72313006-ec231c00-3657-11ea-9bd9-227634d67362.png) + +## Types of Contributions + +### Contributing an Issue? -Failure to comply with the expected responsibilities of each role, or violating the Code of Conduct will result in punitive action relative to the transgression, ranging from a warning to full removal from the project, at the discretion of npm employees. +Great!! Is your [new issue](https://github.com/npm/cli/issues/new/choose) a [bug](https://github.com/npm/cli/issues/new?template=bug.md&title=%5BBUG%5D+%3Ctitle%3E), a [feature](https://github.com/npm/cli/issues/new?template=feature.md&title=%5BFEATURE%5D+%3Ctitle%3E), or a [question](https://github.com/npm/cli/issues/new?template=question.md&title=%5BQUESTION%5D+%3Ctitle%3E)? -### Community Members +### Contributing a Question? -This includes anyone who may show up to the npm/npm repo with issues, PRs, comments etc. They may not have any other involvement with npm. +Huh? 🤔 Got a situation you're not sure about?! Perfect! We've got some resources you can use. -#### Abilities +* Our [documentation site](https://docs.npmjs.com/) +* The local docs that come with the CLI project -* Open issues and PRs -* Comment on issues and PRs + > **Example**: `npm help install --viewer browser` -#### Responsibilities +* The man pages that are built and shipped with the CLI -* Comment on issues when they have a reference to the answer. -* If community members aren't sure they are correct and don't have a reference to the answer, please leave the issue and try another one. -* Defer to collaborators and npm employees for answers. -* Make sure to search for [the troubleshooting posts on npm.community](https://npm.community/c/support/troubleshooting) and search on the issue tracker for similar issues before opening a new one. -* Any users with urgent support needs are welcome to email support@npmjs.com, and our dedicated support team will be happy to help. + > **Example**: `man npm-install` (only on linux/macOS) -PLEASE don't @ collaborators or npm employees on issues. The CLI team is small, and has many outstanding commitments to fulfill. +* Search of the [current issues](https://github.com/npm/cli/issues) -### Collaborators +### Contributing a Bug Fix? -These are folks who have the ability to label and close issues. The role of collaborators may expand over time, but for now it is a limited (& important) role. This is an excellent way to contribute to npm without writing code. +We'd be happy to triage and help! Head over to the issues and [create a new one](https://github.com/npm/cli/issues/new?template=bug.md&title=%5BBUG%5D+%3Ctitle%3E)! -Community members may become collaborators by showing consistent, proven track record of quality contributions to the project, a reasonable level of proficiency with the CLI, and regular participation through the tracker and other related mediums, including regular contact with the CLI team itself. This role entails a higher level of responsibility than community member, so we ask for a higher level of understanding and commitment. +> We'll need a little bit of information about what happened, rather than "it broke". Such as: +* When did/does this bug happen? +* Can you reproduce it? _(Can you make it happen more than once.)_ +* What version of `node`/`npm` are you running on your computer? +* What did you expect it to do? +* What did it _actually do? +* etc... -Collaborators who become inactive for 3 months or longer may have their collaborator privileges removed until they are ready to return. +### Contributing a Feature? -#### Abilities +Snazzy, we're always up for fancy new things! If the feature is fairly minor, the team can triage it and prioritize it into our backlog. However, if the feature is a little more complex, then it's best to create an [RFC](https://en.wikipedia.org/wiki/Request_for_Comments) in our [RFC repository](https://github.com/npm/rfcs). Exactly how to do that is outlined in that repository. If you're not sure _exactly_ how to implement your idea, or don't want to make a document about your idea, then please create an issue on that repository. We consider these RRFC's, or a "Requesting Request For Comment". -* Label/triage new issues -* Respond to ongoing issues -* Close resolved issues. +## Development Dependencies -#### Responsibilities +You'll need a few things installed in order to update and test the CLI project during development: -* Only answer questions when they know the answer, and provide a reference to the answer. -* If collaborators aren't totally confident about their answer, please leave the issue and try another one. -* If they've responded to an issue, it becomes their responsibility to see it to resolution. -* Defer to fellow Collaborators & npm employees for answers (Again, please don't @ collaborators or npm employees, thank you!) -* Make sure to search [the troubleshooting posts on npm.community](https://npm.community/c/support/troubleshooting) and search the rest of the forum for similar topics. +* [node](https://nodejs.org/) v8 or greater -### npm, Inc Employees +> We recommend that you have a [node version manager](https://github.com/nvm-sh/nvm) installed if you plan on fixing bugs that might be present in a specific version of node. With a version manager you can easily switch versions of node and test if your changes to the CLI project are working. -Folks who work at npm, Inc, who have a responsibility to ensure the stability and functionality of the tools npm offers. +* [git](https://git-scm.com/) v2.11+ -#### Abilities -* Label/triage new issues -* Respond to ongoing issues -* Close resolved issues -* Land PRs +## Dependencies -Please note that this is a living document, and the CLI team will put up PRs to it as needed. +> Package vendoring is commonly referred to as the case where dependent packages are stored in the same place as your project. That usually means you dependencies are checked into your source management system, such as Git. -#### Responsibilities +The CLI project vendors it's dependencies in the `node_modules/` folder. Meaning all the dependencies that the CLI project uses are contained withing the project itself. This is represented by the `bundledDependencies` section in the root level `package.json` file. The main reason for this is because the `npm` CLI project is distributed with the NodeJS runtime and needs to work out of the box, which means all dependencies need to be available after the runtime is installed. -* Preserve and promote the health of the CLI, the registry, the website, etc. +There are a couple scripts created to help manage this process in the `scripts/` folder. -In special cases, [Collaborators](#collaborators) may request time to speak with an npm employee directly, by contacting them and coordinating a time/place. diff --git a/deps/npm/README.md b/deps/npm/README.md index 16c7e4b18cdf00..05da169f259619 100644 --- a/deps/npm/README.md +++ b/deps/npm/README.md @@ -155,10 +155,6 @@ When you find issues, please report them: Be sure to include *all* of the output from the npm command that didn't work as expected. The `npm-debug.log` file is also helpful to provide. -You can also find npm people in `#npm` on https://package.community/ or -[on Twitter](https://twitter.com/npm_support). Whoever responds will no -doubt tell you to put the output in a gist or email. - ## SEE ALSO * npm(1) diff --git a/deps/npm/docs/content/configuring-npm/package-json.md b/deps/npm/docs/content/configuring-npm/package-json.md index b7759f482f914a..ccdbe041fb063f 100644 --- a/deps/npm/docs/content/configuring-npm/package-json.md +++ b/deps/npm/docs/content/configuring-npm/package-json.md @@ -740,7 +740,8 @@ If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. This is a map of package name to version or url, just like the `dependencies` object. The difference is that build failures do not cause -installation to fail. +installation to fail. Running `npm install --no-optional` will prevent these +dependencies from being installed. It is still your program's responsibility to handle the lack of the dependency. For example, something like this: diff --git a/deps/npm/docs/public/cli-commands/npm-access/index.html b/deps/npm/docs/public/cli-commands/npm-access/index.html index 6dee07ecbfda50..33febc80177727 100644 --- a/deps/npm/docs/public/cli-commands/npm-access/index.html +++ b/deps/npm/docs/public/cli-commands/npm-access/index.html @@ -74,7 +74,7 @@ } } }) -

npm access

+

npm access

Set access level on published packages

Synopsis

npm access public [<package>]
@@ -148,4 +148,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-adduser/index.html b/deps/npm/docs/public/cli-commands/npm-adduser/index.html index 33ffcaf1bb0918..cf1efe2b9fa631 100644 --- a/deps/npm/docs/public/cli-commands/npm-adduser/index.html +++ b/deps/npm/docs/public/cli-commands/npm-adduser/index.html @@ -74,7 +74,7 @@ } } }) -

+

section: cli-commands title: npm-adduser description: Set access level on published packages

@@ -143,4 +143,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-audit/index.html b/deps/npm/docs/public/cli-commands/npm-audit/index.html index 2894583dde6209..594d46ad9d3f38 100644 --- a/deps/npm/docs/public/cli-commands/npm-audit/index.html +++ b/deps/npm/docs/public/cli-commands/npm-audit/index.html @@ -74,7 +74,7 @@ } } }) -

npm audit

+

npm audit

Run a security audit

Synopsis

npm audit [--json|--parseable|--audit-level=(low|moderate|high|critical)]
@@ -165,4 +165,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-bin/index.html b/deps/npm/docs/public/cli-commands/npm-bin/index.html index 980859fcaa6cd4..c6ec5573855133 100644 --- a/deps/npm/docs/public/cli-commands/npm-bin/index.html +++ b/deps/npm/docs/public/cli-commands/npm-bin/index.html @@ -74,7 +74,7 @@ } } }) -

npm bin

+

npm bin

Display npm bin folder

Synopsis

npm bin [-g|--global]
@@ -94,4 +94,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-bugs/index.html b/deps/npm/docs/public/cli-commands/npm-bugs/index.html index a7d59383e00722..c5992039ed42b4 100644 --- a/deps/npm/docs/public/cli-commands/npm-bugs/index.html +++ b/deps/npm/docs/public/cli-commands/npm-bugs/index.html @@ -74,7 +74,7 @@ } } }) -

npm bugs

+

npm bugs

Bugs for a package in a web browser maybe

Synopsis

npm bugs [<pkgname>]
@@ -114,4 +114,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-build/index.html b/deps/npm/docs/public/cli-commands/npm-build/index.html index 6a70a90b9e6b22..bfaa096a04bf97 100644 --- a/deps/npm/docs/public/cli-commands/npm-build/index.html +++ b/deps/npm/docs/public/cli-commands/npm-build/index.html @@ -74,7 +74,7 @@ } } }) -

npm build

+

npm build

Build a package

Synopsis

npm build [<package-folder>]
@@ -100,4 +100,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-bundle/index.html b/deps/npm/docs/public/cli-commands/npm-bundle/index.html index 763f9b9298adcb..393c5b63358a23 100644 --- a/deps/npm/docs/public/cli-commands/npm-bundle/index.html +++ b/deps/npm/docs/public/cli-commands/npm-bundle/index.html @@ -74,7 +74,7 @@ } } }) -

npm bundle

+

npm bundle

REMOVED

Description

The npm bundle command has been removed in 1.0, for the simple reason @@ -91,4 +91,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-cache/index.html b/deps/npm/docs/public/cli-commands/npm-cache/index.html index 83694f95505c9e..01e2bee9191d07 100644 --- a/deps/npm/docs/public/cli-commands/npm-cache/index.html +++ b/deps/npm/docs/public/cli-commands/npm-cache/index.html @@ -74,7 +74,7 @@ } } }) -

npm cache

+

npm cache

Manipulates packages cache

Synopsis

npm cache add <tarball file>
@@ -145,4 +145,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-ci/index.html b/deps/npm/docs/public/cli-commands/npm-ci/index.html index 1d36a26c5bf997..c4312a4f8b252f 100644 --- a/deps/npm/docs/public/cli-commands/npm-ci/index.html +++ b/deps/npm/docs/public/cli-commands/npm-ci/index.html @@ -74,7 +74,7 @@ } } }) -

npm ci

+

npm ci

Install a project with a clean slate

Synopsis

npm ci
@@ -122,4 +122,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-completion/index.html b/deps/npm/docs/public/cli-commands/npm-completion/index.html index 2bab166d185525..8011d6cc650021 100644 --- a/deps/npm/docs/public/cli-commands/npm-completion/index.html +++ b/deps/npm/docs/public/cli-commands/npm-completion/index.html @@ -74,7 +74,7 @@ } } }) -

npm completion

+

npm completion

Tab Completion for npm

Synopsis

source <(npm completion)
@@ -104,4 +104,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-config/index.html b/deps/npm/docs/public/cli-commands/npm-config/index.html index 379de9129f0575..d20a4504b7bfc4 100644 --- a/deps/npm/docs/public/cli-commands/npm-config/index.html +++ b/deps/npm/docs/public/cli-commands/npm-config/index.html @@ -74,7 +74,7 @@ } } }) -

npm config

+

npm config

Manage the npm configuration files

Synopsis

npm config set <key> <value> [-g|--global]
@@ -128,4 +128,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-dedupe/index.html b/deps/npm/docs/public/cli-commands/npm-dedupe/index.html index 5fa1125304abcb..6ab29223b2b02f 100644 --- a/deps/npm/docs/public/cli-commands/npm-dedupe/index.html +++ b/deps/npm/docs/public/cli-commands/npm-dedupe/index.html @@ -74,7 +74,7 @@ } } }) -

npm dedupe

+

npm dedupe

Reduce duplication

Synopsis

npm dedupe
@@ -121,4 +121,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-deprecate/index.html b/deps/npm/docs/public/cli-commands/npm-deprecate/index.html index 54a695e7ea8dfb..1c451c1ea62d86 100644 --- a/deps/npm/docs/public/cli-commands/npm-deprecate/index.html +++ b/deps/npm/docs/public/cli-commands/npm-deprecate/index.html @@ -74,7 +74,7 @@ } } }) -

npm deprecate

+

npm deprecate

Deprecate a version of a package

Synopsis

npm deprecate <pkg>[@<version>] <message>
@@ -100,4 +100,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-dist-tag/index.html b/deps/npm/docs/public/cli-commands/npm-dist-tag/index.html index fb15951c5f1817..4f358442d2f1b6 100644 --- a/deps/npm/docs/public/cli-commands/npm-dist-tag/index.html +++ b/deps/npm/docs/public/cli-commands/npm-dist-tag/index.html @@ -74,7 +74,7 @@ } } }) -

+

section: cli-commands title: npm-dist-tag description: Modify package distribution tags

@@ -149,4 +149,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-docs/index.html b/deps/npm/docs/public/cli-commands/npm-docs/index.html index db261fafb80f3c..7d6c5dd7a3cf41 100644 --- a/deps/npm/docs/public/cli-commands/npm-docs/index.html +++ b/deps/npm/docs/public/cli-commands/npm-docs/index.html @@ -74,7 +74,7 @@ } } }) -

npm docs

+

npm docs

Docs for a package in a web browser maybe

Synopsis

npm docs [<pkgname> [<pkgname> ...]]
@@ -115,4 +115,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-doctor/index.html b/deps/npm/docs/public/cli-commands/npm-doctor/index.html index a2135e5a5bb054..98941778502b08 100644 --- a/deps/npm/docs/public/cli-commands/npm-doctor/index.html +++ b/deps/npm/docs/public/cli-commands/npm-doctor/index.html @@ -74,7 +74,7 @@ } } }) -

npm doctor

+

npm doctor

Check your environments

Synopsis

npm doctor
@@ -163,4 +163,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-edit/index.html b/deps/npm/docs/public/cli-commands/npm-edit/index.html index c3435bc4854022..d405195ef1582a 100644 --- a/deps/npm/docs/public/cli-commands/npm-edit/index.html +++ b/deps/npm/docs/public/cli-commands/npm-edit/index.html @@ -74,7 +74,7 @@ } } }) -

npm edit

+

npm edit

Edit an installed package

Synopsis

npm edit <pkg>[/<subpkg>...]
@@ -110,4 +110,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-explore/index.html b/deps/npm/docs/public/cli-commands/npm-explore/index.html index 6e7daa4c931ef8..0a087af7ad73bc 100644 --- a/deps/npm/docs/public/cli-commands/npm-explore/index.html +++ b/deps/npm/docs/public/cli-commands/npm-explore/index.html @@ -74,7 +74,7 @@ } } }) -

+

section: cli-commands title: npm-explore description: Browse an installed package

@@ -114,4 +114,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-fund/index.html b/deps/npm/docs/public/cli-commands/npm-fund/index.html index 93dfcb91bfd5fa..bfe02b228d5bc2 100644 --- a/deps/npm/docs/public/cli-commands/npm-fund/index.html +++ b/deps/npm/docs/public/cli-commands/npm-fund/index.html @@ -74,7 +74,7 @@ } } }) -

npm fund

+

npm fund

Retrieve funding information

Synopsis

    npm fund [<pkg>]
@@ -121,4 +121,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-help-search/index.html b/deps/npm/docs/public/cli-commands/npm-help-search/index.html index 8e084402f6eee3..1f6170daae7a97 100644 --- a/deps/npm/docs/public/cli-commands/npm-help-search/index.html +++ b/deps/npm/docs/public/cli-commands/npm-help-search/index.html @@ -74,7 +74,7 @@ } } }) -

npm help-search

+

npm help-search

Search npm help documentation

Synopsis

npm help-search <text>
@@ -105,4 +105,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-help/index.html b/deps/npm/docs/public/cli-commands/npm-help/index.html index c94005329fad87..7bb65bffd3ce55 100644 --- a/deps/npm/docs/public/cli-commands/npm-help/index.html +++ b/deps/npm/docs/public/cli-commands/npm-help/index.html @@ -74,7 +74,7 @@ } } }) -

npm help

+

npm help

Get help on npm

Synopsis

npm help <term> [<terms..>]
@@ -107,4 +107,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-hook/index.html b/deps/npm/docs/public/cli-commands/npm-hook/index.html index 0002da6ba61583..4474cc5565f703 100644 --- a/deps/npm/docs/public/cli-commands/npm-hook/index.html +++ b/deps/npm/docs/public/cli-commands/npm-hook/index.html @@ -74,7 +74,7 @@ } } }) -

npm hook

+

npm hook

Manage registry hooks

Synopsis

npm hook ls [pkg]
@@ -119,4 +119,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-init/index.html b/deps/npm/docs/public/cli-commands/npm-init/index.html index 75b835eb664bb6..8a585d1ae6d53c 100644 --- a/deps/npm/docs/public/cli-commands/npm-init/index.html +++ b/deps/npm/docs/public/cli-commands/npm-init/index.html @@ -74,7 +74,7 @@ } } }) -

npm init

+

npm init

create a package.json file

Synopsis

npm init [--force|-f|--yes|-y|--scope]
@@ -126,4 +126,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-install-ci-test/index.html b/deps/npm/docs/public/cli-commands/npm-install-ci-test/index.html index 79dced8bb642c6..e3ed77e9147b56 100644 --- a/deps/npm/docs/public/cli-commands/npm-install-ci-test/index.html +++ b/deps/npm/docs/public/cli-commands/npm-install-ci-test/index.html @@ -74,7 +74,7 @@ } } }) -

npm install-ci-test

+

npm install-ci-test

Install a project with a clean slate and run tests

Synopsis

npm install-ci-test
@@ -93,4 +93,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-install-test/index.html b/deps/npm/docs/public/cli-commands/npm-install-test/index.html index f2ae1d1593ddd9..7c264c56fb922b 100644 --- a/deps/npm/docs/public/cli-commands/npm-install-test/index.html +++ b/deps/npm/docs/public/cli-commands/npm-install-test/index.html @@ -74,7 +74,7 @@ } } }) -

npm install-test

+

npm install-test

Install package(s) and run tests

Synopsis

npm install-test (with no args, in package dir)
@@ -102,4 +102,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-install/index.html b/deps/npm/docs/public/cli-commands/npm-install/index.html index 48ad186f1ba6c0..c64ae4d529fd56 100644 --- a/deps/npm/docs/public/cli-commands/npm-install/index.html +++ b/deps/npm/docs/public/cli-commands/npm-install/index.html @@ -74,7 +74,7 @@ } } }) -

npm install

+

npm install

Install a package

Synopsis

npm install (with no args, in package dir)
@@ -468,4 +468,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-link/index.html b/deps/npm/docs/public/cli-commands/npm-link/index.html index 9a9ccd18cf3b03..f84406e8a8d3a0 100644 --- a/deps/npm/docs/public/cli-commands/npm-link/index.html +++ b/deps/npm/docs/public/cli-commands/npm-link/index.html @@ -74,7 +74,7 @@ } } }) -

npm link

+

npm link

Synopsis

npm link (in package dir)
@@ -134,4 +134,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-logout/index.html b/deps/npm/docs/public/cli-commands/npm-logout/index.html index 5f74718ef69851..a7512ee5af2430 100644 --- a/deps/npm/docs/public/cli-commands/npm-logout/index.html +++ b/deps/npm/docs/public/cli-commands/npm-logout/index.html @@ -74,7 +74,7 @@ } } }) -

npm logout

+

npm logout

Log out of the registry

Synopsis

npm logout [--registry=<url>] [--scope=<@scope>]
@@ -109,4 +109,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-ls/index.html b/deps/npm/docs/public/cli-commands/npm-ls/index.html index 1a55972865879c..bfd746a74ef8de 100644 --- a/deps/npm/docs/public/cli-commands/npm-ls/index.html +++ b/deps/npm/docs/public/cli-commands/npm-ls/index.html @@ -74,7 +74,7 @@ } } }) -

npm ls

+
\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-org/index.html b/deps/npm/docs/public/cli-commands/npm-org/index.html index 97d2f37e1db7b8..57b897e9638f19 100644 --- a/deps/npm/docs/public/cli-commands/npm-org/index.html +++ b/deps/npm/docs/public/cli-commands/npm-org/index.html @@ -74,7 +74,7 @@ } } }) -

npm org

+

npm org

Manage orgs

Synopsis

npm org set <orgname> <username> [developer | admin | owner]
@@ -107,4 +107,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-outdated/index.html b/deps/npm/docs/public/cli-commands/npm-outdated/index.html index d9cc4fe49cb40e..e80c1cfe0cd137 100644 --- a/deps/npm/docs/public/cli-commands/npm-outdated/index.html +++ b/deps/npm/docs/public/cli-commands/npm-outdated/index.html @@ -74,7 +74,7 @@ } } }) -

npm outdated

+

npm outdated

Check for outdated packages

Synopsis

npm outdated [[<@scope>/]<pkg> ...]
@@ -178,4 +178,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-owner/index.html b/deps/npm/docs/public/cli-commands/npm-owner/index.html index e314b164e15dcd..f8439c79695da0 100644 --- a/deps/npm/docs/public/cli-commands/npm-owner/index.html +++ b/deps/npm/docs/public/cli-commands/npm-owner/index.html @@ -74,7 +74,7 @@ } } }) -

npm owner

+

npm owner

Manage package owners

Synopsis

npm owner add <user> [<@scope>/]<pkg>
@@ -114,4 +114,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-pack/index.html b/deps/npm/docs/public/cli-commands/npm-pack/index.html index 8956f07d207716..f3756959783413 100644 --- a/deps/npm/docs/public/cli-commands/npm-pack/index.html +++ b/deps/npm/docs/public/cli-commands/npm-pack/index.html @@ -74,7 +74,7 @@ } } }) -

npm pack

+

npm pack

Create a tarball from a package

Synopsis

npm pack [[<@scope>/]<pkg>...] [--dry-run]
@@ -102,4 +102,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-ping/index.html b/deps/npm/docs/public/cli-commands/npm-ping/index.html index bb21db0b0a3eaf..711d2b5a5ed372 100644 --- a/deps/npm/docs/public/cli-commands/npm-ping/index.html +++ b/deps/npm/docs/public/cli-commands/npm-ping/index.html @@ -74,7 +74,7 @@ } } }) -

npm ping

+

npm ping

Ping npm registry

Synopsis

npm ping [--registry <registry>]
@@ -95,4 +95,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-prefix/index.html b/deps/npm/docs/public/cli-commands/npm-prefix/index.html index b7c211de1f3dd7..c14010a2d9cf66 100644 --- a/deps/npm/docs/public/cli-commands/npm-prefix/index.html +++ b/deps/npm/docs/public/cli-commands/npm-prefix/index.html @@ -74,7 +74,7 @@ } } }) -

npm prefix

+

npm prefix

Display prefix

Synopsis

npm prefix [-g]
@@ -98,4 +98,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-profile/index.html b/deps/npm/docs/public/cli-commands/npm-profile/index.html index d47ce14d51c51c..8cd34b5c300f20 100644 --- a/deps/npm/docs/public/cli-commands/npm-profile/index.html +++ b/deps/npm/docs/public/cli-commands/npm-profile/index.html @@ -74,7 +74,7 @@ } } }) -

npm profile

+

npm profile

Change settings on your registry profile

Synopsis

npm profile get [--json|--parseable] [<property>]
@@ -148,4 +148,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-prune/index.html b/deps/npm/docs/public/cli-commands/npm-prune/index.html index be9ed3f14aad53..59c87eb763154b 100644 --- a/deps/npm/docs/public/cli-commands/npm-prune/index.html +++ b/deps/npm/docs/public/cli-commands/npm-prune/index.html @@ -74,7 +74,7 @@ } } }) -

npm prune

+

npm prune

Remove extraneous packages

Synopsis

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
@@ -108,4 +108,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-publish/index.html b/deps/npm/docs/public/cli-commands/npm-publish/index.html index 73e142b4f2a096..5cac777b54ef80 100644 --- a/deps/npm/docs/public/cli-commands/npm-publish/index.html +++ b/deps/npm/docs/public/cli-commands/npm-publish/index.html @@ -74,7 +74,7 @@ } } }) -

npm publish

+

npm publish

Publish a package

Synopsis

npm publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>] [--otp otpcode] [--dry-run]
@@ -140,4 +140,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-rebuild/index.html b/deps/npm/docs/public/cli-commands/npm-rebuild/index.html index d62963fe835430..d09ba09ab78cbf 100644 --- a/deps/npm/docs/public/cli-commands/npm-rebuild/index.html +++ b/deps/npm/docs/public/cli-commands/npm-rebuild/index.html @@ -74,7 +74,7 @@ } } }) -

npm rebuild

+

npm rebuild

Rebuild a package

Synopsis

npm rebuild [[<@scope>/<name>]...]
@@ -93,4 +93,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-repo/index.html b/deps/npm/docs/public/cli-commands/npm-repo/index.html index 7845dcadce855e..3b01aea44a5b9f 100644 --- a/deps/npm/docs/public/cli-commands/npm-repo/index.html +++ b/deps/npm/docs/public/cli-commands/npm-repo/index.html @@ -74,7 +74,7 @@ } } }) -

npm repo

+

npm repo

Open package repository page in the browser

Synopsis

npm repo [<pkg>]
@@ -101,4 +101,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-restart/index.html b/deps/npm/docs/public/cli-commands/npm-restart/index.html index 0a4527f0d1f082..a561fad81da43c 100644 --- a/deps/npm/docs/public/cli-commands/npm-restart/index.html +++ b/deps/npm/docs/public/cli-commands/npm-restart/index.html @@ -74,7 +74,7 @@ } } }) -

npm restart

+

npm restart

Restart a package

Synopsis

npm restart [-- <args>]
@@ -113,4 +113,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-root/index.html b/deps/npm/docs/public/cli-commands/npm-root/index.html index f7073c00780d2e..81173f0f3e859e 100644 --- a/deps/npm/docs/public/cli-commands/npm-root/index.html +++ b/deps/npm/docs/public/cli-commands/npm-root/index.html @@ -74,7 +74,7 @@ } } }) -

npm root

+

npm root

Display npm root

Synopsis

npm root [-g]
@@ -94,4 +94,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-run-script/index.html b/deps/npm/docs/public/cli-commands/npm-run-script/index.html index 6b6fc96ca2a484..efb484e69d7906 100644 --- a/deps/npm/docs/public/cli-commands/npm-run-script/index.html +++ b/deps/npm/docs/public/cli-commands/npm-run-script/index.html @@ -74,7 +74,7 @@ } } }) -

npm run-script

+

npm run-script

Run arbitrary package scripts

Synopsis

npm run-script <command> [--silent] [-- <args>...]
@@ -143,4 +143,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-search/index.html b/deps/npm/docs/public/cli-commands/npm-search/index.html index bc1f0e4deec865..d305edcce484ec 100644 --- a/deps/npm/docs/public/cli-commands/npm-search/index.html +++ b/deps/npm/docs/public/cli-commands/npm-search/index.html @@ -74,7 +74,7 @@ } } }) -

npm search

+

npm search

Search for packages

Synopsis

npm search [-l|--long] [--json] [--parseable] [--no-description] [search terms ...]
@@ -168,4 +168,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-shrinkwrap/index.html b/deps/npm/docs/public/cli-commands/npm-shrinkwrap/index.html index 185928d4013da8..5bc73cbdc9d753 100644 --- a/deps/npm/docs/public/cli-commands/npm-shrinkwrap/index.html +++ b/deps/npm/docs/public/cli-commands/npm-shrinkwrap/index.html @@ -74,7 +74,7 @@ } } }) -

npm shrinkwrap

+

npm shrinkwrap

Lock down dependency versions for publication

Synopsis

npm shrinkwrap
@@ -101,4 +101,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-star/index.html b/deps/npm/docs/public/cli-commands/npm-star/index.html index 1db3df501fb48b..12babbf3f3ea12 100644 --- a/deps/npm/docs/public/cli-commands/npm-star/index.html +++ b/deps/npm/docs/public/cli-commands/npm-star/index.html @@ -74,7 +74,7 @@ } } }) -

npm star

+

npm star

Mark your favorite packages

Synopsis

npm star [<pkg>...]
@@ -96,4 +96,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-stars/index.html b/deps/npm/docs/public/cli-commands/npm-stars/index.html index 9feccb1255ae14..629267c0ebfae3 100644 --- a/deps/npm/docs/public/cli-commands/npm-stars/index.html +++ b/deps/npm/docs/public/cli-commands/npm-stars/index.html @@ -74,7 +74,7 @@ } } }) -

npm stars

+

npm stars

View packages marked as favorites

Synopsis

npm stars [<user>]
@@ -96,4 +96,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-start/index.html b/deps/npm/docs/public/cli-commands/npm-start/index.html index b45fdf006ea2dd..13ad0d84b30a48 100644 --- a/deps/npm/docs/public/cli-commands/npm-start/index.html +++ b/deps/npm/docs/public/cli-commands/npm-start/index.html @@ -74,7 +74,7 @@ } } }) -

npm start

+

npm start

Start a package

Synopsis

npm start [-- <args>]
@@ -98,4 +98,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-stop/index.html b/deps/npm/docs/public/cli-commands/npm-stop/index.html index f8dbcd08ba6dcd..65e34691c59c11 100644 --- a/deps/npm/docs/public/cli-commands/npm-stop/index.html +++ b/deps/npm/docs/public/cli-commands/npm-stop/index.html @@ -74,7 +74,7 @@ } } }) -

npm stop

+

npm stop

Stop a package

Synopsis

npm stop [-- <args>]
@@ -94,4 +94,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-team/index.html b/deps/npm/docs/public/cli-commands/npm-team/index.html index 58336283937a21..ab494c39401d11 100644 --- a/deps/npm/docs/public/cli-commands/npm-team/index.html +++ b/deps/npm/docs/public/cli-commands/npm-team/index.html @@ -74,7 +74,7 @@ } } }) -

npm team

+

npm team

Manage organization teams and team memberships

Synopsis

npm team create <scope:team>
@@ -124,4 +124,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-test/index.html b/deps/npm/docs/public/cli-commands/npm-test/index.html index c0af810b85c325..05ab9ecca9d3cc 100644 --- a/deps/npm/docs/public/cli-commands/npm-test/index.html +++ b/deps/npm/docs/public/cli-commands/npm-test/index.html @@ -74,7 +74,7 @@ } } }) -

npm test

+

npm test

Test a package

Synopsis

npm test [-- <args>]
@@ -96,4 +96,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-token/index.html b/deps/npm/docs/public/cli-commands/npm-token/index.html index 3edc2871442405..38faa5edc32c28 100644 --- a/deps/npm/docs/public/cli-commands/npm-token/index.html +++ b/deps/npm/docs/public/cli-commands/npm-token/index.html @@ -74,7 +74,7 @@ } } }) -

npm token

+

npm token

Manage your authentication tokens

Synopsis

  npm token list [--json|--parseable]
@@ -133,4 +133,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-uninstall/index.html b/deps/npm/docs/public/cli-commands/npm-uninstall/index.html index 6c3e9cd979b92a..8abde62f8e6bff 100644 --- a/deps/npm/docs/public/cli-commands/npm-uninstall/index.html +++ b/deps/npm/docs/public/cli-commands/npm-uninstall/index.html @@ -74,7 +74,7 @@ } } }) -

npm uninstall

+

npm uninstall

Remove a package

Synopsis

npm uninstall [<@scope>/]<pkg>[@<version>]... [-S|--save|-D|--save-dev|-O|--save-optional|--no-save]
@@ -118,4 +118,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-unpublish/index.html b/deps/npm/docs/public/cli-commands/npm-unpublish/index.html index 14e2dfde744904..89884913bcee15 100644 --- a/deps/npm/docs/public/cli-commands/npm-unpublish/index.html +++ b/deps/npm/docs/public/cli-commands/npm-unpublish/index.html @@ -74,7 +74,7 @@ } } }) -

npm unpublish

+

npm unpublish

Remove a package from the registry

Synopsis

npm unpublish [<@scope>/]<pkg>[@<version>]
@@ -113,4 +113,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-update/index.html b/deps/npm/docs/public/cli-commands/npm-update/index.html index 56efd23bd6d4e4..0c10e200ca677a 100644 --- a/deps/npm/docs/public/cli-commands/npm-update/index.html +++ b/deps/npm/docs/public/cli-commands/npm-update/index.html @@ -74,7 +74,7 @@ } } }) -

npm update

+

npm update

Update a package

Synopsis

npm update [-g] [<pkg>...]
@@ -166,4 +166,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-version/index.html b/deps/npm/docs/public/cli-commands/npm-version/index.html index 9b199a2abbbd66..a9201194edf6e0 100644 --- a/deps/npm/docs/public/cli-commands/npm-version/index.html +++ b/deps/npm/docs/public/cli-commands/npm-version/index.html @@ -74,7 +74,7 @@ } } }) -

npm version

+

npm version

Bump a package version

Synopsis

npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]
@@ -180,4 +180,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-view/index.html b/deps/npm/docs/public/cli-commands/npm-view/index.html index e5720713c7e73b..e6f88d50b36cb8 100644 --- a/deps/npm/docs/public/cli-commands/npm-view/index.html +++ b/deps/npm/docs/public/cli-commands/npm-view/index.html @@ -74,7 +74,7 @@ } } }) -

npm view

+

npm view

View registry info

Synopsis

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]
@@ -145,4 +145,4 @@ 

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm-whoami/index.html b/deps/npm/docs/public/cli-commands/npm-whoami/index.html index d8e70776cb37e2..79bbd7ba4d6a12 100644 --- a/deps/npm/docs/public/cli-commands/npm-whoami/index.html +++ b/deps/npm/docs/public/cli-commands/npm-whoami/index.html @@ -74,7 +74,7 @@ } } }) -

npm whoami

+

npm whoami

Display npm username

Synopsis

npm whoami [--registry <registry>]
@@ -92,4 +92,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/cli-commands/npm/index.html b/deps/npm/docs/public/cli-commands/npm/index.html index 90aa3ccfffa955..bc67b74183ecc3 100644 --- a/deps/npm/docs/public/cli-commands/npm/index.html +++ b/deps/npm/docs/public/cli-commands/npm/index.html @@ -74,12 +74,12 @@ } } }) -

npm

+

npm

javascript package manager

Synopsis

npm <command> [args]

Version

-

6.13.6

+

6.13.7

Description

npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency @@ -211,4 +211,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/folders/index.html b/deps/npm/docs/public/configuring-npm/folders/index.html index b5f293542fcbf8..4b6eadf7737714 100644 --- a/deps/npm/docs/public/configuring-npm/folders/index.html +++ b/deps/npm/docs/public/configuring-npm/folders/index.html @@ -74,7 +74,7 @@ } } }) -

folders

+

folders

Folder Structures Used by npm

Description

npm puts various things on your computer. That's its job.

@@ -240,4 +240,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/install/index.html b/deps/npm/docs/public/configuring-npm/install/index.html index a49c132a1bc776..598a8534777e15 100644 --- a/deps/npm/docs/public/configuring-npm/install/index.html +++ b/deps/npm/docs/public/configuring-npm/install/index.html @@ -74,7 +74,7 @@ } } }) -

install

+

install

Download and Install npm

Description

To publish and install packages to and from the public npm registry, you must install Node.js and the npm command line interface using either a Node version manager or a Node installer. We strongly recommend using a Node version manager to install Node.js and npm. We do not recommend using a Node installer, since the Node installation process installs npm in a directory with local permissions and can cause permissions errors when you run npm packages globally.

@@ -123,4 +123,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/npmrc/index.html b/deps/npm/docs/public/configuring-npm/npmrc/index.html index 08245496286821..a5c8911f547b4e 100644 --- a/deps/npm/docs/public/configuring-npm/npmrc/index.html +++ b/deps/npm/docs/public/configuring-npm/npmrc/index.html @@ -74,7 +74,7 @@ } } }) -

npmrc

+

npmrc

The npm config files

Description

npm gets its config settings from the command line, environment @@ -145,4 +145,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/package-json/index.html b/deps/npm/docs/public/configuring-npm/package-json/index.html index 373c330ba1ee18..ad6300d846d7f6 100644 --- a/deps/npm/docs/public/configuring-npm/package-json/index.html +++ b/deps/npm/docs/public/configuring-npm/package-json/index.html @@ -74,7 +74,7 @@ } } }) -

package.json

+
\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/package-lock-json/index.html b/deps/npm/docs/public/configuring-npm/package-lock-json/index.html index ba4438363e4c8b..07ea625f509782 100644 --- a/deps/npm/docs/public/configuring-npm/package-lock-json/index.html +++ b/deps/npm/docs/public/configuring-npm/package-lock-json/index.html @@ -74,7 +74,7 @@ } } }) -

package-lock.json

+

package-lock.json

A manifestation of the manifest

Description

package-lock.json is automatically generated for any operations where npm @@ -186,4 +186,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/package-locks/index.html b/deps/npm/docs/public/configuring-npm/package-locks/index.html index 132630b12480b9..f3846d3ad01565 100644 --- a/deps/npm/docs/public/configuring-npm/package-locks/index.html +++ b/deps/npm/docs/public/configuring-npm/package-locks/index.html @@ -74,7 +74,7 @@ } } }) -

package-locks

+

package-locks

An explanation of npm lockfiles

Description

Conceptually, the "input" to npm install is a package.json, while its @@ -214,4 +214,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/configuring-npm/shrinkwrap-json/index.html b/deps/npm/docs/public/configuring-npm/shrinkwrap-json/index.html index d0c46b7cb9c56b..1eb28bd824fa1e 100644 --- a/deps/npm/docs/public/configuring-npm/shrinkwrap-json/index.html +++ b/deps/npm/docs/public/configuring-npm/shrinkwrap-json/index.html @@ -74,7 +74,7 @@ } } }) -

npm shrinkwrap.json

+

npm shrinkwrap.json

A publishable lockfile

Description

npm-shrinkwrap.json is a file created by npm shrinkwrap. It is identical to @@ -102,4 +102,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/index.html b/deps/npm/docs/public/index.html index 9f8fbd156f541a..da5b9e791b1708 100644 --- a/deps/npm/docs/public/index.html +++ b/deps/npm/docs/public/index.html @@ -128,4 +128,4 @@ } } }) -
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!

The current stable version of npm is available on GitHub.

To upgrade, run: npm install npm@latest -g

\ No newline at end of file +
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!
npm cli _
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!

The current stable version of npm is available on GitHub.

To upgrade, run: npm install npm@latest -g

\ No newline at end of file diff --git a/deps/npm/docs/public/static/d/2215187023.json b/deps/npm/docs/public/static/d/2215187023.json index c26e85bd6966e2..328c36542ed0de 100644 --- a/deps/npm/docs/public/static/d/2215187023.json +++ b/deps/npm/docs/public/static/d/2215187023.json @@ -1 +1 @@ -{"data":{"allMarkdownRemark":{"nodes":[{"fields":{"slug":"/using-npm/semver"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/cli-commands/npm-adduser"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/cli-commands/npm-dist-tag"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/cli-commands/npm-explore"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/using-npm/config"},"frontmatter":{"description":"More than you probably want to know about npm configuration","section":"using-npm","title":"config"}},{"fields":{"slug":"/using-npm/developers"},"frontmatter":{"description":"Developer Guide","section":"using-npm","title":"developers"}},{"fields":{"slug":"/using-npm/disputes"},"frontmatter":{"description":"Handling Module Name Disputes","section":"using-npm","title":"disputes"}},{"fields":{"slug":"/configuring-npm/folders"},"frontmatter":{"description":"Folder Structures Used by npm","section":"configuring-npm","title":"folders"}},{"fields":{"slug":"/configuring-npm/install"},"frontmatter":{"description":"Download and install node and npm","section":"configuring-npm","title":"install"}},{"fields":{"slug":"/cli-commands/npm"},"frontmatter":{"description":"javascript package manager","section":"cli-commands","title":"npm"}},{"fields":{"slug":"/cli-commands/npm-access"},"frontmatter":{"description":"Set access level on published packages","section":"cli-commands","title":"npm-access"}},{"fields":{"slug":"/cli-commands/npm-audit"},"frontmatter":{"description":"Run a security audit","section":"cli-commands","title":"npm-audit"}},{"fields":{"slug":"/cli-commands/npm-bin"},"frontmatter":{"description":"Display npm bin folder","section":"cli-commands","title":"npm-bin"}},{"fields":{"slug":"/cli-commands/npm-bugs"},"frontmatter":{"description":"Bugs for a package in a web browser maybe","section":"cli-commands","title":"npm-bugs"}},{"fields":{"slug":"/cli-commands/npm-build"},"frontmatter":{"description":"Build a package","section":"cli-commands","title":"npm-build"}},{"fields":{"slug":"/cli-commands/npm-bundle"},"frontmatter":{"description":"REMOVED","section":"cli-commands","title":"npm-bundle"}},{"fields":{"slug":"/cli-commands/npm-cache"},"frontmatter":{"description":"Manipulates packages cache","section":"cli-commands","title":"npm-cache"}},{"fields":{"slug":"/cli-commands/npm-ci"},"frontmatter":{"description":"Install a project with a clean slate","section":"cli-commands","title":"npm-ci"}},{"fields":{"slug":"/cli-commands/npm-completion"},"frontmatter":{"description":"Tab Completion for npm","section":"cli-commands","title":"npm-completion"}},{"fields":{"slug":"/cli-commands/npm-config"},"frontmatter":{"description":"Manage the npm configuration files","section":"cli-commands","title":"npm-config"}},{"fields":{"slug":"/cli-commands/npm-dedupe"},"frontmatter":{"description":"Reduce duplication","section":"cli-commands","title":"npm-dedupe"}},{"fields":{"slug":"/cli-commands/npm-deprecate"},"frontmatter":{"description":"Deprecate a version of a package","section":"cli-commands","title":"npm-deprecate"}},{"fields":{"slug":"/cli-commands/npm-docs"},"frontmatter":{"description":"Docs for a package in a web browser maybe","section":"cli-commands","title":"npm-docs"}},{"fields":{"slug":"/cli-commands/npm-doctor"},"frontmatter":{"description":"Check your environments","section":"cli-commands","title":"npm-doctor"}},{"fields":{"slug":"/cli-commands/npm-edit"},"frontmatter":{"description":"Edit an installed package","section":"cli-commands","title":"npm-edit"}},{"fields":{"slug":"/cli-commands/npm-fund"},"frontmatter":{"description":"Retrieve funding information","section":"cli-commands","title":"npm-fund"}},{"fields":{"slug":"/cli-commands/npm-help"},"frontmatter":{"description":"Get help on npm","section":"cli-commands","title":"npm-help"}},{"fields":{"slug":"/cli-commands/npm-help-search"},"frontmatter":{"description":"Search npm help documentation","section":"cli-commands","title":"npm-help-search"}},{"fields":{"slug":"/cli-commands/npm-hook"},"frontmatter":{"description":"Manage registry hooks","section":"cli-commands","title":"npm-hook"}},{"fields":{"slug":"/cli-commands/npm-init"},"frontmatter":{"description":"create a package.json file","section":"cli-commands","title":"npm-init"}},{"fields":{"slug":"/cli-commands/npm-install"},"frontmatter":{"description":"Install a package","section":"cli-commands","title":"npm-install"}},{"fields":{"slug":"/cli-commands/npm-install-ci-test"},"frontmatter":{"description":"Install a project with a clean slate and run tests","section":"cli-commands","title":"npm-install-ci-test"}},{"fields":{"slug":"/cli-commands/npm-install-test"},"frontmatter":{"description":"Install package(s) and run tests","section":"cli-commands","title":"npm-install-test"}},{"fields":{"slug":"/cli-commands/npm-link"},"frontmatter":{"description":"Symlink a package folder","section":"cli-commands","title":"npm-link"}},{"fields":{"slug":"/cli-commands/npm-logout"},"frontmatter":{"description":"Log out of the registry","section":"cli-commands","title":"npm-logout"}},{"fields":{"slug":"/cli-commands/npm-ls"},"frontmatter":{"description":"List installed packages","section":"cli-commands","title":"npm-ls"}},{"fields":{"slug":"/cli-commands/npm-org"},"frontmatter":{"description":"Manage orgs","section":"cli-commands","title":"npm-org"}},{"fields":{"slug":"/cli-commands/npm-outdated"},"frontmatter":{"description":"Check for outdated packages","section":"cli-commands","title":"npm-outdated"}},{"fields":{"slug":"/cli-commands/npm-owner"},"frontmatter":{"description":"Manage package owners","section":"cli-commands","title":"npm-owner"}},{"fields":{"slug":"/cli-commands/npm-pack"},"frontmatter":{"description":"Create a tarball from a package","section":"cli-commands","title":"npm-pack"}},{"fields":{"slug":"/cli-commands/npm-ping"},"frontmatter":{"description":"Ping npm registry","section":"cli-commands","title":"npm-ping"}},{"fields":{"slug":"/cli-commands/npm-prefix"},"frontmatter":{"description":"Display prefix","section":"cli-commands","title":"npm-prefix"}},{"fields":{"slug":"/cli-commands/npm-profile"},"frontmatter":{"description":"Change settings on your registry profile","section":"cli-commands","title":"npm-profile"}},{"fields":{"slug":"/cli-commands/npm-prune"},"frontmatter":{"description":"Remove extraneous packages","section":"cli-commands","title":"npm-prune"}},{"fields":{"slug":"/cli-commands/npm-publish"},"frontmatter":{"description":"Publish a package","section":"cli-commands","title":"npm-publish"}},{"fields":{"slug":"/cli-commands/npm-rebuild"},"frontmatter":{"description":"Rebuild a package","section":"cli-commands","title":"npm-rebuild"}},{"fields":{"slug":"/cli-commands/npm-repo"},"frontmatter":{"description":"Open package repository page in the browser","section":"cli-commands","title":"npm-repo"}},{"fields":{"slug":"/cli-commands/npm-restart"},"frontmatter":{"description":"Restart a package","section":"cli-commands","title":"npm-restart"}},{"fields":{"slug":"/cli-commands/npm-root"},"frontmatter":{"description":"Display npm root","section":"cli-commands","title":"npm-root"}},{"fields":{"slug":"/cli-commands/npm-run-script"},"frontmatter":{"description":"Run arbitrary package scripts","section":"cli-commands","title":"npm-run-script"}},{"fields":{"slug":"/cli-commands/npm-search"},"frontmatter":{"description":"Search for packages","section":"cli-commands","title":"npm-search"}},{"fields":{"slug":"/cli-commands/npm-shrinkwrap"},"frontmatter":{"description":"Lock down dependency versions for publication","section":"cli-commands","title":"npm-shrinkwrap"}},{"fields":{"slug":"/cli-commands/npm-star"},"frontmatter":{"description":"Mark your favorite packages","section":"cli-commands","title":"npm-star"}},{"fields":{"slug":"/cli-commands/npm-stars"},"frontmatter":{"description":"View packages marked as favorites","section":"cli-commands","title":"npm-stars"}},{"fields":{"slug":"/cli-commands/npm-start"},"frontmatter":{"description":"Start a package","section":"cli-commands","title":"npm-start"}},{"fields":{"slug":"/cli-commands/npm-stop"},"frontmatter":{"description":"Stop a package","section":"cli-commands","title":"npm-stop"}},{"fields":{"slug":"/cli-commands/npm-team"},"frontmatter":{"description":"Manage organization teams and team memberships","section":"cli-commands","title":"npm-team"}},{"fields":{"slug":"/cli-commands/npm-test"},"frontmatter":{"description":"Test a package","section":"cli-commands","title":"npm-test"}},{"fields":{"slug":"/cli-commands/npm-token"},"frontmatter":{"description":"Manage your authentication tokens","section":"cli-commands","title":"npm-token"}},{"fields":{"slug":"/cli-commands/npm-uninstall"},"frontmatter":{"description":"Remove a package","section":"cli-commands","title":"npm-uninstall"}},{"fields":{"slug":"/cli-commands/npm-unpublish"},"frontmatter":{"description":"Remove a package from the registry","section":"cli-commands","title":"npm-unpublish"}},{"fields":{"slug":"/cli-commands/npm-update"},"frontmatter":{"description":"Update a package","section":"cli-commands","title":"npm-update"}},{"fields":{"slug":"/cli-commands/npm-version"},"frontmatter":{"description":"Bump a package version","section":"cli-commands","title":"npm-version"}},{"fields":{"slug":"/cli-commands/npm-view"},"frontmatter":{"description":"View registry info","section":"cli-commands","title":"npm-view"}},{"fields":{"slug":"/cli-commands/npm-whoami"},"frontmatter":{"description":"Display npm username","section":"cli-commands","title":"npm-whoami"}},{"fields":{"slug":"/configuring-npm/npmrc"},"frontmatter":{"description":"The npm config files","section":"configuring-npm","title":"npmrc"}},{"fields":{"slug":"/using-npm/orgs"},"frontmatter":{"description":"Working with Teams & Orgs","section":"using-npm","title":"orgs"}},{"fields":{"slug":"/configuring-npm/package-lock-json"},"frontmatter":{"description":"A manifestation of the manifest","section":"configuring-npm","title":"package-lock.json"}},{"fields":{"slug":"/configuring-npm/package-locks"},"frontmatter":{"description":"An explanation of npm lockfiles","section":"configuring-npm","title":"package-locks"}},{"fields":{"slug":"/configuring-npm/package-json"},"frontmatter":{"description":"Specifics of npm's package.json handling","section":"configuring-npm","title":"package.json"}},{"fields":{"slug":"/using-npm/registry"},"frontmatter":{"description":"The JavaScript Package Registry","section":"using-npm","title":"registry"}},{"fields":{"slug":"/using-npm/removal"},"frontmatter":{"description":"Cleaning the Slate","section":"using-npm","title":"removal"}},{"fields":{"slug":"/using-npm/scope"},"frontmatter":{"description":"Scoped packages","section":"using-npm","title":"scope"}},{"fields":{"slug":"/using-npm/scripts"},"frontmatter":{"description":"How npm handles the \"scripts\" field","section":"using-npm","title":"scripts"}},{"fields":{"slug":"/configuring-npm/shrinkwrap-json"},"frontmatter":{"description":"A publishable lockfile","section":"configuring-npm","title":"shrinkwrap.json"}}]}}} \ No newline at end of file +{"data":{"allMarkdownRemark":{"nodes":[{"fields":{"slug":"/cli-commands/npm-adduser"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/cli-commands/npm-dist-tag"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/cli-commands/npm-explore"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/using-npm/semver"},"frontmatter":{"description":null,"section":null,"title":""}},{"fields":{"slug":"/using-npm/config"},"frontmatter":{"description":"More than you probably want to know about npm configuration","section":"using-npm","title":"config"}},{"fields":{"slug":"/using-npm/developers"},"frontmatter":{"description":"Developer Guide","section":"using-npm","title":"developers"}},{"fields":{"slug":"/using-npm/disputes"},"frontmatter":{"description":"Handling Module Name Disputes","section":"using-npm","title":"disputes"}},{"fields":{"slug":"/configuring-npm/folders"},"frontmatter":{"description":"Folder Structures Used by npm","section":"configuring-npm","title":"folders"}},{"fields":{"slug":"/configuring-npm/install"},"frontmatter":{"description":"Download and install node and npm","section":"configuring-npm","title":"install"}},{"fields":{"slug":"/cli-commands/npm"},"frontmatter":{"description":"javascript package manager","section":"cli-commands","title":"npm"}},{"fields":{"slug":"/cli-commands/npm-access"},"frontmatter":{"description":"Set access level on published packages","section":"cli-commands","title":"npm-access"}},{"fields":{"slug":"/cli-commands/npm-audit"},"frontmatter":{"description":"Run a security audit","section":"cli-commands","title":"npm-audit"}},{"fields":{"slug":"/cli-commands/npm-bin"},"frontmatter":{"description":"Display npm bin folder","section":"cli-commands","title":"npm-bin"}},{"fields":{"slug":"/cli-commands/npm-bugs"},"frontmatter":{"description":"Bugs for a package in a web browser maybe","section":"cli-commands","title":"npm-bugs"}},{"fields":{"slug":"/cli-commands/npm-build"},"frontmatter":{"description":"Build a package","section":"cli-commands","title":"npm-build"}},{"fields":{"slug":"/cli-commands/npm-bundle"},"frontmatter":{"description":"REMOVED","section":"cli-commands","title":"npm-bundle"}},{"fields":{"slug":"/cli-commands/npm-cache"},"frontmatter":{"description":"Manipulates packages cache","section":"cli-commands","title":"npm-cache"}},{"fields":{"slug":"/cli-commands/npm-ci"},"frontmatter":{"description":"Install a project with a clean slate","section":"cli-commands","title":"npm-ci"}},{"fields":{"slug":"/cli-commands/npm-completion"},"frontmatter":{"description":"Tab Completion for npm","section":"cli-commands","title":"npm-completion"}},{"fields":{"slug":"/cli-commands/npm-config"},"frontmatter":{"description":"Manage the npm configuration files","section":"cli-commands","title":"npm-config"}},{"fields":{"slug":"/cli-commands/npm-dedupe"},"frontmatter":{"description":"Reduce duplication","section":"cli-commands","title":"npm-dedupe"}},{"fields":{"slug":"/cli-commands/npm-deprecate"},"frontmatter":{"description":"Deprecate a version of a package","section":"cli-commands","title":"npm-deprecate"}},{"fields":{"slug":"/cli-commands/npm-docs"},"frontmatter":{"description":"Docs for a package in a web browser maybe","section":"cli-commands","title":"npm-docs"}},{"fields":{"slug":"/cli-commands/npm-doctor"},"frontmatter":{"description":"Check your environments","section":"cli-commands","title":"npm-doctor"}},{"fields":{"slug":"/cli-commands/npm-edit"},"frontmatter":{"description":"Edit an installed package","section":"cli-commands","title":"npm-edit"}},{"fields":{"slug":"/cli-commands/npm-fund"},"frontmatter":{"description":"Retrieve funding information","section":"cli-commands","title":"npm-fund"}},{"fields":{"slug":"/cli-commands/npm-help"},"frontmatter":{"description":"Get help on npm","section":"cli-commands","title":"npm-help"}},{"fields":{"slug":"/cli-commands/npm-help-search"},"frontmatter":{"description":"Search npm help documentation","section":"cli-commands","title":"npm-help-search"}},{"fields":{"slug":"/cli-commands/npm-hook"},"frontmatter":{"description":"Manage registry hooks","section":"cli-commands","title":"npm-hook"}},{"fields":{"slug":"/cli-commands/npm-init"},"frontmatter":{"description":"create a package.json file","section":"cli-commands","title":"npm-init"}},{"fields":{"slug":"/cli-commands/npm-install"},"frontmatter":{"description":"Install a package","section":"cli-commands","title":"npm-install"}},{"fields":{"slug":"/cli-commands/npm-install-ci-test"},"frontmatter":{"description":"Install a project with a clean slate and run tests","section":"cli-commands","title":"npm-install-ci-test"}},{"fields":{"slug":"/cli-commands/npm-install-test"},"frontmatter":{"description":"Install package(s) and run tests","section":"cli-commands","title":"npm-install-test"}},{"fields":{"slug":"/cli-commands/npm-link"},"frontmatter":{"description":"Symlink a package folder","section":"cli-commands","title":"npm-link"}},{"fields":{"slug":"/cli-commands/npm-logout"},"frontmatter":{"description":"Log out of the registry","section":"cli-commands","title":"npm-logout"}},{"fields":{"slug":"/cli-commands/npm-ls"},"frontmatter":{"description":"List installed packages","section":"cli-commands","title":"npm-ls"}},{"fields":{"slug":"/cli-commands/npm-org"},"frontmatter":{"description":"Manage orgs","section":"cli-commands","title":"npm-org"}},{"fields":{"slug":"/cli-commands/npm-outdated"},"frontmatter":{"description":"Check for outdated packages","section":"cli-commands","title":"npm-outdated"}},{"fields":{"slug":"/cli-commands/npm-owner"},"frontmatter":{"description":"Manage package owners","section":"cli-commands","title":"npm-owner"}},{"fields":{"slug":"/cli-commands/npm-pack"},"frontmatter":{"description":"Create a tarball from a package","section":"cli-commands","title":"npm-pack"}},{"fields":{"slug":"/cli-commands/npm-ping"},"frontmatter":{"description":"Ping npm registry","section":"cli-commands","title":"npm-ping"}},{"fields":{"slug":"/cli-commands/npm-prefix"},"frontmatter":{"description":"Display prefix","section":"cli-commands","title":"npm-prefix"}},{"fields":{"slug":"/cli-commands/npm-profile"},"frontmatter":{"description":"Change settings on your registry profile","section":"cli-commands","title":"npm-profile"}},{"fields":{"slug":"/cli-commands/npm-prune"},"frontmatter":{"description":"Remove extraneous packages","section":"cli-commands","title":"npm-prune"}},{"fields":{"slug":"/cli-commands/npm-publish"},"frontmatter":{"description":"Publish a package","section":"cli-commands","title":"npm-publish"}},{"fields":{"slug":"/cli-commands/npm-rebuild"},"frontmatter":{"description":"Rebuild a package","section":"cli-commands","title":"npm-rebuild"}},{"fields":{"slug":"/cli-commands/npm-repo"},"frontmatter":{"description":"Open package repository page in the browser","section":"cli-commands","title":"npm-repo"}},{"fields":{"slug":"/cli-commands/npm-restart"},"frontmatter":{"description":"Restart a package","section":"cli-commands","title":"npm-restart"}},{"fields":{"slug":"/cli-commands/npm-root"},"frontmatter":{"description":"Display npm root","section":"cli-commands","title":"npm-root"}},{"fields":{"slug":"/cli-commands/npm-run-script"},"frontmatter":{"description":"Run arbitrary package scripts","section":"cli-commands","title":"npm-run-script"}},{"fields":{"slug":"/cli-commands/npm-search"},"frontmatter":{"description":"Search for packages","section":"cli-commands","title":"npm-search"}},{"fields":{"slug":"/cli-commands/npm-shrinkwrap"},"frontmatter":{"description":"Lock down dependency versions for publication","section":"cli-commands","title":"npm-shrinkwrap"}},{"fields":{"slug":"/cli-commands/npm-star"},"frontmatter":{"description":"Mark your favorite packages","section":"cli-commands","title":"npm-star"}},{"fields":{"slug":"/cli-commands/npm-stars"},"frontmatter":{"description":"View packages marked as favorites","section":"cli-commands","title":"npm-stars"}},{"fields":{"slug":"/cli-commands/npm-start"},"frontmatter":{"description":"Start a package","section":"cli-commands","title":"npm-start"}},{"fields":{"slug":"/cli-commands/npm-stop"},"frontmatter":{"description":"Stop a package","section":"cli-commands","title":"npm-stop"}},{"fields":{"slug":"/cli-commands/npm-team"},"frontmatter":{"description":"Manage organization teams and team memberships","section":"cli-commands","title":"npm-team"}},{"fields":{"slug":"/cli-commands/npm-test"},"frontmatter":{"description":"Test a package","section":"cli-commands","title":"npm-test"}},{"fields":{"slug":"/cli-commands/npm-token"},"frontmatter":{"description":"Manage your authentication tokens","section":"cli-commands","title":"npm-token"}},{"fields":{"slug":"/cli-commands/npm-uninstall"},"frontmatter":{"description":"Remove a package","section":"cli-commands","title":"npm-uninstall"}},{"fields":{"slug":"/cli-commands/npm-unpublish"},"frontmatter":{"description":"Remove a package from the registry","section":"cli-commands","title":"npm-unpublish"}},{"fields":{"slug":"/cli-commands/npm-update"},"frontmatter":{"description":"Update a package","section":"cli-commands","title":"npm-update"}},{"fields":{"slug":"/cli-commands/npm-version"},"frontmatter":{"description":"Bump a package version","section":"cli-commands","title":"npm-version"}},{"fields":{"slug":"/cli-commands/npm-view"},"frontmatter":{"description":"View registry info","section":"cli-commands","title":"npm-view"}},{"fields":{"slug":"/cli-commands/npm-whoami"},"frontmatter":{"description":"Display npm username","section":"cli-commands","title":"npm-whoami"}},{"fields":{"slug":"/configuring-npm/npmrc"},"frontmatter":{"description":"The npm config files","section":"configuring-npm","title":"npmrc"}},{"fields":{"slug":"/using-npm/orgs"},"frontmatter":{"description":"Working with Teams & Orgs","section":"using-npm","title":"orgs"}},{"fields":{"slug":"/configuring-npm/package-lock-json"},"frontmatter":{"description":"A manifestation of the manifest","section":"configuring-npm","title":"package-lock.json"}},{"fields":{"slug":"/configuring-npm/package-locks"},"frontmatter":{"description":"An explanation of npm lockfiles","section":"configuring-npm","title":"package-locks"}},{"fields":{"slug":"/configuring-npm/package-json"},"frontmatter":{"description":"Specifics of npm's package.json handling","section":"configuring-npm","title":"package.json"}},{"fields":{"slug":"/using-npm/registry"},"frontmatter":{"description":"The JavaScript Package Registry","section":"using-npm","title":"registry"}},{"fields":{"slug":"/using-npm/removal"},"frontmatter":{"description":"Cleaning the Slate","section":"using-npm","title":"removal"}},{"fields":{"slug":"/using-npm/scope"},"frontmatter":{"description":"Scoped packages","section":"using-npm","title":"scope"}},{"fields":{"slug":"/using-npm/scripts"},"frontmatter":{"description":"How npm handles the \"scripts\" field","section":"using-npm","title":"scripts"}},{"fields":{"slug":"/configuring-npm/shrinkwrap-json"},"frontmatter":{"description":"A publishable lockfile","section":"configuring-npm","title":"shrinkwrap.json"}}]}}} \ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/config/index.html b/deps/npm/docs/public/using-npm/config/index.html index da37f443de6c15..f84138225e4935 100644 --- a/deps/npm/docs/public/using-npm/config/index.html +++ b/deps/npm/docs/public/using-npm/config/index.html @@ -74,7 +74,7 @@ } } }) -

config

+

config

More than you probably want to know about npm configuration

Description

npm gets its configuration values from the following sources, sorted by priority:

@@ -1161,4 +1161,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/developers/index.html b/deps/npm/docs/public/using-npm/developers/index.html index ca9530cebbbd8b..5b091a729ac996 100644 --- a/deps/npm/docs/public/using-npm/developers/index.html +++ b/deps/npm/docs/public/using-npm/developers/index.html @@ -74,7 +74,7 @@ } } }) -

developers

+

developers

Developer Guide

Description

So, you've decided to use npm to develop (and maybe publish/deploy) @@ -259,4 +259,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/disputes/index.html b/deps/npm/docs/public/using-npm/disputes/index.html index 42883c09df6bb8..8611bde28cae41 100644 --- a/deps/npm/docs/public/using-npm/disputes/index.html +++ b/deps/npm/docs/public/using-npm/disputes/index.html @@ -74,7 +74,7 @@ } } }) -

disputes

+

disputes

Handling Module Name Disputes

This document describes the steps that you should take to resolve module name disputes with other npm publishers. It also describes special steps you should @@ -192,4 +192,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/orgs/index.html b/deps/npm/docs/public/using-npm/orgs/index.html index d85903790728bb..efd4f3c09848de 100644 --- a/deps/npm/docs/public/using-npm/orgs/index.html +++ b/deps/npm/docs/public/using-npm/orgs/index.html @@ -74,7 +74,7 @@ } } }) -

orgs

+

orgs

Working with Teams & Orgs

Description

There are three levels of org users:

@@ -144,4 +144,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/registry/index.html b/deps/npm/docs/public/using-npm/registry/index.html index b0af7a7df1146d..4fa0e05d14c7de 100644 --- a/deps/npm/docs/public/using-npm/registry/index.html +++ b/deps/npm/docs/public/using-npm/registry/index.html @@ -74,7 +74,7 @@ } } }) -

registry

+

registry

The JavaScript Package Registry

Description

To resolve packages by name and version, npm talks to a registry website @@ -156,4 +156,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/removal/index.html b/deps/npm/docs/public/using-npm/removal/index.html index fc0030f09d7ff9..2c73f0c54d03c2 100644 --- a/deps/npm/docs/public/using-npm/removal/index.html +++ b/deps/npm/docs/public/using-npm/removal/index.html @@ -74,7 +74,7 @@ } } }) -

removal

+

removal

Cleaning the Slate

Synopsis

So sad to see you go.

@@ -116,4 +116,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/scope/index.html b/deps/npm/docs/public/using-npm/scope/index.html index 064d443c233c8c..8c7b6d75a3f49b 100644 --- a/deps/npm/docs/public/using-npm/scope/index.html +++ b/deps/npm/docs/public/using-npm/scope/index.html @@ -74,7 +74,7 @@ } } }) -

scope

+

scope

Scoped packages

Description

All npm packages have a name. Some package names also have a scope. A scope @@ -159,4 +159,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/scripts/index.html b/deps/npm/docs/public/using-npm/scripts/index.html index 662a6a12e61b1a..954cc85258cfa4 100644 --- a/deps/npm/docs/public/using-npm/scripts/index.html +++ b/deps/npm/docs/public/using-npm/scripts/index.html @@ -74,7 +74,7 @@ } } }) -

scripts

+

scripts

How npm handles the "scripts" field

Description

npm supports the "scripts" property of the package.json file, for the @@ -303,4 +303,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/docs/public/using-npm/semver/index.html b/deps/npm/docs/public/using-npm/semver/index.html index df9862ea21c00e..da4134247cdfa2 100644 --- a/deps/npm/docs/public/using-npm/semver/index.html +++ b/deps/npm/docs/public/using-npm/semver/index.html @@ -74,7 +74,7 @@ } } }) -

semver(7) -- The semantic versioner for npm

+

semver(7) -- The semantic versioner for npm

Install

npm install --save semver

Usage

@@ -435,4 +435,4 @@

\ No newline at end of file +
\ No newline at end of file diff --git a/deps/npm/lib/npm.js b/deps/npm/lib/npm.js index 35850078f834d1..74ef6ad2c6e748 100644 --- a/deps/npm/lib/npm.js +++ b/deps/npm/lib/npm.js @@ -283,22 +283,28 @@ ua = ua.replace(/\{arch\}/gi, process.arch) // continuous integration platforms - const ci = process.env.GERRIT_PROJECT ? 'ci/gerrit' - : process.env.GITLAB_CI ? 'ci/gitlab' - : process.env.CIRCLECI ? 'ci/circle-ci' - : process.env.SEMAPHORE ? 'ci/semaphore' - : process.env.DRONE ? 'ci/drone' - : process.env.GITHUB_ACTION ? 'ci/github-actions' - : process.env.TDDIUM ? 'ci/tddium' - : process.env.JENKINS_URL ? 'ci/jenkins' - : process.env['bamboo.buildKey'] ? 'ci/bamboo' - : process.env.GO_PIPELINE_NAME ? 'ci/gocd' - // codeship and a few others - : process.env.CI_NAME ? `ci/${process.env.CI_NAME}` - // test travis last, since many of these mimic it - : process.env.TRAVIS ? 'ci/travis-ci' - : process.env.CI === 'true' || process.env.CI === '1' ? 'ci/custom' - : '' + const ciName = process.env.GERRIT_PROJECT ? 'gerrit' + : process.env.GITLAB_CI ? 'gitlab' + : process.env.APPVEYOR ? 'appveyor' + : process.env.CIRCLECI ? 'circle-ci' + : process.env.SEMAPHORE ? 'semaphore' + : process.env.DRONE ? 'drone' + : process.env.GITHUB_ACTION ? 'github-actions' + : process.env.TDDIUM ? 'tddium' + : process.env.JENKINS_URL ? 'jenkins' + : process.env['bamboo.buildKey'] ? 'bamboo' + : process.env.GO_PIPELINE_NAME ? 'gocd' + // codeship and a few others + : process.env.CI_NAME ? process.env.CI_NAME + // test travis after the others, since several CI systems mimic it + : process.env.TRAVIS ? 'travis-ci' + // aws CodeBuild/CodePipeline + : process.env.CODEBUILD_SRC_DIR ? 'aws-codebuild' + : process.env.CI === 'true' || process.env.CI === '1' ? 'custom' + // Google Cloud Build - it sets almost nothing + : process.env.BUILDER_OUTPUT ? 'builder' + : false + const ci = ciName ? `ci/${ciName}` : '' ua = ua.replace(/\{ci\}/gi, ci) config.set('user-agent', ua.trim()) diff --git a/deps/npm/lib/utils/unsupported.js b/deps/npm/lib/utils/unsupported.js index 71a304030e2424..c34e17374e0405 100644 --- a/deps/npm/lib/utils/unsupported.js +++ b/deps/npm/lib/utils/unsupported.js @@ -7,7 +7,8 @@ var supportedNode = [ {ver: '10', min: '10.0.0'}, {ver: '11', min: '11.0.0'}, {ver: '12', min: '12.0.0'}, - {ver: '13', min: '13.0.0'} + {ver: '13', min: '13.0.0'}, + {ver: '14', min: '14.0.0'} ] var knownBroken = '<6.2.0 || 9.0 - 9.2' diff --git a/deps/npm/man/man1/npm-README.1 b/deps/npm/man/man1/npm-README.1 index 79ab9d3fd6a79e..a068aae1ffc1be 100644 --- a/deps/npm/man/man1/npm-README.1 +++ b/deps/npm/man/man1/npm-README.1 @@ -158,10 +158,6 @@ https://npm\.community/c/bugs .P Be sure to include \fIall\fR of the output from the npm command that didn't work as expected\. The \fBnpm\-debug\.log\fP file is also helpful to provide\. -.P -You can also find npm people in \fB#npm\fP on https://package\.community/ or -on Twitter \fIhttps://twitter\.com/npm_support\fR\|\. Whoever responds will no -doubt tell you to put the output in a gist or email\. .SH SEE ALSO .RS 0 .IP \(bu 2 diff --git a/deps/npm/man/man1/npm-adduser.1 b/deps/npm/man/man1/npm-adduser.1 index c194a3e3080d3a..05166e52ec91df 100644 --- a/deps/npm/man/man1/npm-adduser.1 +++ b/deps/npm/man/man1/npm-adduser.1 @@ -1,3 +1,8 @@ +.HR +.P +section: cli\-commands +title: npm\-adduser +.SH description: Set access level on published packages .TH "NPM\-ADDUSER" "1" "January 2020" "" "" .SH "NAME" \fBnpm-adduser\fR \- Add a registry user account diff --git a/deps/npm/man/man1/npm-dist-tag.1 b/deps/npm/man/man1/npm-dist-tag.1 index 9bbeb4bb39d04f..354438674bdfa0 100644 --- a/deps/npm/man/man1/npm-dist-tag.1 +++ b/deps/npm/man/man1/npm-dist-tag.1 @@ -1,3 +1,8 @@ +.HR +.P +section: cli\-commands +title: npm\-dist\-tag +.SH description: Modify package distribution tags .TH "NPM\-DIST\-TAG" "1" "January 2020" "" "" .SH "NAME" \fBnpm-dist-tag\fR \- Modify package distribution tags diff --git a/deps/npm/man/man1/npm-explore.1 b/deps/npm/man/man1/npm-explore.1 index 4a9a5bd32b993a..81597ca8809246 100644 --- a/deps/npm/man/man1/npm-explore.1 +++ b/deps/npm/man/man1/npm-explore.1 @@ -1,3 +1,8 @@ +.HR +.P +section: cli\-commands +title: npm\-explore +.SH description: Browse an installed package .TH "NPM\-EXPLORE" "1" "January 2020" "" "" .SH "NAME" \fBnpm-explore\fR \- Browse an installed package diff --git a/deps/npm/man/man1/npm-ls.1 b/deps/npm/man/man1/npm-ls.1 index 79f90f9089d342..78c2d9ee14cc57 100644 --- a/deps/npm/man/man1/npm-ls.1 +++ b/deps/npm/man/man1/npm-ls.1 @@ -22,7 +22,7 @@ For example, running \fBnpm ls promzard\fP in npm's source tree will show: .P .RS 2 .nf - npm@6\.13\.6 /path/to/npm + npm@6\.13\.7 /path/to/npm └─┬ init\-package\-json@0\.0\.4 └── promzard@0\.1\.5 .fi diff --git a/deps/npm/man/man1/npm-profile.1 b/deps/npm/man/man1/npm-profile.1 index d05b776e85e23b..45ec331f0bf935 100644 --- a/deps/npm/man/man1/npm-profile.1 +++ b/deps/npm/man/man1/npm-profile.1 @@ -1,6 +1,54 @@ +.TH "NPM\-PROFILE" "1" "January 2020" "" "" +.SH "NAME" +\fBnpm-profile\fR \- Change settings on your registry profile +.SS Synopsis .P -+ -``` +.RS 2 +.nf +npm profile get [\-\-json|\-\-parseable] [] +npm profile set [\-\-json|\-\-parseable] +npm profile set password +npm profile enable\-2fa [auth\-and\-writes|auth\-only] +npm profile disable\-2fa +.fi +.RE +.SS Description +.P +Change your profile information on the registry\. This not be available if +you're using a non\-npmjs registry\. +.RS 0 +.IP \(bu 2 +\fBnpm profile get []\fP: +Display all of the properties of your profile, or one or more specific +properties\. It looks like: + +.RE +.P +.RS 2 +.nf ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| name | example | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| email | me@example\.com (verified) | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| two factor auth | auth\-and\-writes | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| fullname | Example User | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| homepage | | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| freenode | | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| twitter | | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| github | | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| created | 2015\-02\-26T01:38:35\.892Z | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| updated | 2017\-10\-02T21:29:45\.922Z | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +.fi +.RE .RS 0 .IP \(bu 2 \fBnpm profile set \fP: diff --git a/deps/npm/man/man1/npm-token.1 b/deps/npm/man/man1/npm-token.1 index 04a0f5f82f2c6c..7fc5f2bffbf88f 100644 --- a/deps/npm/man/man1/npm-token.1 +++ b/deps/npm/man/man1/npm-token.1 @@ -1,6 +1,70 @@ +.TH "NPM\-TOKEN" "1" "January 2020" "" "" +.SH "NAME" +\fBnpm-token\fR \- Manage your authentication tokens +.SS Synopsis .P -+ -``` +.RS 2 +.nf + npm token list [\-\-json|\-\-parseable] + npm token create [\-\-read\-only] [\-\-cidr=1\.1\.1\.1/24,2\.2\.2\.2/16] + npm token revoke +.fi +.RE +.SS Description +.P +This lets you list, create and revoke authentication tokens\. +.RS 0 +.IP \(bu 2 +\fBnpm token list\fP: +Shows a table of all active authentication tokens\. You can request this as +JSON with \fB\-\-json\fP or tab\-separated values with \fB\-\-parseable\fP\|\. + +.RE +.P +.RS 2 +.nf ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| id | token | created | read\-only | CIDR whitelist | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| 7f3134 | 1fa9ba… | 2017\-10\-02 | yes | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| c03241 | af7aef… | 2017\-10\-02 | no | 192\.168\.0\.1/24 | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| e0cf92 | 3a436a… | 2017\-10\-02 | no | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| 63eb9d | 74ef35… | 2017\-09\-28 | no | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| 2daaa8 | cbad5f… | 2017\-09\-26 | no | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| 68c2fe | 127e51… | 2017\-09\-23 | no | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| 6334e1 | 1dadd1… | 2017\-09\-23 | no | | ++\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +.fi +.RE +.RS 0 +.IP \(bu 2 +\fBnpm token create [\-\-read\-only] [\-\-cidr=]\fP: +Create a new authentication token\. It can be \fB\-\-read\-only\fP or accept a list of +CIDR \fIhttps://en\.wikipedia\.org/wiki/Classless_Inter\-Domain_Routing\fR ranges to +limit use of this token to\. This will prompt you for your password, and, if you have +two\-factor authentication enabled, an otp\. + +.RE +.P +.RS 2 +.nf ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| token | a73c9572\-f1b9\-8983\-983d\-ba3ac3cc913d | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| cidr_whitelist | | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| readonly | false | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| created | 2017\-10\-02T07:52:24\.838Z | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +.fi +.RE .RS 0 .IP \(bu 2 \fBnpm token revoke \fP: diff --git a/deps/npm/man/man1/npm.1 b/deps/npm/man/man1/npm.1 index 0e230590366a26..7674110bf36d71 100644 --- a/deps/npm/man/man1/npm.1 +++ b/deps/npm/man/man1/npm.1 @@ -10,7 +10,7 @@ npm [args] .RE .SS Version .P -6\.13\.6 +6\.13\.7 .SS Description .P npm is the package manager for the Node JavaScript platform\. It puts diff --git a/deps/npm/man/man1/npx.1 b/deps/npm/man/man1/npx.1 index cd44dda044ad62..e5fc2d48e6fa5d 100644 --- a/deps/npm/man/man1/npx.1 +++ b/deps/npm/man/man1/npx.1 @@ -1,4 +1,4 @@ -.TH "NPX" "1" "April 2018" "npx@10.1.1" "User Commands" +.TH "NPX" "1" "January 2020" "npx@10.2.1" "User Commands" .SH "NAME" \fBnpx\fR \- execute npm package binaries .SH SYNOPSIS @@ -158,7 +158,7 @@ Huge thanks to Kwyn Meagher \fIhttps://blog\.kwyn\.io\fR for generously donating Written by Kat Marchan \fIhttps://github\.com/zkat\fR\|\. .SH REPORTING BUGS .P -Please file any relevant issues on Github\. \fIhttps://github\.com/zkat/npx\fR +Please file any relevant issues on Github\. \fIhttps://github\.com/npm/npx\fR .SH LICENSE .P This work is released by its authors into the public domain under CC0\-1\.0\. See \fBLICENSE\.md\fP for details\. diff --git a/deps/npm/man/man5/folders.5 b/deps/npm/man/man5/folders.5 index a6d802775989a0..3148604e7f391b 100644 --- a/deps/npm/man/man5/folders.5 +++ b/deps/npm/man/man5/folders.5 @@ -1,6 +1,176 @@ +.TH "FOLDERS" "5" "January 2020" "" "" +.SH "NAME" +\fBfolders\fR \- Folder Structures Used by npm +.SS Description .P -[E] -``` +npm puts various things on your computer\. That's its job\. +.P +This document will tell you what it puts where\. +.SS tl;dr +.RS 0 +.IP \(bu 2 +Local install (default): puts stuff in \fB\|\./node_modules\fP of the current +package root\. +.IP \(bu 2 +Global install (with \fB\-g\fP): puts stuff in /usr/local or wherever node +is installed\. +.IP \(bu 2 +Install it \fBlocally\fR if you're going to \fBrequire()\fP it\. +.IP \(bu 2 +Install it \fBglobally\fR if you're going to run it on the command line\. +.IP \(bu 2 +If you need both, then install it in both places, or use \fBnpm link\fP\|\. + +.RE +.SS prefix Configuration +.P +The \fBprefix\fP config defaults to the location where node is installed\. +On most systems, this is \fB/usr/local\fP\|\. On Windows, it's \fB%AppData%\\npm\fP\|\. +On Unix systems, it's one level up, since node is typically installed at +\fB{prefix}/bin/node\fP rather than \fB{prefix}/node\.exe\fP\|\. +.P +When the \fBglobal\fP flag is set, npm installs things into this prefix\. +When it is not set, it uses the root of the current package, or the +current working directory if not in a package already\. +.SS Node Modules +.P +Packages are dropped into the \fBnode_modules\fP folder under the \fBprefix\fP\|\. +When installing locally, this means that you can +\fBrequire("packagename")\fP to load its main module, or +\fBrequire("packagename/lib/path/to/sub/module")\fP to load other modules\. +.P +Global installs on Unix systems go to \fB{prefix}/lib/node_modules\fP\|\. +Global installs on Windows go to \fB{prefix}/node_modules\fP (that is, no +\fBlib\fP folder\.) +.P +Scoped packages are installed the same way, except they are grouped together +in a sub\-folder of the relevant \fBnode_modules\fP folder with the name of that +scope prefix by the @ symbol, e\.g\. \fBnpm install @myorg/package\fP would place +the package in \fB{prefix}/node_modules/@myorg/package\fP\|\. See npm help \fBscope\fP for more details\. +.P +If you wish to \fBrequire()\fP a package, then install it locally\. +.SS Executables +.P +When in global mode, executables are linked into \fB{prefix}/bin\fP on Unix, +or directly into \fB{prefix}\fP on Windows\. +.P +When in local mode, executables are linked into +\fB\|\./node_modules/\.bin\fP so that they can be made available to scripts run +through npm\. (For example, so that a test runner will be in the path +when you run \fBnpm test\fP\|\.) +.SS Man Pages +.P +When in global mode, man pages are linked into \fB{prefix}/share/man\fP\|\. +.P +When in local mode, man pages are not installed\. +.P +Man pages are not installed on Windows systems\. +.SS Cache +.P +See npm help \fBcache\fP\|\. Cache files are stored in \fB~/\.npm\fP on Posix, or +\fB%AppData%/npm\-cache\fP on Windows\. +.P +This is controlled by the \fBcache\fP configuration param\. +.SS Temp Files +.P +Temporary files are stored by default in the folder specified by the +\fBtmp\fP config, which defaults to the TMPDIR, TMP, or TEMP environment +variables, or \fB/tmp\fP on Unix and \fBc:\\windows\\temp\fP on Windows\. +.P +Temp files are given a unique folder under this root for each run of the +program, and are deleted upon successful exit\. +.SS More Information +.P +When installing locally, npm first tries to find an appropriate +\fBprefix\fP folder\. This is so that \fBnpm install foo@1\.2\.3\fP will install +to the sensible root of your package, even if you happen to have \fBcd\fPed +into some other folder\. +.P +Starting at the $PWD, npm will walk up the folder tree checking for a +folder that contains either a \fBpackage\.json\fP file, or a \fBnode_modules\fP +folder\. If such a thing is found, then that is treated as the effective +"current directory" for the purpose of running npm commands\. (This +behavior is inspired by and similar to git's \.git\-folder seeking +logic when running git commands in a working dir\.) +.P +If no package root is found, then the current folder is used\. +.P +When you run \fBnpm install foo@1\.2\.3\fP, then the package is loaded into +the cache, and then unpacked into \fB\|\./node_modules/foo\fP\|\. Then, any of +foo's dependencies are similarly unpacked into +\fB\|\./node_modules/foo/node_modules/\.\.\.\fP\|\. +.P +Any bin files are symlinked to \fB\|\./node_modules/\.bin/\fP, so that they may +be found by npm scripts when necessary\. +.SS Global Installation +.P +If the \fBglobal\fP configuration is set to true, then npm will +install packages "globally"\. +.P +For global installation, packages are installed roughly the same way, +but using the folders described above\. +.SS Cycles, Conflicts, and Folder Parsimony +.P +Cycles are handled using the property of node's module system that it +walks up the directories looking for \fBnode_modules\fP folders\. So, at every +stage, if a package is already installed in an ancestor \fBnode_modules\fP +folder, then it is not installed at the current location\. +.P +Consider the case above, where \fBfoo \-> bar \-> baz\fP\|\. Imagine if, in +addition to that, baz depended on bar, so you'd have: +\fBfoo \-> bar \-> baz \-> bar \-> baz \.\.\.\fP\|\. However, since the folder +structure is: \fBfoo/node_modules/bar/node_modules/baz\fP, there's no need to +put another copy of bar into \fB\|\.\.\./baz/node_modules\fP, since when it calls +require("bar"), it will get the copy that is installed in +\fBfoo/node_modules/bar\fP\|\. +.P +This shortcut is only used if the exact same +version would be installed in multiple nested \fBnode_modules\fP folders\. It +is still possible to have \fBa/node_modules/b/node_modules/a\fP if the two +"a" packages are different versions\. However, without repeating the +exact same package multiple times, an infinite regress will always be +prevented\. +.P +Another optimization can be made by installing dependencies at the +highest level possible, below the localized "target" folder\. +.SS Example +.P +Consider this dependency graph: +.P +.RS 2 +.nf +foo ++\-\- blerg@1\.2\.5 ++\-\- bar@1\.2\.3 +| +\-\- blerg@1\.x (latest=1\.3\.7) +| +\-\- baz@2\.x +| | `\-\- quux@3\.x +| | `\-\- bar@1\.2\.3 (cycle) +| `\-\- asdf@* +`\-\- baz@1\.2\.3 + `\-\- quux@3\.x + `\-\- bar +.fi +.RE +.P +In this case, we might expect a folder structure like this: +.P +.RS 2 +.nf +foo ++\-\- node_modules + +\-\- blerg (1\.2\.5) <\-\-\-[A] + +\-\- bar (1\.2\.3) <\-\-\-[B] + | `\-\- node_modules + | +\-\- baz (2\.0\.2) <\-\-\-[C] + | | `\-\- node_modules + | | `\-\- quux (3\.2\.0) + | `\-\- asdf (2\.3\.4) + `\-\- baz (1\.2\.3) <\-\-\-[D] + `\-\- node_modules + `\-\- quux (3\.2\.0) <\-\-\-[E] +.fi +.RE .P Since foo depends directly on \fBbar@1\.2\.3\fP and \fBbaz@1\.2\.3\fP, those are installed in foo's \fBnode_modules\fP folder\. diff --git a/deps/npm/man/man5/package-json.5 b/deps/npm/man/man5/package-json.5 index 7be8049bd0caaf..7c82b4e95573ff 100644 --- a/deps/npm/man/man5/package-json.5 +++ b/deps/npm/man/man5/package-json.5 @@ -824,7 +824,8 @@ If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the \fBoptionalDependencies\fP object\. This is a map of package name to version or url, just like the \fBdependencies\fP object\. The difference is that build failures do not cause -installation to fail\. +installation to fail\. Running \fBnpm install \-\-no\-optional\fP will prevent these +dependencies from being installed\. .P It is still your program's responsibility to handle the lack of the dependency\. For example, something like this: diff --git a/deps/npm/man/man7/config.7 b/deps/npm/man/man7/config.7 index 617b5354c1db25..ad67a24a3bc43e 100644 --- a/deps/npm/man/man7/config.7 +++ b/deps/npm/man/man7/config.7 @@ -1,6 +1,846 @@ +.TH "CONFIG" "7" "January 2020" "" "" +.SH "NAME" +\fBconfig\fR \- More than you probably want to know about npm configuration +.SS Description .P -" -``` +npm gets its configuration values from the following sources, sorted by priority: +.SS Command Line Flags +.P +Putting \fB\-\-foo bar\fP on the command line sets the \fBfoo\fP configuration +parameter to \fB"bar"\fP\|\. A \fB\-\-\fP argument tells the cli parser to stop +reading flags\. Using \fB\-\-flag\fP without specifying any value will set +the value to \fBtrue\fP\|\. +.P +Example: \fB\-\-flag1 \-\-flag2\fP will set both configuration parameters +to \fBtrue\fP, while \fB\-\-flag1 \-\-flag2 bar\fP will set \fBflag1\fP to \fBtrue\fP, +and \fBflag2\fP to \fBbar\fP\|\. Finally, \fB\-\-flag1 \-\-flag2 \-\- bar\fP will set +both configuration parameters to \fBtrue\fP, and the \fBbar\fP is taken +as a command argument\. +.SS Environment Variables +.P +Any environment variables that start with \fBnpm_config_\fP will be +interpreted as a configuration parameter\. For example, putting +\fBnpm_config_foo=bar\fP in your environment will set the \fBfoo\fP +configuration parameter to \fBbar\fP\|\. Any environment configurations that +are not given a value will be given the value of \fBtrue\fP\|\. Config +values are case\-insensitive, so \fBNPM_CONFIG_FOO=bar\fP will work the +same\. However, please note that inside npm help \fBscripts\fP +npm will set its own environment variables and Node will prefer +those lowercase versions over any uppercase ones that you might set\. +For details see this issue \fIhttps://github\.com/npm/npm/issues/14528\fR\|\. +.P +Notice that you need to use underscores instead of dashes, so \fB\-\-allow\-same\-version\fP +would become \fBnpm_config_allow_same_version=true\fP\|\. +.SS npmrc Files +.P +The four relevant files are: +.RS 0 +.IP \(bu 2 +per\-project configuration file (\fB/path/to/my/project/\.npmrc\fP) +.IP \(bu 2 +per\-user configuration file (defaults to \fB$HOME/\.npmrc\fP; configurable via CLI +option \fB\-\-userconfig\fP or environment variable \fB$NPM_CONFIG_USERCONFIG\fP) +.IP \(bu 2 +global configuration file (defaults to \fB$PREFIX/etc/npmrc\fP; configurable via +CLI option \fB\-\-globalconfig\fP or environment variable \fB$NPM_CONFIG_GLOBALCONFIG\fP) +.IP \(bu 2 +npm's built\-in configuration file (\fB/path/to/npm/npmrc\fP) + +.RE +.P +See npm help npmrc for more details\. +.SS Default Configs +.P +Run \fBnpm config ls \-l\fP to see a set of configuration parameters that are +internal to npm, and are defaults if nothing else is specified\. +.SS Shorthands and Other CLI Niceties +.P +The following shorthands are parsed on the command\-line: +.RS 0 +.IP \(bu 2 +\fB\-v\fP: \fB\-\-version\fP +.IP \(bu 2 +\fB\-h\fP, \fB\-?\fP, \fB\-\-help\fP, \fB\-H\fP: \fB\-\-usage\fP +.IP \(bu 2 +\fB\-s\fP, \fB\-\-silent\fP: \fB\-\-loglevel silent\fP +.IP \(bu 2 +\fB\-q\fP, \fB\-\-quiet\fP: \fB\-\-loglevel warn\fP +.IP \(bu 2 +\fB\-d\fP: \fB\-\-loglevel info\fP +.IP \(bu 2 +\fB\-dd\fP, \fB\-\-verbose\fP: \fB\-\-loglevel verbose\fP +.IP \(bu 2 +\fB\-ddd\fP: \fB\-\-loglevel silly\fP +.IP \(bu 2 +\fB\-g\fP: \fB\-\-global\fP +.IP \(bu 2 +\fB\-C\fP: \fB\-\-prefix\fP +.IP \(bu 2 +\fB\-l\fP: \fB\-\-long\fP +.IP \(bu 2 +\fB\-m\fP: \fB\-\-message\fP +.IP \(bu 2 +\fB\-p\fP, \fB\-\-porcelain\fP: \fB\-\-parseable\fP +.IP \(bu 2 +\fB\-reg\fP: \fB\-\-registry\fP +.IP \(bu 2 +\fB\-f\fP: \fB\-\-force\fP +.IP \(bu 2 +\fB\-desc\fP: \fB\-\-description\fP +.IP \(bu 2 +\fB\-S\fP: \fB\-\-save\fP +.IP \(bu 2 +\fB\-P\fP: \fB\-\-save\-prod\fP +.IP \(bu 2 +\fB\-D\fP: \fB\-\-save\-dev\fP +.IP \(bu 2 +\fB\-O\fP: \fB\-\-save\-optional\fP +.IP \(bu 2 +\fB\-B\fP: \fB\-\-save\-bundle\fP +.IP \(bu 2 +\fB\-E\fP: \fB\-\-save\-exact\fP +.IP \(bu 2 +\fB\-y\fP: \fB\-\-yes\fP +.IP \(bu 2 +\fB\-n\fP: \fB\-\-yes false\fP +.IP \(bu 2 +\fBll\fP and \fBla\fP commands: \fBls \-\-long\fP + +.RE +.P +If the specified configuration param resolves unambiguously to a known +configuration parameter, then it is expanded to that configuration +parameter\. For example: +.P +.RS 2 +.nf +npm ls \-\-par +# same as: +npm ls \-\-parseable +.fi +.RE +.P +If multiple single\-character shorthands are strung together, and the +resulting combination is unambiguously not some other configuration +param, then it is expanded to its various component pieces\. For +example: +.P +.RS 2 +.nf +npm ls \-gpld +# same as: +npm ls \-\-global \-\-parseable \-\-long \-\-loglevel info +.fi +.RE +.SS Per\-Package Config Settings +.P +When running scripts (see npm help \fBscripts\fP) the package\.json "config" +keys are overwritten in the environment if there is a config param of +\fB[@]:\fP\|\. For example, if the package\.json has +this: +.P +.RS 2 +.nf +{ "name" : "foo" +, "config" : { "port" : "8080" } +, "scripts" : { "start" : "node server\.js" } } +.fi +.RE +.P +and the server\.js is this: +.P +.RS 2 +.nf +http\.createServer(\.\.\.)\.listen(process\.env\.npm_package_config_port) +.fi +.RE +.P +then the user could change the behavior by doing: +.P +.RS 2 +.nf +npm config set foo:port 80 +.fi +.RE +.P +See npm help package\.json for more information\. +.SS Config Settings +.SS access +.RS 0 +.IP \(bu 2 +Default: \fBrestricted\fP +.IP \(bu 2 +Type: Access + +.RE +.P +When publishing scoped packages, the access level defaults to \fBrestricted\fP\|\. If +you want your scoped package to be publicly viewable (and installable) set +\fB\-\-access=public\fP\|\. The only valid values for \fBaccess\fP are \fBpublic\fP and +\fBrestricted\fP\|\. Unscoped packages \fIalways\fR have an access level of \fBpublic\fP\|\. +.SS allow\-same\-version +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Prevents throwing an error when \fBnpm version\fP is used to set the new version +to the same value as the current version\. +.SS always\-auth +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Force npm to always require authentication when accessing the registry, +even for \fBGET\fP requests\. +.SS also +.RS 0 +.IP \(bu 2 +Default: null +.IP \(bu 2 +Type: String + +.RE +.P +When "dev" or "development" and running local \fBnpm shrinkwrap\fP, +\fBnpm outdated\fP, or \fBnpm update\fP, is an alias for \fB\-\-dev\fP\|\. +.SS audit +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean + +.RE +.P +When "true" submit audit reports alongside \fBnpm install\fP runs to the default +registry and all registries configured for scopes\. See the documentation +for npm help \fBaudit\fP for details on what is submitted\. +.SS audit\-level +.RS 0 +.IP \(bu 2 +Default: \fB"low"\fP +.IP \(bu 2 +Type: \fB\|'low'\fP, \fB\|'moderate'\fP, \fB\|'high'\fP, \fB\|'critical'\fP + +.RE +.P +The minimum level of vulnerability for \fBnpm audit\fP to exit with +a non\-zero exit code\. +.SS auth\-type +.RS 0 +.IP \(bu 2 +Default: \fB\|'legacy'\fP +.IP \(bu 2 +Type: \fB\|'legacy'\fP, \fB\|'sso'\fP, \fB\|'saml'\fP, \fB\|'oauth'\fP + +.RE +.P +What authentication strategy to use with \fBadduser\fP/\fBlogin\fP\|\. +.SS before +.RS 0 +.IP \(bu 2 +Alias: enjoy\-by +.IP \(bu 2 +Default: null +.IP \(bu 2 +Type: Date + +.RE +.P +If passed to \fBnpm install\fP, will rebuild the npm tree such that only versions +that were available \fBon or before\fR the \fB\-\-before\fP time get installed\. +If there's no versions available for the current set of direct dependencies, the +command will error\. +.P +If the requested version is a \fBdist\-tag\fP and the given tag does not pass the +\fB\-\-before\fP filter, the most recent version less than or equal to that tag will +be used\. For example, \fBfoo@latest\fP might install \fBfoo@1\.2\fP even though \fBlatest\fP +is \fB2\.0\fP\|\. +.SS bin\-links +.RS 0 +.IP \(bu 2 +Default: \fBtrue\fP +.IP \(bu 2 +Type: Boolean + +.RE +.P +Tells npm to create symlinks (or \fB\|\.cmd\fP shims on Windows) for package +executables\. +.P +Set to false to have it not do this\. This can be used to work around +the fact that some file systems don't support symlinks, even on +ostensibly Unix systems\. +.SS browser +.RS 0 +.IP \(bu 2 +Default: OS X: \fB"open"\fP, Windows: \fB"start"\fP, Others: \fB"xdg\-open"\fP +.IP \(bu 2 +Type: String + +.RE +.P +The browser that is called by the \fBnpm docs\fP command to open websites\. +.SS ca +.RS 0 +.IP \(bu 2 +Default: The npm CA certificate +.IP \(bu 2 +Type: String, Array or null + +.RE +.P +The Certificate Authority signing certificate that is trusted for SSL +connections to the registry\. Values should be in PEM format (Windows calls it "Base\-64 encoded X\.509 (\.CER)") with newlines +replaced by the string "\\n"\. For example: +.P +.RS 2 +.nf +ca="\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\\nXXXX\\nXXXX\\n\-\-\-\-\-END CERTIFICATE\-\-\-\-\-" +.fi +.RE +.P +Set to \fBnull\fP to only allow "known" registrars, or to a specific CA cert +to trust only that specific signing authority\. +.P +Multiple CAs can be trusted by specifying an array of certificates: +.P +.RS 2 +.nf +ca[]="\.\.\." +ca[]="\.\.\." +.fi +.RE +.P +See also the \fBstrict\-ssl\fP config\. +.SS cafile +.RS 0 +.IP \(bu 2 +Default: \fBnull\fP +.IP \(bu 2 +Type: path + +.RE +.P +A path to a file containing one or multiple Certificate Authority signing +certificates\. Similar to the \fBca\fP setting, but allows for multiple CA's, as +well as for the CA information to be stored in a file on disk\. +.SS cache +.RS 0 +.IP \(bu 2 +Default: Windows: \fB%AppData%\\npm\-cache\fP, Posix: \fB~/\.npm\fP +.IP \(bu 2 +Type: path + +.RE +.P +The location of npm's cache directory\. See npm help \fBcache\fP +.SS cache\-lock\-stale +.RS 0 +.IP \(bu 2 +Default: 60000 (1 minute) +.IP \(bu 2 +Type: Number + +.RE +.P +The number of ms before cache folder lockfiles are considered stale\. +.SS cache\-lock\-retries +.RS 0 +.IP \(bu 2 +Default: 10 +.IP \(bu 2 +Type: Number + +.RE +.P +Number of times to retry to acquire a lock on cache folder lockfiles\. +.SS cache\-lock\-wait +.RS 0 +.IP \(bu 2 +Default: 10000 (10 seconds) +.IP \(bu 2 +Type: Number + +.RE +.P +Number of ms to wait for cache lock files to expire\. +.SS cache\-max +.RS 0 +.IP \(bu 2 +Default: Infinity +.IP \(bu 2 +Type: Number + +.RE +.P +\fBDEPRECATED\fR: This option has been deprecated in favor of \fB\-\-prefer\-online\fP\|\. +.P +\fB\-\-cache\-max=0\fP is an alias for \fB\-\-prefer\-online\fP\|\. +.SS cache\-min +.RS 0 +.IP \(bu 2 +Default: 10 +.IP \(bu 2 +Type: Number + +.RE +.P +\fBDEPRECATED\fR: This option has been deprecated in favor of \fB\-\-prefer\-offline\fP\|\. +.P +\fB\-\-cache\-min=9999 (or bigger)\fP is an alias for \fB\-\-prefer\-offline\fP\|\. +.SS cert +.RS 0 +.IP \(bu 2 +Default: \fBnull\fP +.IP \(bu 2 +Type: String + +.RE +.P +A client certificate to pass when accessing the registry\. Values should be in +PEM format (Windows calls it "Base\-64 encoded X\.509 (\.CER)") with newlines replaced by the string "\\n"\. For example: +.P +.RS 2 +.nf +cert="\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\\nXXXX\\nXXXX\\n\-\-\-\-\-END CERTIFICATE\-\-\-\-\-" +.fi +.RE +.P +It is \fInot\fR the path to a certificate file (and there is no "certfile" option)\. +.SS cidr +.RS 0 +.IP \(bu 2 +Default: \fBnull\fP +.IP \(bu 2 +Type: String, Array, null + +.RE +.P +This is a list of CIDR address to be used when configuring limited access tokens with the \fBnpm token create\fP command\. +.SS color +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean or \fB"always"\fP + +.RE +.P +If false, never shows colors\. If \fB"always"\fP then always shows colors\. +If true, then only prints color codes for tty file descriptors\. +.P +This option can also be changed using the environment: colors are +disabled when the environment variable \fBNO_COLOR\fP is set to any value\. +.SS depth +.RS 0 +.IP \(bu 2 +Default: Infinity +.IP \(bu 2 +Type: Number + +.RE +.P +The depth to go when recursing directories for \fBnpm ls\fP, +\fBnpm cache ls\fP, and \fBnpm outdated\fP\|\. +.P +For \fBnpm outdated\fP, a setting of \fBInfinity\fP will be treated as \fB0\fP +since that gives more useful information\. To show the outdated status +of all packages and dependents, use a large integer value, +e\.g\., \fBnpm outdated \-\-depth 9999\fP +.SS description +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean + +.RE +.P +Show the description in \fBnpm search\fP +.SS dev +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Install \fBdev\-dependencies\fP along with packages\. +.SS dry\-run +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Indicates that you don't want npm to make any changes and that it should +only report what it would have done\. This can be passed into any of the +commands that modify your local installation, eg, \fBinstall\fP, \fBupdate\fP, +\fBdedupe\fP, \fBuninstall\fP\|\. This is NOT currently honored by some network related +commands, eg \fBdist\-tags\fP, \fBowner\fP, etc\. +.SS editor +.RS 0 +.IP \(bu 2 +Default: \fBEDITOR\fP environment variable if set, or \fB"vi"\fP on Posix, +or \fB"notepad"\fP on Windows\. +.IP \(bu 2 +Type: path + +.RE +.P +The command to run for \fBnpm edit\fP or \fBnpm config edit\fP\|\. +.SS engine\-strict +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +If set to true, then npm will stubbornly refuse to install (or even +consider installing) any package that claims to not be compatible with +the current Node\.js version\. +.SS force +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Makes various commands more forceful\. +.RS 0 +.IP \(bu 2 +lifecycle script failure does not block progress\. +.IP \(bu 2 +publishing clobbers previously published versions\. +.IP \(bu 2 +skips cache when requesting from the registry\. +.IP \(bu 2 +prevents checks against clobbering non\-npm files\. + +.RE +.SS format\-package\-lock +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean + +.RE +.P +Format \fBpackage\-lock\.json\fP or \fBnpm\-shrinkwrap\.json\fP as a human readable file\. +.SS fetch\-retries +.RS 0 +.IP \(bu 2 +Default: 2 +.IP \(bu 2 +Type: Number + +.RE +.P +The "retries" config for the \fBretry\fP module to use when fetching +packages from the registry\. +.SS fetch\-retry\-factor +.RS 0 +.IP \(bu 2 +Default: 10 +.IP \(bu 2 +Type: Number + +.RE +.P +The "factor" config for the \fBretry\fP module to use when fetching +packages\. +.SS fetch\-retry\-mintimeout +.RS 0 +.IP \(bu 2 +Default: 10000 (10 seconds) +.IP \(bu 2 +Type: Number + +.RE +.P +The "minTimeout" config for the \fBretry\fP module to use when fetching +packages\. +.SS fetch\-retry\-maxtimeout +.RS 0 +.IP \(bu 2 +Default: 60000 (1 minute) +.IP \(bu 2 +Type: Number + +.RE +.P +The "maxTimeout" config for the \fBretry\fP module to use when fetching +packages\. +.SS fund +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean + +.RE +.P +When "true" displays the message at the end of each \fBnpm install\fP +aknowledging the number of dependencies looking for funding\. +See npm help \fBfund\fP for details\. +.SS git +.RS 0 +.IP \(bu 2 +Default: \fB"git"\fP +.IP \(bu 2 +Type: String + +.RE +.P +The command to use for git commands\. If git is installed on the +computer, but is not in the \fBPATH\fP, then set this to the full path to +the git binary\. +.SS git\-tag\-version +.RS 0 +.IP \(bu 2 +Default: \fBtrue\fP +.IP \(bu 2 +Type: Boolean + +.RE +.P +Tag the commit when using the \fBnpm version\fP command\. +.SS commit\-hooks +.RS 0 +.IP \(bu 2 +Default: \fBtrue\fP +.IP \(bu 2 +Type: Boolean + +.RE +.P +Run git commit hooks when using the \fBnpm version\fP command\. +.SS global +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Operates in "global" mode, so that packages are installed into the +\fBprefix\fP folder instead of the current working directory\. See +npm help folders for more on the differences in behavior\. +.RS 0 +.IP \(bu 2 +packages are installed into the \fB{prefix}/lib/node_modules\fP folder, instead of the +current working directory\. +.IP \(bu 2 +bin files are linked to \fB{prefix}/bin\fP +.IP \(bu 2 +man pages are linked to \fB{prefix}/share/man\fP + +.RE +.SS globalconfig +.RS 0 +.IP \(bu 2 +Default: {prefix}/etc/npmrc +.IP \(bu 2 +Type: path + +.RE +.P +The config file to read for global config options\. +.SS global\-style +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Causes npm to install the package into your local \fBnode_modules\fP folder with +the same layout it uses with the global \fBnode_modules\fP folder\. Only your +direct dependencies will show in \fBnode_modules\fP and everything they depend +on will be flattened in their \fBnode_modules\fP folders\. This obviously will +eliminate some deduping\. If used with \fBlegacy\-bundling\fP, \fBlegacy\-bundling\fP will be +preferred\. +.SS group +.RS 0 +.IP \(bu 2 +Default: GID of the current process +.IP \(bu 2 +Type: String or Number + +.RE +.P +The group to use when running package scripts in global mode as the root +user\. +.SS heading +.RS 0 +.IP \(bu 2 +Default: \fB"npm"\fP +.IP \(bu 2 +Type: String + +.RE +.P +The string that starts all the debugging log output\. +.SS https\-proxy +.RS 0 +.IP \(bu 2 +Default: null +.IP \(bu 2 +Type: url + +.RE +.P +A proxy to use for outgoing https requests\. If the \fBHTTPS_PROXY\fP or +\fBhttps_proxy\fP or \fBHTTP_PROXY\fP or \fBhttp_proxy\fP environment variables are set, +proxy settings will be honored by the underlying \fBrequest\fP library\. +.SS if\-present +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +If true, npm will not exit with an error code when \fBrun\-script\fP is invoked for +a script that isn't defined in the \fBscripts\fP section of \fBpackage\.json\fP\|\. This +option can be used when it's desirable to optionally run a script when it's +present and fail if the script fails\. This is useful, for example, when running +scripts that may only apply for some builds in an otherwise generic CI setup\. +.SS ignore\-prepublish +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +If true, npm will not run \fBprepublish\fP scripts\. +.SS ignore\-scripts +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +If true, npm does not run scripts specified in package\.json files\. +.SS init\-module +.RS 0 +.IP \(bu 2 +Default: ~/\.npm\-init\.js +.IP \(bu 2 +Type: path + +.RE +.P +A module that will be loaded by the \fBnpm init\fP command\. See the +documentation for the +init\-package\-json \fIhttps://github\.com/isaacs/init\-package\-json\fR module +for more information, or npm help init\. +.SS init\-author\-name +.RS 0 +.IP \(bu 2 +Default: "" +.IP \(bu 2 +Type: String + +.RE +.P +The value \fBnpm init\fP should use by default for the package author's name\. +.SS init\-author\-email +.RS 0 +.IP \(bu 2 +Default: "" +.IP \(bu 2 +Type: String + +.RE +.P +The value \fBnpm init\fP should use by default for the package author's email\. +.SS init\-author\-url +.RS 0 +.IP \(bu 2 +Default: "" +.IP \(bu 2 +Type: String + +.RE +.P +The value \fBnpm init\fP should use by default for the package author's homepage\. +.SS init\-license +.RS 0 +.IP \(bu 2 +Default: "ISC" +.IP \(bu 2 +Type: String + +.RE +.P +The value \fBnpm init\fP should use by default for the package license\. +.SS init\-version +.RS 0 +.IP \(bu 2 +Default: "1\.0\.0" +.IP \(bu 2 +Type: semver + +.RE +.P +The value that \fBnpm init\fP should use by default for the package +version number, if not already set in package\.json\. +.SS json +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Whether or not to output JSON data, rather than the normal output\. +.P +This feature is currently experimental, and the output data structures for many +commands is either not implemented in JSON yet, or subject to change\. Only the +output from \fBnpm ls \-\-json\fP and \fBnpm search \-\-json\fP are currently valid\. +.SS key +.RS 0 +.IP \(bu 2 +Default: \fBnull\fP +.IP \(bu 2 +Type: String + +.RE +.P +A client key to pass when accessing the registry\. Values should be in PEM +format with newlines replaced by the string "\\n"\. For example: +.P +.RS 2 +.nf +key="\-\-\-\-\-BEGIN PRIVATE KEY\-\-\-\-\-\\nXXXX\\nXXXX\\n\-\-\-\-\-END PRIVATE KEY\-\-\-\-\-" +.fi +.RE .P It is \fInot\fR the path to a key file (and there is no "keyfile" option)\. .SS legacy\-bundling diff --git a/deps/npm/node_modules/bin-links/CHANGELOG.md b/deps/npm/node_modules/bin-links/CHANGELOG.md index 697e3c53559b40..e7b640c08d13fe 100644 --- a/deps/npm/node_modules/bin-links/CHANGELOG.md +++ b/deps/npm/node_modules/bin-links/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [1.1.7](https://github.com/npm/bin-links/compare/v1.1.6...v1.1.7) (2019-12-26) + + +### Bug Fixes + +* resolve folder that is passed in ([0bbd303](https://github.com/npm/bin-links/commit/0bbd303)) + + + ## [1.1.6](https://github.com/npm/bin-links/compare/v1.1.5...v1.1.6) (2019-12-11) diff --git a/deps/npm/node_modules/bin-links/index.js b/deps/npm/node_modules/bin-links/index.js index 4f6d3c055c02ee..79c2cb585bd73e 100644 --- a/deps/npm/node_modules/bin-links/index.js +++ b/deps/npm/node_modules/bin-links/index.js @@ -18,6 +18,7 @@ module.exports = BB.promisify(binLinks) function binLinks (pkg, folder, global, opts, cb) { pkg = normalize(pkg) + folder = path.resolve(folder) // if it's global, and folder is in {prefix}/node_modules, // then bins are in {prefix}/bin diff --git a/deps/npm/node_modules/bin-links/package.json b/deps/npm/node_modules/bin-links/package.json index a4d2c02226e5f1..45393d11c5fc87 100644 --- a/deps/npm/node_modules/bin-links/package.json +++ b/deps/npm/node_modules/bin-links/package.json @@ -1,19 +1,19 @@ { - "_from": "bin-links@1.1.6", - "_id": "bin-links@1.1.6", + "_from": "bin-links@1.1.7", + "_id": "bin-links@1.1.7", "_inBundle": false, - "_integrity": "sha512-b5rV3uVyrlrJWLI3mawUUf5t2f9mCEQm/TqT5zNj6DPYhYDZaNp0AYaYd/CVASkSEklayNDLliZHVdo2J3niPw==", + "_integrity": "sha512-/eaLaTu7G7/o7PV04QPy1HRT65zf+1tFkPGv0sPTV0tRwufooYBQO3zrcyGgm+ja+ZtBf2GEuKjDRJ2pPG+yqA==", "_location": "/bin-links", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, - "raw": "bin-links@1.1.6", + "raw": "bin-links@1.1.7", "name": "bin-links", "escapedName": "bin-links", - "rawSpec": "1.1.6", + "rawSpec": "1.1.7", "saveSpec": null, - "fetchSpec": "1.1.6" + "fetchSpec": "1.1.7" }, "_requiredBy": [ "#USER", @@ -21,10 +21,10 @@ "/libcipm", "/libnpm" ], - "_resolved": "https://registry.npmjs.org/bin-links/-/bin-links-1.1.6.tgz", - "_shasum": "30d33e810829305e5e61b90cfcb9a3a4f65eb516", - "_spec": "bin-links@1.1.6", - "_where": "/Users/isaacs/dev/npm/cli", + "_resolved": "https://registry.npmjs.org/bin-links/-/bin-links-1.1.7.tgz", + "_shasum": "34b79ea9d0e575d7308afeff0c6b2fc24c793359", + "_spec": "bin-links@1.1.7", + "_where": "/Users/mperrotte/npminc/cli", "author": { "name": "Mike Sherov" }, @@ -77,5 +77,5 @@ "update-coc": "weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'", "update-contrib": "weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'" }, - "version": "1.1.6" + "version": "1.1.7" } diff --git a/deps/npm/node_modules/env-paths/index.d.ts b/deps/npm/node_modules/env-paths/index.d.ts new file mode 100644 index 00000000000000..e57fa8f661f1ff --- /dev/null +++ b/deps/npm/node_modules/env-paths/index.d.ts @@ -0,0 +1,69 @@ +declare namespace envPaths { + export interface Options { + /** + __Don't use this option unless you really have to!__ + + Suffix appended to the project name to avoid name conflicts with native apps. Pass an empty string to disable it. + + @default 'nodejs' + */ + readonly suffix?: string; + } + + export interface Paths { + /** + Directory for data files. + */ + readonly data: string; + + /** + Directory for data files. + */ + readonly config: string; + + /** + Directory for non-essential data files. + */ + readonly cache: string; + + /** + Directory for log files. + */ + readonly log: string; + + /** + Directory for temporary files. + */ + readonly temp: string; + } +} + +declare const envPaths: { + /** + Get paths for storing things like data, config, cache, etc. + + @param name - Name of your project. Used to generate the paths. + @returns The paths to use for your project on current OS. + + @example + ``` + import envPaths = require('env-paths'); + + const paths = envPaths('MyApp'); + + paths.data; + //=> '/home/sindresorhus/.local/share/MyApp-nodejs' + + paths.config + //=> '/home/sindresorhus/.config/MyApp-nodejs' + ``` + */ + (name: string, options?: envPaths.Options): envPaths.Paths; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function envPaths(name: string, options?: envPaths.Options): envPaths.Paths; + // export = envPaths; + default: typeof envPaths; +}; + +export = envPaths; diff --git a/deps/npm/node_modules/env-paths/index.js b/deps/npm/node_modules/env-paths/index.js index 4a04b712ff8a67..7e7b50baa4416f 100644 --- a/deps/npm/node_modules/env-paths/index.js +++ b/deps/npm/node_modules/env-paths/index.js @@ -4,7 +4,7 @@ const os = require('os'); const homedir = os.homedir(); const tmpdir = os.tmpdir(); -const env = process.env; +const {env} = process; const macos = name => { const library = path.join(homedir, 'Library'); @@ -19,14 +19,15 @@ const macos = name => { }; const windows = name => { - const appData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); + const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); + const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); return { - // data/config/cache/log are invented by me as Windows isn't opinionated about this - data: path.join(appData, name, 'Data'), + // Data/config/cache/log are invented by me as Windows isn't opinionated about this + data: path.join(localAppData, name, 'Data'), config: path.join(appData, name, 'Config'), - cache: path.join(appData, name, 'Cache'), - log: path.join(appData, name, 'Log'), + cache: path.join(localAppData, name, 'Cache'), + log: path.join(localAppData, name, 'Log'), temp: path.join(tmpdir, name) }; }; @@ -45,16 +46,16 @@ const linux = name => { }; }; -module.exports = (name, opts) => { +const envPaths = (name, options) => { if (typeof name !== 'string') { throw new TypeError(`Expected string, got ${typeof name}`); } - opts = Object.assign({suffix: 'nodejs'}, opts); + options = Object.assign({suffix: 'nodejs'}, options); - if (opts.suffix) { - // add suffix to prevent possible conflict with native apps - name += `-${opts.suffix}`; + if (options.suffix) { + // Add suffix to prevent possible conflict with native apps + name += `-${options.suffix}`; } if (process.platform === 'darwin') { @@ -67,3 +68,7 @@ module.exports = (name, opts) => { return linux(name); }; + +module.exports = envPaths; +// TODO: Remove this for the next major release +module.exports.default = envPaths; diff --git a/deps/npm/node_modules/env-paths/license b/deps/npm/node_modules/env-paths/license index 654d0bfe943437..e7af2f77107d73 100644 --- a/deps/npm/node_modules/env-paths/license +++ b/deps/npm/node_modules/env-paths/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/env-paths/package.json b/deps/npm/node_modules/env-paths/package.json index 3b1dfb74d8041a..6af6711479dff7 100644 --- a/deps/npm/node_modules/env-paths/package.json +++ b/deps/npm/node_modules/env-paths/package.json @@ -1,27 +1,27 @@ { - "_from": "env-paths@^1.0.0", - "_id": "env-paths@1.0.0", + "_from": "env-paths@^2.2.0", + "_id": "env-paths@2.2.0", "_inBundle": false, - "_integrity": "sha1-QWgTO0K7BcOKNbGuQ5fIKYqzaeA=", + "_integrity": "sha512-6u0VYSCo/OW6IoD5WCLLy9JUGARbamfSavcNXry/eu8aHVFei6CD3Sw+VGX5alea1i9pgPHW0mbu6Xj0uBh7gA==", "_location": "/env-paths", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "env-paths@^1.0.0", + "raw": "env-paths@^2.2.0", "name": "env-paths", "escapedName": "env-paths", - "rawSpec": "^1.0.0", + "rawSpec": "^2.2.0", "saveSpec": null, - "fetchSpec": "^1.0.0" + "fetchSpec": "^2.2.0" }, "_requiredBy": [ "/node-gyp" ], - "_resolved": "https://registry.npmjs.org/env-paths/-/env-paths-1.0.0.tgz", - "_shasum": "4168133b42bb05c38a35b1ae4397c8298ab369e0", - "_spec": "env-paths@^1.0.0", - "_where": "/Users/isaacs/dev/npm/cli/node_modules/node-gyp", + "_resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.0.tgz", + "_shasum": "cdca557dc009152917d6166e2febe1f039685e43", + "_spec": "env-paths@^2.2.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/node-gyp", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -34,14 +34,16 @@ "deprecated": false, "description": "Get paths for storing things like data, config, cache, etc", "devDependencies": { - "ava": "*", - "xo": "*" + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" }, "engines": { - "node": ">=4" + "node": ">=6" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "homepage": "https://github.com/sindresorhus/env-paths#readme", "keywords": [ @@ -69,10 +71,7 @@ "url": "git+https://github.com/sindresorhus/env-paths.git" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd" }, - "version": "1.0.0", - "xo": { - "esnext": true - } + "version": "2.2.0" } diff --git a/deps/npm/node_modules/env-paths/readme.md b/deps/npm/node_modules/env-paths/readme.md index 0bdc2ac1439b70..ec3439316f9a1b 100644 --- a/deps/npm/node_modules/env-paths/readme.md +++ b/deps/npm/node_modules/env-paths/readme.md @@ -2,11 +2,13 @@ > Get paths for storing things like data, config, cache, etc +Uses the correct OS-specific paths. Most developers get this wrong. + ## Install ``` -$ npm install --save env-paths +$ npm install env-paths ``` @@ -14,6 +16,7 @@ $ npm install --save env-paths ```js const envPaths = require('env-paths'); + const paths = envPaths('MyApp'); paths.data; @@ -36,6 +39,8 @@ Name of your project. Used to generate the paths. #### options +Type: `Object` + ##### suffix Type: `string`
diff --git a/deps/npm/node_modules/get-caller-file/LICENSE.md b/deps/npm/node_modules/get-caller-file/LICENSE.md new file mode 100644 index 00000000000000..bf3e1c071bae44 --- /dev/null +++ b/deps/npm/node_modules/get-caller-file/LICENSE.md @@ -0,0 +1,6 @@ +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/deps/npm/node_modules/get-caller-file/README.md b/deps/npm/node_modules/get-caller-file/README.md index c32df54c391352..194492736bc4fe 100644 --- a/deps/npm/node_modules/get-caller-file/README.md +++ b/deps/npm/node_modules/get-caller-file/README.md @@ -1,4 +1,4 @@ # get-caller-file -[![Build Status](https://travis-ci.org/ember-cli/ember-cli.svg?branch=master)](https://travis-ci.org/ember-cli/ember-cli) +[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) diff --git a/deps/npm/node_modules/get-caller-file/package.json b/deps/npm/node_modules/get-caller-file/package.json index d5c90d52fca1e5..e853deec1b0563 100644 --- a/deps/npm/node_modules/get-caller-file/package.json +++ b/deps/npm/node_modules/get-caller-file/package.json @@ -1,8 +1,8 @@ { "_from": "get-caller-file@^1.0.1", - "_id": "get-caller-file@1.0.2", + "_id": "get-caller-file@1.0.3", "_inBundle": false, - "_integrity": "sha1-9wLmMSfn4jHBYKgMFVSstw1QR+U=", + "_integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", "_location": "/get-caller-file", "_phantomChildren": {}, "_requested": { @@ -18,10 +18,10 @@ "_requiredBy": [ "/yargs" ], - "_resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.2.tgz", - "_shasum": "f702e63127e7e231c160a80c1554acb70d5047e5", + "_resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "_shasum": "f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a", "_spec": "get-caller-file@^1.0.1", - "_where": "/Users/rebecca/code/npm/node_modules/yargs", + "_where": "/Users/mperrotte/npminc/cli/node_modules/yargs", "author": { "name": "Stefan Penner" }, @@ -30,11 +30,11 @@ }, "bundleDependencies": false, "deprecated": false, - "description": "[![Build Status](https://travis-ci.org/ember-cli/ember-cli.svg?branch=master)](https://travis-ci.org/ember-cli/ember-cli) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master)", + "description": "[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master)", "devDependencies": { - "chai": "^3.4.1", + "chai": "^4.1.2", "ensure-posix-path": "^1.0.1", - "mocha": "^2.3.4" + "mocha": "^5.2.0" }, "directories": { "test": "tests" @@ -54,5 +54,5 @@ "test": "mocha test", "test:debug": "mocha test" }, - "version": "1.0.2" + "version": "1.0.3" } diff --git a/deps/npm/node_modules/invert-kv/index.js b/deps/npm/node_modules/invert-kv/index.js index 61e21961128f71..27f9cbb8eaf281 100644 --- a/deps/npm/node_modules/invert-kv/index.js +++ b/deps/npm/node_modules/invert-kv/index.js @@ -1,14 +1,14 @@ 'use strict'; -module.exports = function (obj) { - if (typeof obj !== 'object') { +module.exports = object => { + if (typeof object !== 'object') { throw new TypeError('Expected an object'); } - var ret = {}; + const ret = {}; - for (var key in obj) { - var val = obj[key]; - ret[val] = key; + for (const key of Object.keys(object)) { + const value = object[key]; + ret[value] = key; } return ret; diff --git a/deps/npm/node_modules/mimic-fn/license b/deps/npm/node_modules/invert-kv/license similarity index 100% rename from deps/npm/node_modules/mimic-fn/license rename to deps/npm/node_modules/invert-kv/license diff --git a/deps/npm/node_modules/invert-kv/package.json b/deps/npm/node_modules/invert-kv/package.json index c38e09e5d91bac..beb77fa37f6fa7 100644 --- a/deps/npm/node_modules/invert-kv/package.json +++ b/deps/npm/node_modules/invert-kv/package.json @@ -1,43 +1,44 @@ { - "_from": "invert-kv@^1.0.0", - "_id": "invert-kv@1.0.0", + "_from": "invert-kv@^2.0.0", + "_id": "invert-kv@2.0.0", "_inBundle": false, - "_integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", + "_integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", "_location": "/invert-kv", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "invert-kv@^1.0.0", + "raw": "invert-kv@^2.0.0", "name": "invert-kv", "escapedName": "invert-kv", - "rawSpec": "^1.0.0", + "rawSpec": "^2.0.0", "saveSpec": null, - "fetchSpec": "^1.0.0" + "fetchSpec": "^2.0.0" }, "_requiredBy": [ "/lcid" ], - "_resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", - "_shasum": "104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6", - "_spec": "invert-kv@^1.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/lcid", + "_resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", + "_shasum": "7393f5afa59ec9ff5f67a27620d11c226e3eec02", + "_spec": "invert-kv@^2.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/lcid", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", - "url": "http://sindresorhus.com" + "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/invert-kv/issues" }, "bundleDependencies": false, "deprecated": false, - "description": "Invert the key/value of an object. Example: {foo: 'bar'} → {bar: 'foo'}", + "description": "Invert the key/value of an object. Example: `{foo: 'bar'}` → `{bar: 'foo'}`", "devDependencies": { - "mocha": "*" + "ava": "*", + "xo": "*" }, "engines": { - "node": ">=0.10.0" + "node": ">=4" }, "files": [ "index.js" @@ -45,10 +46,8 @@ "homepage": "https://github.com/sindresorhus/invert-kv#readme", "keywords": [ "object", - "obj", "key", "value", - "val", "kv", "invert" ], @@ -59,7 +58,7 @@ "url": "git+https://github.com/sindresorhus/invert-kv.git" }, "scripts": { - "test": "mocha" + "test": "xo && ava" }, - "version": "1.0.0" + "version": "2.0.0" } diff --git a/deps/npm/node_modules/invert-kv/readme.md b/deps/npm/node_modules/invert-kv/readme.md index 039fc7cfa25b01..365a97997cac3f 100644 --- a/deps/npm/node_modules/invert-kv/readme.md +++ b/deps/npm/node_modules/invert-kv/readme.md @@ -5,15 +5,15 @@ ## Install -```sh -$ npm install --save invert-kv +``` +$ npm install invert-kv ``` ## Usage ```js -var invertKv = require('invert-kv'); +const invertKv = require('invert-kv'); invertKv({foo: 'bar', unicorn: 'rainbow'}); //=> {bar: 'foo', rainbow: 'unicorn'} @@ -22,4 +22,4 @@ invertKv({foo: 'bar', unicorn: 'rainbow'}); ## License -MIT © [Sindre Sorhus](http://sindresorhus.com) +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/lcid/index.js b/deps/npm/node_modules/lcid/index.js index 69bd3d231e0594..b666ef00a4504c 100644 --- a/deps/npm/node_modules/lcid/index.js +++ b/deps/npm/node_modules/lcid/index.js @@ -1,9 +1,10 @@ 'use strict'; -var invertKv = require('invert-kv'); -var all = require('./lcid.json'); -var inverted = invertKv(all); +const invertKv = require('invert-kv'); +const all = require('./lcid.json'); -exports.from = function (lcidCode) { +const inverted = invertKv(all); + +exports.from = lcidCode => { if (typeof lcidCode !== 'number') { throw new TypeError('Expected a number'); } @@ -11,7 +12,7 @@ exports.from = function (lcidCode) { return inverted[lcidCode]; }; -exports.to = function (localeId) { +exports.to = localeId => { if (typeof localeId !== 'string') { throw new TypeError('Expected a string'); } diff --git a/deps/npm/node_modules/lcid/license b/deps/npm/node_modules/lcid/license index 654d0bfe943437..e7af2f77107d73 100644 --- a/deps/npm/node_modules/lcid/license +++ b/deps/npm/node_modules/lcid/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/lcid/package.json b/deps/npm/node_modules/lcid/package.json index 6ab09a0881309b..3de023722441e6 100644 --- a/deps/npm/node_modules/lcid/package.json +++ b/deps/npm/node_modules/lcid/package.json @@ -1,28 +1,27 @@ { - "_from": "lcid@^1.0.0", - "_id": "lcid@1.0.0", + "_from": "lcid@^2.0.0", + "_id": "lcid@2.0.0", "_inBundle": false, - "_integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "_integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", "_location": "/lcid", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "lcid@^1.0.0", + "raw": "lcid@^2.0.0", "name": "lcid", "escapedName": "lcid", - "rawSpec": "^1.0.0", + "rawSpec": "^2.0.0", "saveSpec": null, - "fetchSpec": "^1.0.0" + "fetchSpec": "^2.0.0" }, "_requiredBy": [ - "/os-locale", - "/tacks/os-locale" + "/os-locale" ], - "_resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", - "_shasum": "308accafa0bc483a3867b4b6f2b9506251d1b835", - "_spec": "lcid@^1.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/os-locale", + "_resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", + "_shasum": "6ef5d2df60e52f82eb228a4c373e8d1f397253cf", + "_spec": "lcid@^2.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -33,15 +32,16 @@ }, "bundleDependencies": false, "dependencies": { - "invert-kv": "^1.0.0" + "invert-kv": "^2.0.0" }, "deprecated": false, "description": "Mapping between standard locale identifiers and Windows locale identifiers (LCID)", "devDependencies": { - "ava": "0.0.4" + "ava": "*", + "xo": "*" }, "engines": { - "node": ">=0.10.0" + "node": ">=6" }, "files": [ "index.js", @@ -73,7 +73,7 @@ "url": "git+https://github.com/sindresorhus/lcid.git" }, "scripts": { - "test": "node test.js" + "test": "xo && ava" }, - "version": "1.0.0" + "version": "2.0.0" } diff --git a/deps/npm/node_modules/lcid/readme.md b/deps/npm/node_modules/lcid/readme.md index bee4a701669788..2b1aa798b69301 100644 --- a/deps/npm/node_modules/lcid/readme.md +++ b/deps/npm/node_modules/lcid/readme.md @@ -1,8 +1,8 @@ # lcid [![Build Status](https://travis-ci.org/sindresorhus/lcid.svg?branch=master)](https://travis-ci.org/sindresorhus/lcid) -> Mapping between [standard locale identifiers](http://en.wikipedia.org/wiki/Locale) and [Windows locale identifiers (LCID)](http://en.wikipedia.org/wiki/Locale#Specifics_for_Microsoft_platforms) +> Mapping between [standard locale identifiers](https://en.wikipedia.org/wiki/Locale_(computer_software)) and [Windows locale identifiers (LCID)](http://en.wikipedia.org/wiki/Locale#Specifics_for_Microsoft_platforms) -Based on the [mapping](https://github.com/python/cpython/blob/be2a1a76fa43bb1ea1b3577bb5bdd506a2e90e37/Lib/locale.py#L1395-L1604) used in the Python standard library. +Based on the [mapping](https://github.com/python/cpython/blob/8f7bb100d0fa7fb2714f3953b5b627878277c7c6/Lib/locale.py#L1465-L1674) used in the Python standard library. The mapping itself is just a [JSON file](lcid.json) and can be used wherever. @@ -10,14 +10,14 @@ The mapping itself is just a [JSON file](lcid.json) and can be used wherever. ## Install ``` -$ npm install --save lcid +$ npm install lcid ``` ## Usage ```js -var lcid = require('lcid'); +const lcid = require('lcid'); lcid.from(1044); //=> 'nb_NO' @@ -32,4 +32,4 @@ lcid.all; ## License -MIT © [Sindre Sorhus](http://sindresorhus.com) +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/libnpx/CHANGELOG.md b/deps/npm/node_modules/libnpx/CHANGELOG.md index 5fa91fac96ae70..74da62235d696e 100644 --- a/deps/npm/node_modules/libnpx/CHANGELOG.md +++ b/deps/npm/node_modules/libnpx/CHANGELOG.md @@ -2,61 +2,73 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [10.2.2](https://github.com/npm/npx/compare/v10.2.1...v10.2.2) (2020-01-28) + + +### Bug Fixes + +* correct Kat's github url ([9a23db1](https://github.com/npm/npx/commit/9a23db1)) +* install latest npm on travis for node 6 ([e0eb3cb](https://github.com/npm/npx/commit/e0eb3cb)) +* Update changelog to fix old issue links ([3733137](https://github.com/npm/npx/commit/3733137)) + + + -# [10.2.0](https://github.com/zkat/npx/compare/v10.1.1...v10.2.0) (2018-04-13) +# [10.2.0](https://github.com/npm/npx/compare/v10.1.1...v10.2.0) (2018-04-13) ### Bug Fixes -* **i18n:** fix korean; 쉘 -> 셸 ([#163](https://github.com/zkat/npx/issues/163)) ([11d9fe0](https://github.com/zkat/npx/commit/11d9fe0)) -* **spawn:** spawn child processes with node without relying on the shebang. ([#174](https://github.com/zkat/npx/issues/174)) ([cba97bb](https://github.com/zkat/npx/commit/cba97bb)) -* **windows:** Allow spaces in the node path when using --node-arg ([#173](https://github.com/zkat/npx/issues/173)) ([fe0d48a](https://github.com/zkat/npx/commit/fe0d48a)), closes [#170](https://github.com/zkat/npx/issues/170) +* **i18n:** fix korean; 쉘 -> 셸 ([#163](https://github.com/zkat/npx/issues/163)) ([11d9fe0](https://github.com/npm/npx/commit/11d9fe0)) +* **spawn:** spawn child processes with node without relying on the shebang. ([#174](https://github.com/zkat/npx/issues/174)) ([cba97bb](https://github.com/npm/npx/commit/cba97bb)) +* **windows:** Allow spaces in the node path when using --node-arg ([#173](https://github.com/zkat/npx/issues/173)) ([fe0d48a](https://github.com/npm/npx/commit/fe0d48a)), closes [#170](https://github.com/zkat/npx/issues/170) ### Features -* **i18n:** add translation ([#159](https://github.com/zkat/npx/issues/159)) ([5da008b](https://github.com/zkat/npx/commit/5da008b)) +* **i18n:** add translation ([#159](https://github.com/zkat/npx/issues/159)) ([5da008b](https://github.com/npm/npx/commit/5da008b)) -## [10.1.1](https://github.com/zkat/npx/compare/v10.1.0...v10.1.1) (2018-04-12) +## [10.1.1](https://github.com/npm/npx/compare/v10.1.0...v10.1.1) (2018-04-12) -# [10.1.0](https://github.com/zkat/npx/compare/v10.0.1...v10.1.0) (2018-04-12) +# [10.1.0](https://github.com/npm/npx/compare/v10.0.1...v10.1.0) (2018-04-12) ### Features -* **spawn:** add --always-spawn to opt out of process takeover optimization feature ([#172](https://github.com/zkat/npx/issues/172)) ([c0d6abc](https://github.com/zkat/npx/commit/c0d6abc)) +* **spawn:** add --always-spawn to opt out of process takeover optimization feature ([#172](https://github.com/zkat/npx/issues/172)) ([c0d6abc](https://github.com/npm/npx/commit/c0d6abc)) -## [10.0.1](https://github.com/zkat/npx/compare/v10.0.0...v10.0.1) (2018-03-08) +## [10.0.1](https://github.com/npm/npx/compare/v10.0.0...v10.0.1) (2018-03-08) ### Bug Fixes -* **i18n:** Improve French localization ([#158](https://github.com/zkat/npx/issues/158)) ([c88823e](https://github.com/zkat/npx/commit/c88823e)) -* **windows:** on Windows, throw useful error when package contains no binaries([#142](https://github.com/zkat/npx/issues/142)) ([a69276e](https://github.com/zkat/npx/commit/a69276e)), closes [#137](https://github.com/zkat/npx/issues/137) +* **i18n:** Improve French localization ([#158](https://github.com/zkat/npx/issues/158)) ([c88823e](https://github.com/npm/npx/commit/c88823e)) +* **windows:** on Windows, throw useful error when package contains no binaries([#142](https://github.com/zkat/npx/issues/142)) ([a69276e](https://github.com/npm/npx/commit/a69276e)), closes [#137](https://github.com/zkat/npx/issues/137) -# [10.0.0](https://github.com/zkat/npx/compare/v9.7.1...v10.0.0) (2018-03-08) +# [10.0.0](https://github.com/npm/npx/compare/v9.7.1...v10.0.0) (2018-03-08) ### Bug Fixes -* **i18n:** Fix Korean locale ([#130](https://github.com/zkat/npx/issues/130)) ([752db48](https://github.com/zkat/npx/commit/752db48)) -* **index:** remove extraneous logging on Windows ([#136](https://github.com/zkat/npx/issues/136)) ([357e6ab](https://github.com/zkat/npx/commit/357e6ab)), closes [#131](https://github.com/zkat/npx/issues/131) -* **license:** change npx license to ISC ([a617d7b](https://github.com/zkat/npx/commit/a617d7b)) -* **parse-args:** fix version thing for yargs ([30677ed](https://github.com/zkat/npx/commit/30677ed)) -* **prefix:** Handle node_modules without package.json ([#128](https://github.com/zkat/npx/issues/128)) ([f64ae43](https://github.com/zkat/npx/commit/f64ae43)), closes [/github.com/babel/babel/issues/4066#issuecomment-336705199](https://github.com//github.com/babel/babel/issues/4066/issues/issuecomment-336705199) -* **standard:** get things in line with standard 11 ([6cf8e88](https://github.com/zkat/npx/commit/6cf8e88)) +* **i18n:** Fix Korean locale ([#130](https://github.com/zkat/npx/issues/130)) ([752db48](https://github.com/npm/npx/commit/752db48)) +* **index:** remove extraneous logging on Windows ([#136](https://github.com/zkat/npx/issues/136)) ([357e6ab](https://github.com/npm/npx/commit/357e6ab)), closes [#131](https://github.com/zkat/npx/issues/131) +* **license:** change npx license to ISC ([a617d7b](https://github.com/npm/npx/commit/a617d7b)) +* **parse-args:** fix version thing for yargs ([30677ed](https://github.com/npm/npx/commit/30677ed)) +* **prefix:** Handle node_modules without package.json ([#128](https://github.com/zkat/npx/issues/128)) ([f64ae43](https://github.com/npm/npx/commit/f64ae43)), closes [/github.com/babel/babel/issues/4066#issuecomment-336705199](https://github.com//github.com/babel/babel/issues/4066/issues/issuecomment-336705199) +* **standard:** get things in line with standard 11 ([6cf8e88](https://github.com/npm/npx/commit/6cf8e88)) ### BREAKING CHANGES @@ -66,271 +78,271 @@ All notable changes to this project will be documented in this file. See [standa -## [9.7.1](https://github.com/zkat/npx/compare/v9.7.0...v9.7.1) (2017-10-19) +## [9.7.1](https://github.com/npm/npx/compare/v9.7.0...v9.7.1) (2017-10-19) ### Bug Fixes -* **main:** err... oops? ([f24b4e3](https://github.com/zkat/npx/commit/f24b4e3)) +* **main:** err... oops? ([f24b4e3](https://github.com/npm/npx/commit/f24b4e3)) -# [9.7.0](https://github.com/zkat/npx/compare/v9.6.0...v9.7.0) (2017-10-19) +# [9.7.0](https://github.com/npm/npx/compare/v9.6.0...v9.7.0) (2017-10-19) ### Bug Fixes -* **exec:** fixed unix binary pathing issues (#120) ([f80a970](https://github.com/zkat/npx/commit/f80a970)), closes [#120](https://github.com/zkat/npx/issues/120) +* **exec:** fixed unix binary pathing issues (#120) ([f80a970](https://github.com/npm/npx/commit/f80a970)), closes [#120](https://github.com/zkat/npx/issues/120) ### Features -* **child:** add opts.installerStdio (#126) ([ade03f7](https://github.com/zkat/npx/commit/ade03f7)) +* **child:** add opts.installerStdio (#126) ([ade03f7](https://github.com/npm/npx/commit/ade03f7)) -# [9.6.0](https://github.com/zkat/npx/compare/v9.5.0...v9.6.0) (2017-08-17) +# [9.6.0](https://github.com/npm/npx/compare/v9.5.0...v9.6.0) (2017-08-17) ### Features -* **i18n:** add Arabic translation (#111) ([3c5b99a](https://github.com/zkat/npx/commit/3c5b99a)) -* **i18n:** add Dutch (#108) ([ed116fd](https://github.com/zkat/npx/commit/ed116fd)) +* **i18n:** add Arabic translation (#111) ([3c5b99a](https://github.com/npm/npx/commit/3c5b99a)) +* **i18n:** add Dutch (#108) ([ed116fd](https://github.com/npm/npx/commit/ed116fd)) -# [9.5.0](https://github.com/zkat/npx/compare/v9.4.1...v9.5.0) (2017-07-28) +# [9.5.0](https://github.com/npm/npx/compare/v9.4.1...v9.5.0) (2017-07-28) ### Features -* **i18n:** add Polish translations (#99) ([8442f59](https://github.com/zkat/npx/commit/8442f59)) +* **i18n:** add Polish translations (#99) ([8442f59](https://github.com/npm/npx/commit/8442f59)) -## [9.4.1](https://github.com/zkat/npx/compare/v9.4.0...v9.4.1) (2017-07-21) +## [9.4.1](https://github.com/npm/npx/compare/v9.4.0...v9.4.1) (2017-07-21) ### Bug Fixes -* **i18n:** fix filename for uk.json locale ([2c770e4](https://github.com/zkat/npx/commit/2c770e4)) +* **i18n:** fix filename for uk.json locale ([2c770e4](https://github.com/npm/npx/commit/2c770e4)) -# [9.4.0](https://github.com/zkat/npx/compare/v9.3.2...v9.4.0) (2017-07-21) +# [9.4.0](https://github.com/npm/npx/compare/v9.3.2...v9.4.0) (2017-07-21) ### Bug Fixes -* **i18n:** minor fixes to ru locale (#92) ([f4d5051](https://github.com/zkat/npx/commit/f4d5051)), closes [#92](https://github.com/zkat/npx/issues/92) +* **i18n:** minor fixes to ru locale (#92) ([f4d5051](https://github.com/npm/npx/commit/f4d5051)), closes [#92](https://github.com/zkat/npx/issues/92) ### Features -* **i18n:** `no` locale fallback for Norwegian bokmål ⚠️ In case of weird setups ⚠️ (#91) ([74f0e4c](https://github.com/zkat/npx/commit/74f0e4c)) -* **i18n:** add Bahasa Indonesia locale (#95) ([80dceeb](https://github.com/zkat/npx/commit/80dceeb)) -* **i18n:** add serbian translation (#96) ([040de7a](https://github.com/zkat/npx/commit/040de7a)) -* **i18n:** add Ukrainian locale (#93) ([9a3ef33](https://github.com/zkat/npx/commit/9a3ef33)) -* **i18n:** Added Norwegian (bokmål and nynorsk) translations (#90) ([6c5c733](https://github.com/zkat/npx/commit/6c5c733)) +* **i18n:** `no` locale fallback for Norwegian bokmål ⚠️ In case of weird setups ⚠️ (#91) ([74f0e4c](https://github.com/npm/npx/commit/74f0e4c)) +* **i18n:** add Bahasa Indonesia locale (#95) ([80dceeb](https://github.com/npm/npx/commit/80dceeb)) +* **i18n:** add serbian translation (#96) ([040de7a](https://github.com/npm/npx/commit/040de7a)) +* **i18n:** add Ukrainian locale (#93) ([9a3ef33](https://github.com/npm/npx/commit/9a3ef33)) +* **i18n:** Added Norwegian (bokmål and nynorsk) translations (#90) ([6c5c733](https://github.com/npm/npx/commit/6c5c733)) -## [9.3.2](https://github.com/zkat/npx/compare/v9.3.1...v9.3.2) (2017-07-17) +## [9.3.2](https://github.com/npm/npx/compare/v9.3.1...v9.3.2) (2017-07-17) ### Bug Fixes -* **exec:** detect a wider range of shebang lines for node scripts (#89) ([1841b6f](https://github.com/zkat/npx/commit/1841b6f)) -* **windows:** escape spawn args because windows is picky (#87) ([314e5eb](https://github.com/zkat/npx/commit/314e5eb)) -* **windows:** get magic shim detection working on Windows (#88) ([255aeeb](https://github.com/zkat/npx/commit/255aeeb)) +* **exec:** detect a wider range of shebang lines for node scripts (#89) ([1841b6f](https://github.com/npm/npx/commit/1841b6f)) +* **windows:** escape spawn args because windows is picky (#87) ([314e5eb](https://github.com/npm/npx/commit/314e5eb)) +* **windows:** get magic shim detection working on Windows (#88) ([255aeeb](https://github.com/npm/npx/commit/255aeeb)) -## [9.3.1](https://github.com/zkat/npx/compare/v9.3.0...v9.3.1) (2017-07-17) +## [9.3.1](https://github.com/npm/npx/compare/v9.3.0...v9.3.1) (2017-07-17) ### Bug Fixes -* **deps:** update to npm[@5](https://github.com/5).3.0 ([2b14de2](https://github.com/zkat/npx/commit/2b14de2)) +* **deps:** update to npm[@5](https://github.com/5).3.0 ([2b14de2](https://github.com/npm/npx/commit/2b14de2)) -# [9.3.0](https://github.com/zkat/npx/compare/v9.2.3...v9.3.0) (2017-07-17) +# [9.3.0](https://github.com/npm/npx/compare/v9.2.3...v9.3.0) (2017-07-17) ### Features -* **i18n:** add Korean locale (#86) ([3655314](https://github.com/zkat/npx/commit/3655314)) +* **i18n:** add Korean locale (#86) ([3655314](https://github.com/npm/npx/commit/3655314)) -## [9.2.3](https://github.com/zkat/npx/compare/v9.2.2...v9.2.3) (2017-07-17) +## [9.2.3](https://github.com/npm/npx/compare/v9.2.2...v9.2.3) (2017-07-17) ### Bug Fixes -* **paths:** support npm/npx paths with spaces in them ([8f3b829](https://github.com/zkat/npx/commit/8f3b829)) +* **paths:** support npm/npx paths with spaces in them ([8f3b829](https://github.com/npm/npx/commit/8f3b829)) -## [9.2.2](https://github.com/zkat/npx/compare/v9.2.1...v9.2.2) (2017-07-15) +## [9.2.2](https://github.com/npm/npx/compare/v9.2.1...v9.2.2) (2017-07-15) ### Bug Fixes -* **npm:** escape path to npm, too ([333d2ff](https://github.com/zkat/npx/commit/333d2ff)) +* **npm:** escape path to npm, too ([333d2ff](https://github.com/npm/npx/commit/333d2ff)) -## [9.2.1](https://github.com/zkat/npx/compare/v9.2.0...v9.2.1) (2017-07-14) +## [9.2.1](https://github.com/npm/npx/compare/v9.2.0...v9.2.1) (2017-07-14) ### Bug Fixes -* **windows:** fixed windows binary pathing issues ([761dfe9](https://github.com/zkat/npx/commit/761dfe9)) +* **windows:** fixed windows binary pathing issues ([761dfe9](https://github.com/npm/npx/commit/761dfe9)) -# [9.2.0](https://github.com/zkat/npx/compare/v9.1.0...v9.2.0) (2017-07-14) +# [9.2.0](https://github.com/npm/npx/compare/v9.1.0...v9.2.0) (2017-07-14) ### Bug Fixes -* **binpath:** fix calling binaries from subdirectories ([f185d0d](https://github.com/zkat/npx/commit/f185d0d)) -* **i18n:** Fix typos in french locale (#78) ([f277fc7](https://github.com/zkat/npx/commit/f277fc7)), closes [#78](https://github.com/zkat/npx/issues/78) +* **binpath:** fix calling binaries from subdirectories ([f185d0d](https://github.com/npm/npx/commit/f185d0d)) +* **i18n:** Fix typos in french locale (#78) ([f277fc7](https://github.com/npm/npx/commit/f277fc7)), closes [#78](https://github.com/zkat/npx/issues/78) ### Features -* **i18n:** Add German translations (#79) ([c81e26d](https://github.com/zkat/npx/commit/c81e26d)) -* **i18n:** add zh_TW translation (#80) ([98288d8](https://github.com/zkat/npx/commit/98288d8)) +* **i18n:** Add German translations (#79) ([c81e26d](https://github.com/npm/npx/commit/c81e26d)) +* **i18n:** add zh_TW translation (#80) ([98288d8](https://github.com/npm/npx/commit/98288d8)) -# [9.1.0](https://github.com/zkat/npx/compare/v9.0.7...v9.1.0) (2017-07-12) +# [9.1.0](https://github.com/npm/npx/compare/v9.0.7...v9.1.0) (2017-07-12) ### Bug Fixes -* **call:** only npm run env if package.json exists ([370f395](https://github.com/zkat/npx/commit/370f395)) -* **i18n:** Fix grammar and spelling for de.json (#63) ([b14020f](https://github.com/zkat/npx/commit/b14020f)), closes [#63](https://github.com/zkat/npx/issues/63) -* **i18n:** wording revisions for Brazilian Portuguese (#75) ([b5dc536](https://github.com/zkat/npx/commit/b5dc536)) -* **npm:** path directly to the npm-cli.js script ([d531206](https://github.com/zkat/npx/commit/d531206)) -* **rimraf:** fix rimraf.sync is not a function issue ([d2ecba3](https://github.com/zkat/npx/commit/d2ecba3)) -* **windows:** get npx working well on Windows again (#69) ([6cfb8de](https://github.com/zkat/npx/commit/6cfb8de)), closes [#60](https://github.com/zkat/npx/issues/60) [#58](https://github.com/zkat/npx/issues/58) [#62](https://github.com/zkat/npx/issues/62) +* **call:** only npm run env if package.json exists ([370f395](https://github.com/npm/npx/commit/370f395)) +* **i18n:** Fix grammar and spelling for de.json (#63) ([b14020f](https://github.com/npm/npx/commit/b14020f)), closes [#63](https://github.com/zkat/npx/issues/63) +* **i18n:** wording revisions for Brazilian Portuguese (#75) ([b5dc536](https://github.com/npm/npx/commit/b5dc536)) +* **npm:** path directly to the npm-cli.js script ([d531206](https://github.com/npm/npx/commit/d531206)) +* **rimraf:** fix rimraf.sync is not a function issue ([d2ecba3](https://github.com/npm/npx/commit/d2ecba3)) +* **windows:** get npx working well on Windows again (#69) ([6cfb8de](https://github.com/npm/npx/commit/6cfb8de)), closes [#60](https://github.com/zkat/npx/issues/60) [#58](https://github.com/zkat/npx/issues/58) [#62](https://github.com/zkat/npx/issues/62) ### Features -* **i18n:** add Czech translation (#76) ([8a0b3f6](https://github.com/zkat/npx/commit/8a0b3f6)) -* **i18n:** Add Turkish translation (#73) ([26e5edf](https://github.com/zkat/npx/commit/26e5edf)) -* **i18n:** Added support for Italian language (#71) ([6883e75](https://github.com/zkat/npx/commit/6883e75)) -* **i18n:** Fix Romanian translation (#70) ([fd6bbcf](https://github.com/zkat/npx/commit/fd6bbcf)), closes [#70](https://github.com/zkat/npx/issues/70) -* **node:** add --node-arg support to pass flags to node for script binaries (#77) ([65665bd](https://github.com/zkat/npx/commit/65665bd)) +* **i18n:** add Czech translation (#76) ([8a0b3f6](https://github.com/npm/npx/commit/8a0b3f6)) +* **i18n:** Add Turkish translation (#73) ([26e5edf](https://github.com/npm/npx/commit/26e5edf)) +* **i18n:** Added support for Italian language (#71) ([6883e75](https://github.com/npm/npx/commit/6883e75)) +* **i18n:** Fix Romanian translation (#70) ([fd6bbcf](https://github.com/npm/npx/commit/fd6bbcf)), closes [#70](https://github.com/zkat/npx/issues/70) +* **node:** add --node-arg support to pass flags to node for script binaries (#77) ([65665bd](https://github.com/npm/npx/commit/65665bd)) -## [9.0.7](https://github.com/zkat/npx/compare/v9.0.6...v9.0.7) (2017-07-11) +## [9.0.7](https://github.com/npm/npx/compare/v9.0.6...v9.0.7) (2017-07-11) ### Bug Fixes -* **i18n:** Fix some Catalan translations (#59) ([11c8a19](https://github.com/zkat/npx/commit/11c8a19)), closes [#59](https://github.com/zkat/npx/issues/59) +* **i18n:** Fix some Catalan translations (#59) ([11c8a19](https://github.com/npm/npx/commit/11c8a19)), closes [#59](https://github.com/zkat/npx/issues/59) -## [9.0.6](https://github.com/zkat/npx/compare/v9.0.5...v9.0.6) (2017-07-11) +## [9.0.6](https://github.com/npm/npx/compare/v9.0.5...v9.0.6) (2017-07-11) ### Bug Fixes -* **auto-fallback:** fix syntax error in bash/zsh auto-fallback ([d8b19db](https://github.com/zkat/npx/commit/d8b19db)) +* **auto-fallback:** fix syntax error in bash/zsh auto-fallback ([d8b19db](https://github.com/npm/npx/commit/d8b19db)) -## [9.0.5](https://github.com/zkat/npx/compare/v9.0.4...v9.0.5) (2017-07-11) +## [9.0.5](https://github.com/npm/npx/compare/v9.0.4...v9.0.5) (2017-07-11) ### Bug Fixes -* **npx:** something went wrong with the 9.0.4 build and bundledeps ([75fc436](https://github.com/zkat/npx/commit/75fc436)) +* **npx:** something went wrong with the 9.0.4 build and bundledeps ([75fc436](https://github.com/npm/npx/commit/75fc436)) -## [9.0.4](https://github.com/zkat/npx/compare/v9.0.3...v9.0.4) (2017-07-11) +## [9.0.4](https://github.com/npm/npx/compare/v9.0.3...v9.0.4) (2017-07-11) ### Bug Fixes -* **auto-fallback:** prevent infinite loop if npx disappears ([6c24e58](https://github.com/zkat/npx/commit/6c24e58)) -* **bin:** add repository and more detailed author info ([906574e](https://github.com/zkat/npx/commit/906574e)) -* **bin:** pin the npx bin's dependencies ([ae62f7a](https://github.com/zkat/npx/commit/ae62f7a)) -* **build:** make sure changelog and license are copied to bin ([4fbb599](https://github.com/zkat/npx/commit/4fbb599)) -* **deps:** stop bundling deps in libnpx itself ([c3e56e9](https://github.com/zkat/npx/commit/c3e56e9)) -* **errors:** print command not found for packages without valid binaries ([9b24359](https://github.com/zkat/npx/commit/9b24359)) -* **help:** --no-install help text was contradicting itself ([9d96f5e](https://github.com/zkat/npx/commit/9d96f5e)) -* **install:** prevent concurrent npx runs from clobbering each other ([6b35c91](https://github.com/zkat/npx/commit/6b35c91)) -* **npx:** npx npx npx npx npx npx npx npx npx works again ([875d4cd](https://github.com/zkat/npx/commit/875d4cd)) -* **updater:** dependency injection for update-notifier target ([c3027a9](https://github.com/zkat/npx/commit/c3027a9)) -* **updater:** ignore some kinds of update-notifier errors ([7631bbe](https://github.com/zkat/npx/commit/7631bbe)) +* **auto-fallback:** prevent infinite loop if npx disappears ([6c24e58](https://github.com/npm/npx/commit/6c24e58)) +* **bin:** add repository and more detailed author info ([906574e](https://github.com/npm/npx/commit/906574e)) +* **bin:** pin the npx bin's dependencies ([ae62f7a](https://github.com/npm/npx/commit/ae62f7a)) +* **build:** make sure changelog and license are copied to bin ([4fbb599](https://github.com/npm/npx/commit/4fbb599)) +* **deps:** stop bundling deps in libnpx itself ([c3e56e9](https://github.com/npm/npx/commit/c3e56e9)) +* **errors:** print command not found for packages without valid binaries ([9b24359](https://github.com/npm/npx/commit/9b24359)) +* **help:** --no-install help text was contradicting itself ([9d96f5e](https://github.com/npm/npx/commit/9d96f5e)) +* **install:** prevent concurrent npx runs from clobbering each other ([6b35c91](https://github.com/npm/npx/commit/6b35c91)) +* **npx:** npx npx npx npx npx npx npx npx npx works again ([875d4cd](https://github.com/npm/npx/commit/875d4cd)) +* **updater:** dependency injection for update-notifier target ([c3027a9](https://github.com/npm/npx/commit/c3027a9)) +* **updater:** ignore some kinds of update-notifier errors ([7631bbe](https://github.com/npm/npx/commit/7631bbe)) -## [9.0.3](https://github.com/zkat/npx/compare/v9.0.2...v9.0.3) (2017-07-08) +## [9.0.3](https://github.com/npm/npx/compare/v9.0.2...v9.0.3) (2017-07-08) ### Bug Fixes -* **version:** hand version to yargs directly ([e0b5eeb](https://github.com/zkat/npx/commit/e0b5eeb)) +* **version:** hand version to yargs directly ([e0b5eeb](https://github.com/npm/npx/commit/e0b5eeb)) -## [9.0.2](https://github.com/zkat/npx/compare/v9.0.1...v9.0.2) (2017-07-08) +## [9.0.2](https://github.com/npm/npx/compare/v9.0.1...v9.0.2) (2017-07-08) ### Bug Fixes -* **manpage:** fix manpage for real because files syntax is weird ([9145e2a](https://github.com/zkat/npx/commit/9145e2a)) +* **manpage:** fix manpage for real because files syntax is weird ([9145e2a](https://github.com/npm/npx/commit/9145e2a)) -## [9.0.1](https://github.com/zkat/npx/compare/v9.0.0...v9.0.1) (2017-07-08) +## [9.0.1](https://github.com/npm/npx/compare/v9.0.0...v9.0.1) (2017-07-08) ### Bug Fixes -* **man:** make sure manpage is used in npx bin ([704b94f](https://github.com/zkat/npx/commit/704b94f)) +* **man:** make sure manpage is used in npx bin ([704b94f](https://github.com/npm/npx/commit/704b94f)) -# [9.0.0](https://github.com/zkat/npx/compare/v8.1.1...v9.0.0) (2017-07-08) +# [9.0.0](https://github.com/npm/npx/compare/v8.1.1...v9.0.0) (2017-07-08) ### Features -* **libnpx:** libify main npx codebase ([643f58e](https://github.com/zkat/npx/commit/643f58e)) -* **npx:** create a new binary for standalone publishing ([da5a3b7](https://github.com/zkat/npx/commit/da5a3b7)) +* **libnpx:** libify main npx codebase ([643f58e](https://github.com/npm/npx/commit/643f58e)) +* **npx:** create a new binary for standalone publishing ([da5a3b7](https://github.com/npm/npx/commit/da5a3b7)) ### BREAKING CHANGES @@ -342,49 +354,49 @@ and a separate project will take over the role of the main `npx` binary. -## [8.1.1](https://github.com/zkat/npx/compare/v8.1.0...v8.1.1) (2017-07-06) +## [8.1.1](https://github.com/npm/npx/compare/v8.1.0...v8.1.1) (2017-07-06) ### Bug Fixes -* **deps:** bump all deps ([6ea24bf](https://github.com/zkat/npx/commit/6ea24bf)) -* **npm:** bump npm to 5.1.0 for a bunch of fixes ([18e4587](https://github.com/zkat/npx/commit/18e4587)) +* **deps:** bump all deps ([6ea24bf](https://github.com/npm/npx/commit/6ea24bf)) +* **npm:** bump npm to 5.1.0 for a bunch of fixes ([18e4587](https://github.com/npm/npx/commit/18e4587)) -# [8.1.0](https://github.com/zkat/npx/compare/v8.0.1...v8.1.0) (2017-06-27) +# [8.1.0](https://github.com/npm/npx/compare/v8.0.1...v8.1.0) (2017-06-27) ### Bug Fixes -* **i18n:** minor tweaks to ja.json (#46) ([1ed63c2](https://github.com/zkat/npx/commit/1ed63c2)) +* **i18n:** minor tweaks to ja.json (#46) ([1ed63c2](https://github.com/npm/npx/commit/1ed63c2)) ### Features -* **i18n:** Update pt_BR.json (#51) ([d292f22](https://github.com/zkat/npx/commit/d292f22)) +* **i18n:** Update pt_BR.json (#51) ([d292f22](https://github.com/npm/npx/commit/d292f22)) -## [8.0.1](https://github.com/zkat/npx/compare/v8.0.0...v8.0.1) (2017-06-27) +## [8.0.1](https://github.com/npm/npx/compare/v8.0.0...v8.0.1) (2017-06-27) ### Bug Fixes -* **npm:** bump npm version for more bugfixes ([30711a8](https://github.com/zkat/npx/commit/30711a8)) -* **npm:** Use --parseable option to work around output quirks ([8cb75a2](https://github.com/zkat/npx/commit/8cb75a2)) +* **npm:** bump npm version for more bugfixes ([30711a8](https://github.com/npm/npx/commit/30711a8)) +* **npm:** Use --parseable option to work around output quirks ([8cb75a2](https://github.com/npm/npx/commit/8cb75a2)) -# [8.0.0](https://github.com/zkat/npx/compare/v7.0.0...v8.0.0) (2017-06-24) +# [8.0.0](https://github.com/npm/npx/compare/v7.0.0...v8.0.0) (2017-06-24) ### Features -* **exec:** auto-guess binaries when different from pkg name ([139c434](https://github.com/zkat/npx/commit/139c434)) +* **exec:** auto-guess binaries when different from pkg name ([139c434](https://github.com/npm/npx/commit/139c434)) ### BREAKING CHANGES @@ -398,17 +410,17 @@ multiple non-matching binaries, but that should be rare. -# [7.0.0](https://github.com/zkat/npx/compare/v6.2.0...v7.0.0) (2017-06-24) +# [7.0.0](https://github.com/npm/npx/compare/v6.2.0...v7.0.0) (2017-06-24) ### Bug Fixes -* **win32:** improve win32 situation a bit (#50) ([b7ad934](https://github.com/zkat/npx/commit/b7ad934)) +* **win32:** improve win32 situation a bit (#50) ([b7ad934](https://github.com/npm/npx/commit/b7ad934)) ### Features -* **local:** improve the behavior when calling ./local paths (#48) ([2e418d1](https://github.com/zkat/npx/commit/2e418d1)) +* **local:** improve the behavior when calling ./local paths (#48) ([2e418d1](https://github.com/npm/npx/commit/2e418d1)) ### BREAKING CHANGES @@ -422,71 +434,71 @@ of all the various cases and how each of them is handled. -# [6.2.0](https://github.com/zkat/npx/compare/v6.1.0...v6.2.0) (2017-06-23) +# [6.2.0](https://github.com/npm/npx/compare/v6.1.0...v6.2.0) (2017-06-23) ### Bug Fixes -* **child:** iron out a few crinkles and add tests ([b3b5ef6](https://github.com/zkat/npx/commit/b3b5ef6)) -* **execCmd:** only reuse the current process if no shell passed in ([e413cff](https://github.com/zkat/npx/commit/e413cff)) -* **execCmd:** use the module built-in directly ([6f741c2](https://github.com/zkat/npx/commit/6f741c2)) -* **help:** fuck it. just hard-code it ([d5d5085](https://github.com/zkat/npx/commit/d5d5085)) -* **main:** only exec if this is the main module ([9631e2a](https://github.com/zkat/npx/commit/9631e2a)) +* **child:** iron out a few crinkles and add tests ([b3b5ef6](https://github.com/npm/npx/commit/b3b5ef6)) +* **execCmd:** only reuse the current process if no shell passed in ([e413cff](https://github.com/npm/npx/commit/e413cff)) +* **execCmd:** use the module built-in directly ([6f741c2](https://github.com/npm/npx/commit/6f741c2)) +* **help:** fuck it. just hard-code it ([d5d5085](https://github.com/npm/npx/commit/d5d5085)) +* **main:** only exec if this is the main module ([9631e2a](https://github.com/npm/npx/commit/9631e2a)) ### Features -* **i18n:** Update fr.json (#44) ([ea47c4f](https://github.com/zkat/npx/commit/ea47c4f)) -* **i18n:** update the Romanian translation. (#42) ([2ed36b6](https://github.com/zkat/npx/commit/2ed36b6)) +* **i18n:** Update fr.json (#44) ([ea47c4f](https://github.com/npm/npx/commit/ea47c4f)) +* **i18n:** update the Romanian translation. (#42) ([2ed36b6](https://github.com/npm/npx/commit/2ed36b6)) -# [6.1.0](https://github.com/zkat/npx/compare/v6.0.0...v6.1.0) (2017-06-21) +# [6.1.0](https://github.com/npm/npx/compare/v6.0.0...v6.1.0) (2017-06-21) ### Bug Fixes -* **deps:** remove unused gauge dep ([aa40a34](https://github.com/zkat/npx/commit/aa40a34)) +* **deps:** remove unused gauge dep ([aa40a34](https://github.com/npm/npx/commit/aa40a34)) ### Features -* **i18n:** update ru locale (#41) ([7c84dee](https://github.com/zkat/npx/commit/7c84dee)) -* **i18n:** update zh_CN (#40) ([da4ec67](https://github.com/zkat/npx/commit/da4ec67)) -* **perf:** run node-based commands in the current process ([6efcde4](https://github.com/zkat/npx/commit/6efcde4)) +* **i18n:** update ru locale (#41) ([7c84dee](https://github.com/npm/npx/commit/7c84dee)) +* **i18n:** update zh_CN (#40) ([da4ec67](https://github.com/npm/npx/commit/da4ec67)) +* **perf:** run node-based commands in the current process ([6efcde4](https://github.com/npm/npx/commit/6efcde4)) -# [6.0.0](https://github.com/zkat/npx/compare/v5.4.0...v6.0.0) (2017-06-20) +# [6.0.0](https://github.com/npm/npx/compare/v5.4.0...v6.0.0) (2017-06-20) ### Bug Fixes -* **call:** stop parsing -c for commands + fix corner cases ([bd4e538](https://github.com/zkat/npx/commit/bd4e538)) -* **child:** exec does not have the information needed to correctly escape its args ([6714992](https://github.com/zkat/npx/commit/6714992)) -* **guessCmdName:** tests failed because of lazy npa ([53a0119](https://github.com/zkat/npx/commit/53a0119)) -* **i18n:** gender inclusiveness fix for french version (#37) ([04920ae](https://github.com/zkat/npx/commit/04920ae)), closes [#37](https://github.com/zkat/npx/issues/37) -* **i18n:** typo 😇 (#38) ([ede4a53](https://github.com/zkat/npx/commit/ede4a53)) -* **install:** handle JSON parsing failures ([bec2887](https://github.com/zkat/npx/commit/bec2887)) -* **output:** stop printing out Command Failed messages ([873cffe](https://github.com/zkat/npx/commit/873cffe)) -* **parseArgs:** fix booboo in fast path ([d1e5487](https://github.com/zkat/npx/commit/d1e5487)) -* **perf:** fast-path `npx foo` arg parsing ([ba4fe71](https://github.com/zkat/npx/commit/ba4fe71)) -* **perf:** remove bluebird and defer some requires for SPEED ([00fc313](https://github.com/zkat/npx/commit/00fc313)) +* **call:** stop parsing -c for commands + fix corner cases ([bd4e538](https://github.com/npm/npx/commit/bd4e538)) +* **child:** exec does not have the information needed to correctly escape its args ([6714992](https://github.com/npm/npx/commit/6714992)) +* **guessCmdName:** tests failed because of lazy npa ([53a0119](https://github.com/npm/npx/commit/53a0119)) +* **i18n:** gender inclusiveness fix for french version (#37) ([04920ae](https://github.com/npm/npx/commit/04920ae)), closes [#37](https://github.com/zkat/npx/issues/37) +* **i18n:** typo 😇 (#38) ([ede4a53](https://github.com/npm/npx/commit/ede4a53)) +* **install:** handle JSON parsing failures ([bec2887](https://github.com/npm/npx/commit/bec2887)) +* **output:** stop printing out Command Failed messages ([873cffe](https://github.com/npm/npx/commit/873cffe)) +* **parseArgs:** fix booboo in fast path ([d1e5487](https://github.com/npm/npx/commit/d1e5487)) +* **perf:** fast-path `npx foo` arg parsing ([ba4fe71](https://github.com/npm/npx/commit/ba4fe71)) +* **perf:** remove bluebird and defer some requires for SPEED ([00fc313](https://github.com/npm/npx/commit/00fc313)) ### Features -* **i18n:** add Romanian translations. (#34) ([9e98bd0](https://github.com/zkat/npx/commit/9e98bd0)) -* **i18n:** added a few more localizable strings ([779d950](https://github.com/zkat/npx/commit/779d950)) -* **i18n:** updated ca.json ([af7a035](https://github.com/zkat/npx/commit/af7a035)) -* **i18n:** updated es.json ([414644f](https://github.com/zkat/npx/commit/414644f)) -* **i18n:** updated ja.json ([448b082](https://github.com/zkat/npx/commit/448b082)) -* **i18n:** Ze German Translation (#35) ([6f003f5](https://github.com/zkat/npx/commit/6f003f5)) -* **package:** report number of temp packages installed ([5b7fe8d](https://github.com/zkat/npx/commit/5b7fe8d)) -* **perf:** only launch update-notifier when npx installs stuff ([549d413](https://github.com/zkat/npx/commit/549d413)) -* **quiet:** added -q/--quiet to suppress output from npx itself ([16607d9](https://github.com/zkat/npx/commit/16607d9)) +* **i18n:** add Romanian translations. (#34) ([9e98bd0](https://github.com/npm/npx/commit/9e98bd0)) +* **i18n:** added a few more localizable strings ([779d950](https://github.com/npm/npx/commit/779d950)) +* **i18n:** updated ca.json ([af7a035](https://github.com/npm/npx/commit/af7a035)) +* **i18n:** updated es.json ([414644f](https://github.com/npm/npx/commit/414644f)) +* **i18n:** updated ja.json ([448b082](https://github.com/npm/npx/commit/448b082)) +* **i18n:** Ze German Translation (#35) ([6f003f5](https://github.com/npm/npx/commit/6f003f5)) +* **package:** report number of temp packages installed ([5b7fe8d](https://github.com/npm/npx/commit/5b7fe8d)) +* **perf:** only launch update-notifier when npx installs stuff ([549d413](https://github.com/npm/npx/commit/549d413)) +* **quiet:** added -q/--quiet to suppress output from npx itself ([16607d9](https://github.com/npm/npx/commit/16607d9)) ### BREAKING CHANGES @@ -496,124 +508,124 @@ of all the various cases and how each of them is handled. -# [5.4.0](https://github.com/zkat/npx/compare/v5.3.0...v5.4.0) (2017-06-17) +# [5.4.0](https://github.com/npm/npx/compare/v5.3.0...v5.4.0) (2017-06-17) ### Bug Fixes -* **i18n:** some corrections for es.json ([4d50b71](https://github.com/zkat/npx/commit/4d50b71)) -* **i18n:** update locale files with bugfixes ([77caf82](https://github.com/zkat/npx/commit/77caf82)) -* **i18n:** Y utility was ignoring falsy entries ([f22a4d0](https://github.com/zkat/npx/commit/f22a4d0)) -* **i18n:** してください -> します ([01671af](https://github.com/zkat/npx/commit/01671af)) +* **i18n:** some corrections for es.json ([4d50b71](https://github.com/npm/npx/commit/4d50b71)) +* **i18n:** update locale files with bugfixes ([77caf82](https://github.com/npm/npx/commit/77caf82)) +* **i18n:** Y utility was ignoring falsy entries ([f22a4d0](https://github.com/npm/npx/commit/f22a4d0)) +* **i18n:** してください -> します ([01671af](https://github.com/npm/npx/commit/01671af)) ### Features -* **i18n:** add catalan translation ([579efa1](https://github.com/zkat/npx/commit/579efa1)) -* **i18n:** add pt-br translation (#33) ([6142551](https://github.com/zkat/npx/commit/6142551)) -* **i18n:** added largely machine-translated ja.json ([827705f](https://github.com/zkat/npx/commit/827705f)) -* **i18n:** adds russian translation (#32) ([b2619c1](https://github.com/zkat/npx/commit/b2619c1)) +* **i18n:** add catalan translation ([579efa1](https://github.com/npm/npx/commit/579efa1)) +* **i18n:** add pt-br translation (#33) ([6142551](https://github.com/npm/npx/commit/6142551)) +* **i18n:** added largely machine-translated ja.json ([827705f](https://github.com/npm/npx/commit/827705f)) +* **i18n:** adds russian translation (#32) ([b2619c1](https://github.com/npm/npx/commit/b2619c1)) -# [5.3.0](https://github.com/zkat/npx/compare/v5.2.0...v5.3.0) (2017-06-13) +# [5.3.0](https://github.com/npm/npx/compare/v5.2.0...v5.3.0) (2017-06-13) ### Features -* **i18n:** add Chinese translation (#31) ([24e1b31](https://github.com/zkat/npx/commit/24e1b31)) +* **i18n:** add Chinese translation (#31) ([24e1b31](https://github.com/npm/npx/commit/24e1b31)) -# [5.2.0](https://github.com/zkat/npx/compare/v5.1.3...v5.2.0) (2017-06-12) +# [5.2.0](https://github.com/npm/npx/compare/v5.1.3...v5.2.0) (2017-06-12) ### Bug Fixes -* **i18n:** removing extra spacing in fr.json ([002e2b8](https://github.com/zkat/npx/commit/002e2b8)) +* **i18n:** removing extra spacing in fr.json ([002e2b8](https://github.com/npm/npx/commit/002e2b8)) ### Features -* **i18n:** add french locale (#29) ([662395b](https://github.com/zkat/npx/commit/662395b)) +* **i18n:** add french locale (#29) ([662395b](https://github.com/npm/npx/commit/662395b)) -## [5.1.3](https://github.com/zkat/npx/compare/v5.1.2...v5.1.3) (2017-06-12) +## [5.1.3](https://github.com/npm/npx/compare/v5.1.2...v5.1.3) (2017-06-12) ### Bug Fixes -* **fallback:** put the Y in the wrong place lol ([d6bf8aa](https://github.com/zkat/npx/commit/d6bf8aa)) +* **fallback:** put the Y in the wrong place lol ([d6bf8aa](https://github.com/npm/npx/commit/d6bf8aa)) -## [5.1.2](https://github.com/zkat/npx/compare/v5.1.1...v5.1.2) (2017-06-10) +## [5.1.2](https://github.com/npm/npx/compare/v5.1.1...v5.1.2) (2017-06-10) -## [5.1.1](https://github.com/zkat/npx/compare/v5.1.0...v5.1.1) (2017-06-10) +## [5.1.1](https://github.com/npm/npx/compare/v5.1.0...v5.1.1) (2017-06-10) ### Bug Fixes -* **i18n:** forgot to add locales to files ([4118d6a](https://github.com/zkat/npx/commit/4118d6a)) +* **i18n:** forgot to add locales to files ([4118d6a](https://github.com/npm/npx/commit/4118d6a)) -# [5.1.0](https://github.com/zkat/npx/compare/v5.0.3...v5.1.0) (2017-06-10) +# [5.1.0](https://github.com/npm/npx/compare/v5.0.3...v5.1.0) (2017-06-10) ### Bug Fixes -* **exit:** let process exit normally to finish writes ([c50a398](https://github.com/zkat/npx/commit/c50a398)) +* **exit:** let process exit normally to finish writes ([c50a398](https://github.com/npm/npx/commit/c50a398)) ### Features -* **i18n:** added es.json ([6cf58b9](https://github.com/zkat/npx/commit/6cf58b9)) -* **i18n:** set up i18n plus baseline en.json locale ([b67bb3a](https://github.com/zkat/npx/commit/b67bb3a)) +* **i18n:** added es.json ([6cf58b9](https://github.com/npm/npx/commit/6cf58b9)) +* **i18n:** set up i18n plus baseline en.json locale ([b67bb3a](https://github.com/npm/npx/commit/b67bb3a)) -## [5.0.3](https://github.com/zkat/npx/compare/v5.0.2...v5.0.3) (2017-06-09) +## [5.0.3](https://github.com/npm/npx/compare/v5.0.2...v5.0.3) (2017-06-09) ### Bug Fixes -* **fallback:** exec is no ([42c1d30](https://github.com/zkat/npx/commit/42c1d30)) +* **fallback:** exec is no ([42c1d30](https://github.com/npm/npx/commit/42c1d30)) -## [5.0.2](https://github.com/zkat/npx/compare/v5.0.1...v5.0.2) (2017-06-09) +## [5.0.2](https://github.com/npm/npx/compare/v5.0.1...v5.0.2) (2017-06-09) ### Bug Fixes -* **fallback:** allow fallback to local anyway ([569cf2c](https://github.com/zkat/npx/commit/569cf2c)) +* **fallback:** allow fallback to local anyway ([569cf2c](https://github.com/npm/npx/commit/569cf2c)) -## [5.0.1](https://github.com/zkat/npx/compare/v5.0.0...v5.0.1) (2017-06-09) +## [5.0.1](https://github.com/npm/npx/compare/v5.0.0...v5.0.1) (2017-06-09) -# [5.0.0](https://github.com/zkat/npx/compare/v4.0.3...v5.0.0) (2017-06-09) +# [5.0.0](https://github.com/npm/npx/compare/v4.0.3...v5.0.0) (2017-06-09) ### Features -* **fallback:** by default, only fall back if you have an @ in the name ([bea08a0](https://github.com/zkat/npx/commit/bea08a0)) +* **fallback:** by default, only fall back if you have an @ in the name ([bea08a0](https://github.com/npm/npx/commit/bea08a0)) ### BREAKING CHANGES @@ -624,45 +636,45 @@ an @ sign in the command. -## [4.0.3](https://github.com/zkat/npx/compare/v4.0.2...v4.0.3) (2017-06-04) +## [4.0.3](https://github.com/npm/npx/compare/v4.0.2...v4.0.3) (2017-06-04) ### Bug Fixes -* **npm:** use --userconfig when querying for npm cache config (#28) ([21bc3bf](https://github.com/zkat/npx/commit/21bc3bf)) +* **npm:** use --userconfig when querying for npm cache config (#28) ([21bc3bf](https://github.com/npm/npx/commit/21bc3bf)) -## [4.0.2](https://github.com/zkat/npx/compare/v4.0.1...v4.0.2) (2017-06-04) +## [4.0.2](https://github.com/npm/npx/compare/v4.0.1...v4.0.2) (2017-06-04) ### Bug Fixes -* **install:** get windows workin (#27) ([9472175](https://github.com/zkat/npx/commit/9472175)) +* **install:** get windows workin (#27) ([9472175](https://github.com/npm/npx/commit/9472175)) -## [4.0.1](https://github.com/zkat/npx/compare/v4.0.0...v4.0.1) (2017-06-04) +## [4.0.1](https://github.com/npm/npx/compare/v4.0.0...v4.0.1) (2017-06-04) ### Bug Fixes -* **cmd:** make sure to use our own, enriched path ([9c89c2a](https://github.com/zkat/npx/commit/9c89c2a)) -* **error:** join args with a space on Command failed error ([c2f6f18](https://github.com/zkat/npx/commit/c2f6f18)) +* **cmd:** make sure to use our own, enriched path ([9c89c2a](https://github.com/npm/npx/commit/9c89c2a)) +* **error:** join args with a space on Command failed error ([c2f6f18](https://github.com/npm/npx/commit/c2f6f18)) -# [4.0.0](https://github.com/zkat/npx/compare/v3.0.0...v4.0.0) (2017-06-03) +# [4.0.0](https://github.com/npm/npx/compare/v3.0.0...v4.0.0) (2017-06-03) ### Features -* **call:** -c now loads same env as run-script ([76ae44c](https://github.com/zkat/npx/commit/76ae44c)) -* **npm:** allow configuration of npm binary ([e5d5634](https://github.com/zkat/npx/commit/e5d5634)) -* **npm:** embed npm binary ([a2cae9d](https://github.com/zkat/npx/commit/a2cae9d)) +* **call:** -c now loads same env as run-script ([76ae44c](https://github.com/npm/npx/commit/76ae44c)) +* **npm:** allow configuration of npm binary ([e5d5634](https://github.com/npm/npx/commit/e5d5634)) +* **npm:** embed npm binary ([a2cae9d](https://github.com/npm/npx/commit/a2cae9d)) ### BREAKING CHANGES @@ -674,29 +686,29 @@ variables added to them that were not there before. -# [3.0.0](https://github.com/zkat/npx/compare/v2.1.0...v3.0.0) (2017-06-03) +# [3.0.0](https://github.com/npm/npx/compare/v2.1.0...v3.0.0) (2017-06-03) ### Bug Fixes -* **args:** accept argv as arg and fix minor bugs ([46f10fe](https://github.com/zkat/npx/commit/46f10fe)) -* **deps:** explicitly add mkdirp and rimraf to devDeps ([832c75d](https://github.com/zkat/npx/commit/832c75d)) -* **docs:** misc tweaks to docs ([ed70a7b](https://github.com/zkat/npx/commit/ed70a7b)) -* **exec:** escape binaries and args to cp.exec (#18) ([55d6a11](https://github.com/zkat/npx/commit/55d6a11)) -* **fallback:** shells were sometimes ignored based on $SHELL ([07b7efc](https://github.com/zkat/npx/commit/07b7efc)) -* **get-prefix:** nudge isRootPath ([1ab31eb](https://github.com/zkat/npx/commit/1ab31eb)) -* **help:** correctly enable -h and --help ([adc2f45](https://github.com/zkat/npx/commit/adc2f45)) -* **startup:** delay loading some things to speed up startup ([6b32bf5](https://github.com/zkat/npx/commit/6b32bf5)) +* **args:** accept argv as arg and fix minor bugs ([46f10fe](https://github.com/npm/npx/commit/46f10fe)) +* **deps:** explicitly add mkdirp and rimraf to devDeps ([832c75d](https://github.com/npm/npx/commit/832c75d)) +* **docs:** misc tweaks to docs ([ed70a7b](https://github.com/npm/npx/commit/ed70a7b)) +* **exec:** escape binaries and args to cp.exec (#18) ([55d6a11](https://github.com/npm/npx/commit/55d6a11)) +* **fallback:** shells were sometimes ignored based on $SHELL ([07b7efc](https://github.com/npm/npx/commit/07b7efc)) +* **get-prefix:** nudge isRootPath ([1ab31eb](https://github.com/npm/npx/commit/1ab31eb)) +* **help:** correctly enable -h and --help ([adc2f45](https://github.com/npm/npx/commit/adc2f45)) +* **startup:** delay loading some things to speed up startup ([6b32bf5](https://github.com/npm/npx/commit/6b32bf5)) ### Features -* **cmd:** do some heuristic guesswork on default command names (#23) ([2404420](https://github.com/zkat/npx/commit/2404420)) -* **ignore:** add --ignore-existing option (#20) ([0866a83](https://github.com/zkat/npx/commit/0866a83)) -* **install:** added --no-install option to prevent install fallbacks ([a5fbdaf](https://github.com/zkat/npx/commit/a5fbdaf)) -* **package:** multiple --package options are now accepted ([f2fa6b3](https://github.com/zkat/npx/commit/f2fa6b3)) -* **save:** remove all save-related functionality (#19) ([ab77f6c](https://github.com/zkat/npx/commit/ab77f6c)) -* **shell:** run -c strings inside a system shell (#22) ([17db461](https://github.com/zkat/npx/commit/17db461)) +* **cmd:** do some heuristic guesswork on default command names (#23) ([2404420](https://github.com/npm/npx/commit/2404420)) +* **ignore:** add --ignore-existing option (#20) ([0866a83](https://github.com/npm/npx/commit/0866a83)) +* **install:** added --no-install option to prevent install fallbacks ([a5fbdaf](https://github.com/npm/npx/commit/a5fbdaf)) +* **package:** multiple --package options are now accepted ([f2fa6b3](https://github.com/npm/npx/commit/f2fa6b3)) +* **save:** remove all save-related functionality (#19) ([ab77f6c](https://github.com/npm/npx/commit/ab77f6c)) +* **shell:** run -c strings inside a system shell (#22) ([17db461](https://github.com/npm/npx/commit/17db461)) ### BREAKING CHANGES @@ -706,37 +718,37 @@ variables added to them that were not there before. -# [2.1.0](https://github.com/zkat/npx/compare/v2.0.1...v2.1.0) (2017-06-01) +# [2.1.0](https://github.com/npm/npx/compare/v2.0.1...v2.1.0) (2017-06-01) ### Features -* **opts:** add --shell-auto-fallback (#7) ([ac9cb40](https://github.com/zkat/npx/commit/ac9cb40)) +* **opts:** add --shell-auto-fallback (#7) ([ac9cb40](https://github.com/npm/npx/commit/ac9cb40)) -## [2.0.1](https://github.com/zkat/npx/compare/v2.0.0...v2.0.1) (2017-05-31) +## [2.0.1](https://github.com/npm/npx/compare/v2.0.0...v2.0.1) (2017-05-31) ### Bug Fixes -* **exec:** use command lookup joined with current PATH ([d9175e8](https://github.com/zkat/npx/commit/d9175e8)) +* **exec:** use command lookup joined with current PATH ([d9175e8](https://github.com/npm/npx/commit/d9175e8)) -# [2.0.0](https://github.com/zkat/npx/compare/v1.1.1...v2.0.0) (2017-05-31) +# [2.0.0](https://github.com/npm/npx/compare/v1.1.1...v2.0.0) (2017-05-31) ### Bug Fixes -* **npm:** manually look up npm path for Windows compat ([0fe8fbf](https://github.com/zkat/npx/commit/0fe8fbf)) +* **npm:** manually look up npm path for Windows compat ([0fe8fbf](https://github.com/npm/npx/commit/0fe8fbf)) ### Features -* **commands:** -p and [@version](https://github.com/version) now trigger installs ([9668c83](https://github.com/zkat/npx/commit/9668c83)) +* **commands:** -p and [@version](https://github.com/version) now trigger installs ([9668c83](https://github.com/npm/npx/commit/9668c83)) ### BREAKING CHANGES @@ -746,51 +758,51 @@ variables added to them that were not there before. -## [1.1.1](https://github.com/zkat/npx/compare/v1.1.0...v1.1.1) (2017-05-30) +## [1.1.1](https://github.com/npm/npx/compare/v1.1.0...v1.1.1) (2017-05-30) ### Bug Fixes -* **docs:** make sure man page gets installed ([2aadc16](https://github.com/zkat/npx/commit/2aadc16)) +* **docs:** make sure man page gets installed ([2aadc16](https://github.com/npm/npx/commit/2aadc16)) -# [1.1.0](https://github.com/zkat/npx/compare/v1.0.2...v1.1.0) (2017-05-30) +# [1.1.0](https://github.com/npm/npx/compare/v1.0.2...v1.1.0) (2017-05-30) ### Bug Fixes -* **help:** update usage string for help ([0747cff](https://github.com/zkat/npx/commit/0747cff)) -* **main:** exit if no package was parsed ([cdb579d](https://github.com/zkat/npx/commit/cdb579d)) -* **opts:** allow -- to prevent further parsing ([db7a0e4](https://github.com/zkat/npx/commit/db7a0e4)) +* **help:** update usage string for help ([0747cff](https://github.com/npm/npx/commit/0747cff)) +* **main:** exit if no package was parsed ([cdb579d](https://github.com/npm/npx/commit/cdb579d)) +* **opts:** allow -- to prevent further parsing ([db7a0e4](https://github.com/npm/npx/commit/db7a0e4)) ### Features -* **updates:** added update-notifier ([8dc91d4](https://github.com/zkat/npx/commit/8dc91d4)) +* **updates:** added update-notifier ([8dc91d4](https://github.com/npm/npx/commit/8dc91d4)) -## [1.0.2](https://github.com/zkat/npx/compare/v1.0.1...v1.0.2) (2017-05-30) +## [1.0.2](https://github.com/npm/npx/compare/v1.0.1...v1.0.2) (2017-05-30) ### Bug Fixes -* **pkg:** bundle deps to guarantee global install precision ([3e21217](https://github.com/zkat/npx/commit/3e21217)) +* **pkg:** bundle deps to guarantee global install precision ([3e21217](https://github.com/npm/npx/commit/3e21217)) -## [1.0.1](https://github.com/zkat/npx/compare/v1.0.0...v1.0.1) (2017-05-30) +## [1.0.1](https://github.com/npm/npx/compare/v1.0.0...v1.0.1) (2017-05-30) ### Bug Fixes -* **build:** add dummy test file to let things build ([6199eb6](https://github.com/zkat/npx/commit/6199eb6)) -* **docs:** fix arg documentation in readme/manpage ([d1cf44c](https://github.com/zkat/npx/commit/d1cf44c)) -* **opts:** add --version/-v ([2633a0e](https://github.com/zkat/npx/commit/2633a0e)) +* **build:** add dummy test file to let things build ([6199eb6](https://github.com/npm/npx/commit/6199eb6)) +* **docs:** fix arg documentation in readme/manpage ([d1cf44c](https://github.com/npm/npx/commit/d1cf44c)) +* **opts:** add --version/-v ([2633a0e](https://github.com/npm/npx/commit/2633a0e)) @@ -800,4 +812,4 @@ variables added to them that were not there before. ### Features -* **npx:** initial working implementation ([a83a67d](https://github.com/zkat/npx/commit/a83a67d)) +* **npx:** initial working implementation ([a83a67d](https://github.com/npm/npx/commit/a83a67d)) diff --git a/deps/npm/node_modules/libnpx/README.md b/deps/npm/node_modules/libnpx/README.md index 130f1bc3fdd023..fa7f37d878a067 100644 --- a/deps/npm/node_modules/libnpx/README.md +++ b/deps/npm/node_modules/libnpx/README.md @@ -1,4 +1,4 @@ -[![npm](https://img.shields.io/npm/v/npx.svg)](https://npm.im/npx) [![license](https://img.shields.io/npm/l/npx.svg)](https://npm.im/npx) [![Travis](https://img.shields.io/travis/zkat/npx.svg)](https://travis-ci.org/zkat/npx) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/npx?svg=true)](https://ci.appveyor.com/project/zkat/npx) [![Coverage Status](https://coveralls.io/repos/github/zkat/npx/badge.svg?branch=latest)](https://coveralls.io/github/zkat/npx?branch=latest) +[![npm](https://img.shields.io/npm/v/npx.svg)](https://npm.im/npx) [![license](https://img.shields.io/npm/l/npx.svg)](https://npm.im/npx) [![Travis](https://img.shields.io/travis/npm/npx.svg)](https://travis-ci.org/npm/npx) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/npm/npx?svg=true)](https://ci.appveyor.com/project/npm/npx) [![Coverage Status](https://coveralls.io/repos/github/npm/npx/badge.svg?branch=latest)](https://coveralls.io/github/npm/npx?branch=latest) # npx(1) -- execute npm package binaries @@ -152,7 +152,7 @@ Written by [Kat Marchan](https://github.com/zkat). ## REPORTING BUGS -Please file any relevant issues [on Github.](https://github.com/zkat/npx) +Please file any relevant issues [on Github.](https://github.com/npm/npx) ## LICENSE diff --git a/deps/npm/node_modules/libnpx/libnpx.1 b/deps/npm/node_modules/libnpx/libnpx.1 index 4215202da8e244..aea3ffe8f41922 100644 --- a/deps/npm/node_modules/libnpx/libnpx.1 +++ b/deps/npm/node_modules/libnpx/libnpx.1 @@ -1,4 +1,4 @@ -.TH "NPX" "1" "April 2018" "libnpx@10.1.1" "User Commands" +.TH "NPX" "1" "January 2020" "libnpx@10.2.1" "User Commands" .SH "NAME" \fBnpx\fR \- execute npm package binaries .SH SYNOPSIS @@ -158,7 +158,7 @@ Huge thanks to Kwyn Meagher \fIhttps://blog\.kwyn\.io\fR for generously donating Written by Kat Marchan \fIhttps://github\.com/zkat\fR\|\. .SH REPORTING BUGS .P -Please file any relevant issues on Github\. \fIhttps://github\.com/zkat/npx\fR +Please file any relevant issues on Github\. \fIhttps://github\.com/npm/npx\fR .SH LICENSE .P This work is released by its authors into the public domain under CC0\-1\.0\. See \fBLICENSE\.md\fP for details\. diff --git a/deps/npm/node_modules/libnpx/package.json b/deps/npm/node_modules/libnpx/package.json index b9d866b96a7d00..9b9949cd3ca4f4 100644 --- a/deps/npm/node_modules/libnpx/package.json +++ b/deps/npm/node_modules/libnpx/package.json @@ -1,39 +1,36 @@ { - "_args": [ - [ - "libnpx@10.2.0", - "/Users/rebecca/code/npm" - ] - ], - "_from": "libnpx@10.2.0", - "_id": "libnpx@10.2.0", + "_from": "libnpx@10.2.2", + "_id": "libnpx@10.2.2", "_inBundle": false, - "_integrity": "sha512-X28coei8/XRCt15cYStbLBph+KGhFra4VQhRBPuH/HHMkC5dxM8v24RVgUsvODKCrUZ0eTgiTqJp6zbl0sskQQ==", + "_integrity": "sha512-ujaYToga1SAX5r7FU5ShMFi88CWpY75meNZtr6RtEyv4l2ZK3+Wgvxq2IqlwWBiDZOqhumdeiocPS1aKrCMe3A==", "_location": "/libnpx", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, - "raw": "libnpx@10.2.0", + "raw": "libnpx@10.2.2", "name": "libnpx", "escapedName": "libnpx", - "rawSpec": "10.2.0", + "rawSpec": "10.2.2", "saveSpec": null, - "fetchSpec": "10.2.0" + "fetchSpec": "10.2.2" }, "_requiredBy": [ + "#USER", "/" ], - "_resolved": "https://registry.npmjs.org/libnpx/-/libnpx-10.2.0.tgz", - "_spec": "10.2.0", - "_where": "/Users/rebecca/code/npm", + "_resolved": "https://registry.npmjs.org/libnpx/-/libnpx-10.2.2.tgz", + "_shasum": "5a4171b9b92dd031463ef66a4af9f5cbd6b09572", + "_spec": "libnpx@10.2.2", + "_where": "/Users/mperrotte/npminc/cli", "author": { "name": "Kat Marchán", "email": "kzm@sykosomatic.org" }, "bugs": { - "url": "https://github.com/zkat/npx/issues" + "url": "https://github.com/npm/npx/issues" }, + "bundleDependencies": false, "config": { "nyc": { "exclude": [ @@ -52,6 +49,7 @@ "y18n": "^4.0.0", "yargs": "^11.0.0" }, + "deprecated": false, "description": "support library for npx -- an tool for executing npm-based packages.", "devDependencies": { "cross-env": "^5.1.3", @@ -76,7 +74,7 @@ "libnpx.1", "locales" ], - "homepage": "https://github.com/zkat/npx#readme", + "homepage": "https://github.com/npm/npx#readme", "keywords": [ "npm", "npm exec", @@ -93,7 +91,7 @@ "name": "libnpx", "repository": { "type": "git", - "url": "git+https://github.com/zkat/npx.git" + "url": "git+https://github.com/npm/npx.git" }, "scripts": { "bin": "make bin", @@ -107,5 +105,5 @@ "update-coc": "weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'", "update-contrib": "weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'" }, - "version": "10.2.0" + "version": "10.2.2" } diff --git a/deps/npm/node_modules/map-age-cleaner/dist/index.d.ts b/deps/npm/node_modules/map-age-cleaner/dist/index.d.ts new file mode 100644 index 00000000000000..fbf5ce08f5fc18 --- /dev/null +++ b/deps/npm/node_modules/map-age-cleaner/dist/index.d.ts @@ -0,0 +1,20 @@ +interface Entry { + [key: string]: any; +} +interface MaxAgeEntry extends Entry { + maxAge: number; +} +/** + * Automatically cleanup the items in the provided `map`. The property of the expiration timestamp should be named `maxAge`. + * + * @param map - Map instance which should be cleaned up. + */ +export default function mapAgeCleaner(map: Map): any; +/** + * Automatically cleanup the items in the provided `map`. + * + * @param map - Map instance which should be cleaned up. + * @param property - Name of the property which olds the expiry timestamp. + */ +export default function mapAgeCleaner(map: Map, property: string): any; +export {}; diff --git a/deps/npm/node_modules/map-age-cleaner/dist/index.js b/deps/npm/node_modules/map-age-cleaner/dist/index.js new file mode 100644 index 00000000000000..ff137dec85f56d --- /dev/null +++ b/deps/npm/node_modules/map-age-cleaner/dist/index.js @@ -0,0 +1,92 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const p_defer_1 = __importDefault(require("p-defer")); +function mapAgeCleaner(map, property = 'maxAge') { + let processingKey; + let processingTimer; + let processingDeferred; + const cleanup = () => __awaiter(this, void 0, void 0, function* () { + if (processingKey !== undefined) { + // If we are already processing an item, we can safely exit + return; + } + const setupTimer = (item) => __awaiter(this, void 0, void 0, function* () { + processingDeferred = p_defer_1.default(); + const delay = item[1][property] - Date.now(); + if (delay <= 0) { + // Remove the item immediately if the delay is equal to or below 0 + map.delete(item[0]); + processingDeferred.resolve(); + return; + } + // Keep track of the current processed key + processingKey = item[0]; + processingTimer = setTimeout(() => { + // Remove the item when the timeout fires + map.delete(item[0]); + if (processingDeferred) { + processingDeferred.resolve(); + } + }, delay); + // tslint:disable-next-line:strict-type-predicates + if (typeof processingTimer.unref === 'function') { + // Don't hold up the process from exiting + processingTimer.unref(); + } + return processingDeferred.promise; + }); + try { + for (const entry of map) { + yield setupTimer(entry); + } + } + catch (_a) { + // Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing + } + processingKey = undefined; + }); + const reset = () => { + processingKey = undefined; + if (processingTimer !== undefined) { + clearTimeout(processingTimer); + processingTimer = undefined; + } + if (processingDeferred !== undefined) { // tslint:disable-line:early-exit + processingDeferred.reject(undefined); + processingDeferred = undefined; + } + }; + const originalSet = map.set.bind(map); + map.set = (key, value) => { + if (map.has(key)) { + // If the key already exist, remove it so we can add it back at the end of the map. + map.delete(key); + } + // Call the original `map.set` + const result = originalSet(key, value); + // If we are already processing a key and the key added is the current processed key, stop processing it + if (processingKey && processingKey === key) { + reset(); + } + // Always run the cleanup method in case it wasn't started yet + cleanup(); // tslint:disable-line:no-floating-promises + return result; + }; + cleanup(); // tslint:disable-line:no-floating-promises + return map; +} +exports.default = mapAgeCleaner; +// Add support for CJS +module.exports = mapAgeCleaner; +module.exports.default = mapAgeCleaner; diff --git a/deps/npm/node_modules/map-age-cleaner/license b/deps/npm/node_modules/map-age-cleaner/license new file mode 100644 index 00000000000000..0711ab006f8a92 --- /dev/null +++ b/deps/npm/node_modules/map-age-cleaner/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sam Verschueren (github.com/SamVerschueren) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/map-age-cleaner/package.json b/deps/npm/node_modules/map-age-cleaner/package.json new file mode 100644 index 00000000000000..fc6be6aac5f145 --- /dev/null +++ b/deps/npm/node_modules/map-age-cleaner/package.json @@ -0,0 +1,95 @@ +{ + "_args": [ + [ + "map-age-cleaner@0.1.3", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "map-age-cleaner@0.1.3", + "_id": "map-age-cleaner@0.1.3", + "_inBundle": false, + "_integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", + "_location": "/map-age-cleaner", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "map-age-cleaner@0.1.3", + "name": "map-age-cleaner", + "escapedName": "map-age-cleaner", + "rawSpec": "0.1.3", + "saveSpec": null, + "fetchSpec": "0.1.3" + }, + "_requiredBy": [ + "/nyc/mem" + ], + "_resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", + "_spec": "0.1.3", + "_where": "/Users/mperrotte/npminc/cli", + "author": { + "name": "Sam Verschueren", + "email": "sam.verschueren@gmail.com", + "url": "github.com/SamVerschueren" + }, + "bugs": { + "url": "https://github.com/SamVerschueren/map-age-cleaner/issues" + }, + "dependencies": { + "p-defer": "^1.0.0" + }, + "description": "Automatically cleanup expired items in a Map", + "devDependencies": { + "@types/delay": "^2.0.1", + "@types/node": "^10.7.1", + "ava": "^0.25.0", + "codecov": "^3.0.0", + "del-cli": "^1.1.0", + "delay": "^3.0.0", + "nyc": "^12.0.0", + "tslint": "^5.11.0", + "tslint-xo": "^0.9.0", + "typescript": "^3.0.1" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "dist/index.js", + "dist/index.d.ts" + ], + "homepage": "https://github.com/SamVerschueren/map-age-cleaner#readme", + "keywords": [ + "map", + "age", + "cleaner", + "maxage", + "expire", + "expiration", + "expiring" + ], + "license": "MIT", + "main": "dist/index.js", + "name": "map-age-cleaner", + "nyc": { + "exclude": [ + "dist/test.js" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/SamVerschueren/map-age-cleaner.git" + }, + "scripts": { + "build": "npm run clean && tsc", + "clean": "del-cli dist", + "lint": "tslint --format stylish --project .", + "prepublishOnly": "npm run build", + "pretest": "npm run build -- --sourceMap", + "test": "npm run lint && nyc ava dist/test.js" + }, + "sideEffects": false, + "typings": "dist/index.d.ts", + "version": "0.1.3" +} diff --git a/deps/npm/node_modules/map-age-cleaner/readme.md b/deps/npm/node_modules/map-age-cleaner/readme.md new file mode 100644 index 00000000000000..471d93353a07ec --- /dev/null +++ b/deps/npm/node_modules/map-age-cleaner/readme.md @@ -0,0 +1,67 @@ +# map-age-cleaner + +[![Build Status](https://travis-ci.org/SamVerschueren/map-age-cleaner.svg?branch=master)](https://travis-ci.org/SamVerschueren/map-age-cleaner) [![codecov](https://codecov.io/gh/SamVerschueren/map-age-cleaner/badge.svg?branch=master)](https://codecov.io/gh/SamVerschueren/map-age-cleaner?branch=master) + +> Automatically cleanup expired items in a Map + + +## Install + +``` +$ npm install map-age-cleaner +``` + + +## Usage + +```js +import mapAgeCleaner from 'map-age-cleaner'; + +const map = new Map([ + ['unicorn', {data: '🦄', maxAge: Date.now() + 1000}] +]); + +mapAgeCleaner(map); + +map.has('unicorn'); +//=> true + +// Wait for 1 second... + +map.has('unicorn'); +//=> false +``` + +> **Note**: Items have to be ordered ascending based on the expiry property. This means that the item which will be expired first, should be in the first position of the `Map`. + + +## API + +### mapAgeCleaner(map, [property]) + +Returns the `Map` instance. + +#### map + +Type: `Map` + +Map instance which should be cleaned up. + +#### property + +Type: `string`
+Default: `maxAge` + +Name of the property which olds the expiry timestamp. + + +## Related + +- [expiry-map](https://github.com/SamVerschueren/expiry-map) - A `Map` implementation with expirable items +- [expiry-set](https://github.com/SamVerschueren/expiry-set) - A `Set` implementation with expirable keys +- [mem](https://github.com/sindresorhus/mem) - Memoize functions + + +## License + +MIT © [Sam Verschueren](https://github.com/SamVerschueren) diff --git a/deps/npm/node_modules/mem/index.d.ts b/deps/npm/node_modules/mem/index.d.ts new file mode 100644 index 00000000000000..786625520b2034 --- /dev/null +++ b/deps/npm/node_modules/mem/index.d.ts @@ -0,0 +1,96 @@ +declare namespace mem { + interface CacheStorage { + has(key: KeyType): boolean; + get(key: KeyType): ValueType | undefined; + set(key: KeyType, value: ValueType): void; + delete(key: KeyType): void; + clear?: () => void; + } + + interface Options< + ArgumentsType extends unknown[], + CacheKeyType extends unknown, + ReturnType extends unknown + > { + /** + Milliseconds until the cache expires. + + @default Infinity + */ + readonly maxAge?: number; + + /** + Determines the cache key for storing the result based on the function arguments. By default, if there's only one argument and it's a [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive), it's used directly as a key, otherwise it's all the function arguments JSON stringified as an array. + + You could for example change it to only cache on the first argument `x => JSON.stringify(x)`. + */ + readonly cacheKey?: (...arguments: ArgumentsType) => CacheKeyType; + + /** + Use a different cache storage. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache. + + @default new Map() + */ + readonly cache?: CacheStorage; + + /** + Cache rejected promises. + + @default false + */ + readonly cachePromiseRejection?: boolean; + } +} + +declare const mem: { + /** + [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input. + + @param fn - Function to be memoized. + + @example + ``` + import mem = require('mem'); + + let i = 0; + const counter = () => ++i; + const memoized = mem(counter); + + memoized('foo'); + //=> 1 + + // Cached as it's the same arguments + memoized('foo'); + //=> 1 + + // Not cached anymore as the arguments changed + memoized('bar'); + //=> 2 + + memoized('bar'); + //=> 2 + ``` + */ + < + ArgumentsType extends unknown[], + ReturnType extends unknown, + CacheKeyType extends unknown + >( + fn: (...arguments: ArgumentsType) => ReturnType, + options?: mem.Options + ): (...arguments: ArgumentsType) => ReturnType; + + /** + Clear all cached data of a memoized function. + + @param fn - Memoized function. + */ + clear( + fn: (...arguments: ArgumentsType) => ReturnType + ): void; + + // TODO: Remove this for the next major release + default: typeof mem; +}; + +export = mem; diff --git a/deps/npm/node_modules/mem/index.js b/deps/npm/node_modules/mem/index.js index aa5a0739822c7e..51faf012c2fc44 100644 --- a/deps/npm/node_modules/mem/index.js +++ b/deps/npm/node_modules/mem/index.js @@ -1,51 +1,84 @@ 'use strict'; const mimicFn = require('mimic-fn'); +const isPromise = require('p-is-promise'); +const mapAgeCleaner = require('map-age-cleaner'); const cacheStore = new WeakMap(); -const defaultCacheKey = function (x) { - if (arguments.length === 1 && (x === null || x === undefined || (typeof x !== 'function' && typeof x !== 'object'))) { - return x; +const defaultCacheKey = (...arguments_) => { + if (arguments_.length === 0) { + return '__defaultKey'; } - return JSON.stringify(arguments); + if (arguments_.length === 1) { + const [firstArgument] = arguments_; + if ( + firstArgument === null || + firstArgument === undefined || + (typeof firstArgument !== 'function' && typeof firstArgument !== 'object') + ) { + return firstArgument; + } + } + + return JSON.stringify(arguments_); }; -module.exports = (fn, opts) => { - opts = Object.assign({ +const mem = (fn, options) => { + options = Object.assign({ cacheKey: defaultCacheKey, - cache: new Map() - }, opts); + cache: new Map(), + cachePromiseRejection: false + }, options); + + if (typeof options.maxAge === 'number') { + mapAgeCleaner(options.cache); + } - const memoized = function () { - const cache = cacheStore.get(memoized); - const key = opts.cacheKey.apply(null, arguments); + const {cache} = options; + options.maxAge = options.maxAge || 0; - if (cache.has(key)) { - const c = cache.get(key); + const setData = (key, data) => { + cache.set(key, { + data, + maxAge: Date.now() + options.maxAge + }); + }; + + const memoized = function (...arguments_) { + const key = options.cacheKey(...arguments_); - if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) { - return c.data; - } + if (cache.has(key)) { + return cache.get(key).data; } - const ret = fn.apply(null, arguments); + const cacheItem = fn.call(this, ...arguments_); - cache.set(key, { - data: ret, - maxAge: Date.now() + (opts.maxAge || 0) - }); + setData(key, cacheItem); + + if (isPromise(cacheItem) && options.cachePromiseRejection === false) { + // Remove rejected promises from cache unless `cachePromiseRejection` is set to `true` + cacheItem.catch(() => cache.delete(key)); + } - return ret; + return cacheItem; }; - mimicFn(memoized, fn); + try { + // The below call will throw in some host environments + // See https://github.com/sindresorhus/mimic-fn/issues/10 + mimicFn(memoized, fn); + } catch (_) {} - cacheStore.set(memoized, opts.cache); + cacheStore.set(memoized, options.cache); return memoized; }; +module.exports = mem; +// TODO: Remove this for the next major release +module.exports.default = mem; + module.exports.clear = fn => { const cache = cacheStore.get(fn); diff --git a/deps/npm/node_modules/mem/license b/deps/npm/node_modules/mem/license index 654d0bfe943437..e7af2f77107d73 100644 --- a/deps/npm/node_modules/mem/license +++ b/deps/npm/node_modules/mem/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/mem/node_modules/mimic-fn/index.d.ts b/deps/npm/node_modules/mem/node_modules/mimic-fn/index.d.ts new file mode 100644 index 00000000000000..b4047d58902ebf --- /dev/null +++ b/deps/npm/node_modules/mem/node_modules/mimic-fn/index.d.ts @@ -0,0 +1,54 @@ +declare const mimicFn: { + /** + Make a function mimic another one. It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. + + @param to - Mimicking function. + @param from - Function to mimic. + @returns The modified `to` function. + + @example + ``` + import mimicFn = require('mimic-fn'); + + function foo() {} + foo.unicorn = '🦄'; + + function wrapper() { + return foo(); + } + + console.log(wrapper.name); + //=> 'wrapper' + + mimicFn(wrapper, foo); + + console.log(wrapper.name); + //=> 'foo' + + console.log(wrapper.unicorn); + //=> '🦄' + ``` + */ + < + ArgumentsType extends unknown[], + ReturnType, + FunctionType extends (...arguments: ArgumentsType) => ReturnType + >( + to: (...arguments: ArgumentsType) => ReturnType, + from: FunctionType + ): FunctionType; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function mimicFn< + // ArgumentsType extends unknown[], + // ReturnType, + // FunctionType extends (...arguments: ArgumentsType) => ReturnType + // >( + // to: (...arguments: ArgumentsType) => ReturnType, + // from: FunctionType + // ): FunctionType; + // export = mimicFn; + default: typeof mimicFn; +}; + +export = mimicFn; diff --git a/deps/npm/node_modules/mem/node_modules/mimic-fn/index.js b/deps/npm/node_modules/mem/node_modules/mimic-fn/index.js new file mode 100644 index 00000000000000..1a597051750da2 --- /dev/null +++ b/deps/npm/node_modules/mem/node_modules/mimic-fn/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const mimicFn = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +module.exports = mimicFn; +// TODO: Remove this for the next major release +module.exports.default = mimicFn; diff --git a/deps/npm/node_modules/mem/node_modules/mimic-fn/license b/deps/npm/node_modules/mem/node_modules/mimic-fn/license new file mode 100644 index 00000000000000..e7af2f77107d73 --- /dev/null +++ b/deps/npm/node_modules/mem/node_modules/mimic-fn/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/mimic-fn/package.json b/deps/npm/node_modules/mem/node_modules/mimic-fn/package.json similarity index 59% rename from deps/npm/node_modules/mimic-fn/package.json rename to deps/npm/node_modules/mem/node_modules/mimic-fn/package.json index 4dc1bdae9aa20f..b4970a28d40c8a 100644 --- a/deps/npm/node_modules/mimic-fn/package.json +++ b/deps/npm/node_modules/mem/node_modules/mimic-fn/package.json @@ -1,28 +1,27 @@ { - "_from": "mimic-fn@^1.0.0", - "_id": "mimic-fn@1.2.0", + "_from": "mimic-fn@^2.0.0", + "_id": "mimic-fn@2.1.0", "_inBundle": false, - "_integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", - "_location": "/mimic-fn", + "_integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "_location": "/mem/mimic-fn", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "mimic-fn@^1.0.0", + "raw": "mimic-fn@^2.0.0", "name": "mimic-fn", "escapedName": "mimic-fn", - "rawSpec": "^1.0.0", + "rawSpec": "^2.0.0", "saveSpec": null, - "fetchSpec": "^1.0.0" + "fetchSpec": "^2.0.0" }, "_requiredBy": [ - "/mem", - "/onetime" + "/mem" ], - "_resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "_shasum": "820c86a39334640e99516928bd03fca88057d022", - "_spec": "mimic-fn@^1.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/mem", + "_resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "_shasum": "7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b", + "_spec": "mimic-fn@^2.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/mem", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -35,14 +34,16 @@ "deprecated": false, "description": "Make a function mimic another one", "devDependencies": { - "ava": "*", - "xo": "*" + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" }, "engines": { - "node": ">=4" + "node": ">=6" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "homepage": "https://github.com/sindresorhus/mimic-fn#readme", "keywords": [ @@ -67,7 +68,7 @@ "url": "git+https://github.com/sindresorhus/mimic-fn.git" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd" }, - "version": "1.2.0" + "version": "2.1.0" } diff --git a/deps/npm/node_modules/mimic-fn/readme.md b/deps/npm/node_modules/mem/node_modules/mimic-fn/readme.md similarity index 83% rename from deps/npm/node_modules/mimic-fn/readme.md rename to deps/npm/node_modules/mem/node_modules/mimic-fn/readme.md index e57573438997b1..0ef8a13d7e0d95 100644 --- a/deps/npm/node_modules/mimic-fn/readme.md +++ b/deps/npm/node_modules/mem/node_modules/mimic-fn/readme.md @@ -21,7 +21,7 @@ function foo() {} foo.unicorn = '🦄'; function wrapper() { - return foo() {}; + return foo(); } console.log(wrapper.name); @@ -43,7 +43,7 @@ It will copy over the properties `name`, `length`, `displayName`, and any custom ### mimicFn(to, from) -It will modify `to` and return it. +Modifies the `to` function and returns it. #### to @@ -61,6 +61,7 @@ Function to mimic. ## Related - [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function +- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name, length and other properties ## License diff --git a/deps/npm/node_modules/mem/package.json b/deps/npm/node_modules/mem/package.json index 27eefe8d720d4f..eedf07469c4c3c 100644 --- a/deps/npm/node_modules/mem/package.json +++ b/deps/npm/node_modules/mem/package.json @@ -1,27 +1,27 @@ { - "_from": "mem@^1.1.0", - "_id": "mem@1.1.0", + "_from": "mem@^4.0.0", + "_id": "mem@4.3.0", "_inBundle": false, - "_integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", + "_integrity": "sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==", "_location": "/mem", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "mem@^1.1.0", + "raw": "mem@^4.0.0", "name": "mem", "escapedName": "mem", - "rawSpec": "^1.1.0", + "rawSpec": "^4.0.0", "saveSpec": null, - "fetchSpec": "^1.1.0" + "fetchSpec": "^4.0.0" }, "_requiredBy": [ "/os-locale" ], - "_resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", - "_shasum": "5edd52b485ca1d900fe64895505399a0dfa45f76", - "_spec": "mem@^1.1.0", - "_where": "/Users/rebecca/code/npm/node_modules/os-locale", + "_resolved": "https://registry.npmjs.org/mem/-/mem-4.3.0.tgz", + "_shasum": "461af497bc4ae09608cdb2e60eefb69bff744178", + "_spec": "mem@^4.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -32,20 +32,24 @@ }, "bundleDependencies": false, "dependencies": { - "mimic-fn": "^1.0.0" + "map-age-cleaner": "^0.1.1", + "mimic-fn": "^2.0.0", + "p-is-promise": "^2.0.0" }, "deprecated": false, "description": "Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input", "devDependencies": { - "ava": "*", - "delay": "^1.1.0", - "xo": "*" + "ava": "^1.4.1", + "delay": "^4.1.0", + "tsd": "^0.7.1", + "xo": "^0.24.0" }, "engines": { - "node": ">=4" + "node": ">=6" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "homepage": "https://github.com/sindresorhus/mem#readme", "keywords": [ @@ -68,10 +72,7 @@ "url": "git+https://github.com/sindresorhus/mem.git" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd" }, - "version": "1.1.0", - "xo": { - "esnext": true - } + "version": "4.3.0" } diff --git a/deps/npm/node_modules/mem/readme.md b/deps/npm/node_modules/mem/readme.md index 7ebab84f0e716b..add4222b62d71a 100644 --- a/deps/npm/node_modules/mem/readme.md +++ b/deps/npm/node_modules/mem/readme.md @@ -2,11 +2,13 @@ > [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input +Memory is automatically released when an item expires. + ## Install ``` -$ npm install --save mem +$ npm install mem ``` @@ -22,11 +24,11 @@ const memoized = mem(counter); memoized('foo'); //=> 1 -// cached as it's the same arguments +// Cached as it's the same arguments memoized('foo'); //=> 1 -// not cached anymore as the arguments changed +// Not cached anymore as the arguments changed memoized('bar'); //=> 2 @@ -40,35 +42,37 @@ memoized('bar'); const mem = require('mem'); let i = 0; -const counter = () => Promise.resolve(++i); +const counter = async () => ++i; const memoized = mem(counter); -memoized().then(a => { - console.log(a); +(async () => { + console.log(await memoized()); //=> 1 - memoized().then(b => { - // the return value didn't increase as it's cached - console.log(b); - //=> 1 - }); -}); + // The return value didn't increase as it's cached + console.log(await memoized()); + //=> 1 +})(); ``` ```js const mem = require('mem'); const got = require('got'); +const delay = require('delay'); + const memGot = mem(got, {maxAge: 1000}); -memGot('sindresorhus.com').then(() => { - // this call is cached - memGot('sindresorhus.com').then(() => { - setTimeout(() => { - // this call is not cached as the cache has expired - memGot('sindresorhus.com').then(() => {}); - }, 2000); - }); -}); +(async () => { + await memGot('sindresorhus.com'); + + // This call is cached + await memGot('sindresorhus.com'); + + await delay(2000); + + // This call is not cached as the cache has expired + await memGot('sindresorhus.com'); +})(); ``` @@ -84,6 +88,8 @@ Function to be memoized. #### options +Type: `Object` + ##### maxAge Type: `number`
@@ -104,7 +110,14 @@ You could for example change it to only cache on the first argument `x => JSON.s Type: `Object`
Default: `new Map()` -Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, and optionally `.clear()`. You could for example use a `WeakMap` instead. +Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache. + +##### cachePromiseRejection + +Type: `boolean`
+Default: `false` + +Cache rejected promises. ### mem.clear(fn) @@ -133,15 +146,22 @@ const got = require('got'); const cache = new StatsMap(); const memGot = mem(got, {cache}); -memGot('sindresorhus.com') - .then(() => memGot('sindresorhus.com')) - .then(() => memGot('sindresorhus.com')); +(async () => { + await memGot('sindresorhus.com'); + await memGot('sindresorhus.com'); + await memGot('sindresorhus.com'); -console.log(cache.stats); -//=> {hits: 2, misses: 1} + console.log(cache.stats); + //=> {hits: 2, misses: 1} +})(); ``` +## Related + +- [p-memoize](https://github.com/sindresorhus/p-memoize) - Memoize promise-returning & async functions + + ## License MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/mimic-fn/index.js b/deps/npm/node_modules/mimic-fn/index.js deleted file mode 100644 index 08e69d3d88f020..00000000000000 --- a/deps/npm/node_modules/mimic-fn/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; -module.exports = (to, from) => { - // TODO: use `Reflect.ownKeys()` when targeting Node.js 6 - for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } - - return to; -}; diff --git a/deps/npm/node_modules/nice-try/CHANGELOG.md b/deps/npm/node_modules/nice-try/CHANGELOG.md new file mode 100644 index 00000000000000..9e6baf2fb59be2 --- /dev/null +++ b/deps/npm/node_modules/nice-try/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [1.0.5] - 2018-08-25 + +### Changed + +- Removed `prepublish` script from `package.json` + +## [1.0.4] - 2017-08-08 + +### New + +- Added a changelog + +### Changed + +- Ignore `yarn.lock` and `package-lock.json` files \ No newline at end of file diff --git a/deps/npm/node_modules/nice-try/LICENSE b/deps/npm/node_modules/nice-try/LICENSE new file mode 100644 index 00000000000000..681c8f507b00e7 --- /dev/null +++ b/deps/npm/node_modules/nice-try/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Tobias Reich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/npm/node_modules/nice-try/README.md b/deps/npm/node_modules/nice-try/README.md new file mode 100644 index 00000000000000..5b83b78824a0e5 --- /dev/null +++ b/deps/npm/node_modules/nice-try/README.md @@ -0,0 +1,32 @@ +# nice-try + +[![Travis Build Status](https://travis-ci.org/electerious/nice-try.svg?branch=master)](https://travis-ci.org/electerious/nice-try) [![AppVeyor Status](https://ci.appveyor.com/api/projects/status/8tqb09wrwci3xf8l?svg=true)](https://ci.appveyor.com/project/electerious/nice-try) [![Coverage Status](https://coveralls.io/repos/github/electerious/nice-try/badge.svg?branch=master)](https://coveralls.io/github/electerious/nice-try?branch=master) [![Dependencies](https://david-dm.org/electerious/nice-try.svg)](https://david-dm.org/electerious/nice-try#info=dependencies) [![Greenkeeper badge](https://badges.greenkeeper.io/electerious/nice-try.svg)](https://greenkeeper.io/) + +A function that tries to execute a function and discards any error that occurs. + +## Install + +``` +npm install nice-try +``` + +## Usage + +```js +const niceTry = require('nice-try') + +niceTry(() => JSON.parse('true')) // true +niceTry(() => JSON.parse('truee')) // undefined +niceTry() // undefined +niceTry(true) // undefined +``` + +## API + +### Parameters + +- `fn` `{Function}` Function that might or might not throw an error. + +### Returns + +- `{?*}` Return-value of the function when no error occurred. \ No newline at end of file diff --git a/deps/npm/node_modules/nice-try/package.json b/deps/npm/node_modules/nice-try/package.json new file mode 100644 index 00000000000000..787ce7a7a846e5 --- /dev/null +++ b/deps/npm/node_modules/nice-try/package.json @@ -0,0 +1,65 @@ +{ + "_args": [ + [ + "nice-try@1.0.5", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "nice-try@1.0.5", + "_id": "nice-try@1.0.5", + "_inBundle": false, + "_integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "_location": "/nice-try", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "nice-try@1.0.5", + "name": "nice-try", + "escapedName": "nice-try", + "rawSpec": "1.0.5", + "saveSpec": null, + "fetchSpec": "1.0.5" + }, + "_requiredBy": [ + "/nyc/cross-spawn" + ], + "_resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "_spec": "1.0.5", + "_where": "/Users/mperrotte/npminc/cli", + "authors": [ + "Tobias Reich " + ], + "bugs": { + "url": "https://github.com/electerious/nice-try/issues" + }, + "description": "Tries to execute a function and discards any error that occurs", + "devDependencies": { + "chai": "^4.1.2", + "coveralls": "^3.0.0", + "mocha": "^5.1.1", + "nyc": "^12.0.1" + }, + "files": [ + "src" + ], + "homepage": "https://github.com/electerious/nice-try", + "keywords": [ + "try", + "catch", + "error" + ], + "license": "MIT", + "main": "src/index.js", + "name": "nice-try", + "repository": { + "type": "git", + "url": "git+https://github.com/electerious/nice-try.git" + }, + "scripts": { + "coveralls": "nyc report --reporter=text-lcov | coveralls", + "test": "nyc node_modules/mocha/bin/_mocha" + }, + "version": "1.0.5" +} diff --git a/deps/npm/node_modules/nice-try/src/index.js b/deps/npm/node_modules/nice-try/src/index.js new file mode 100644 index 00000000000000..837506f2cc2db3 --- /dev/null +++ b/deps/npm/node_modules/nice-try/src/index.js @@ -0,0 +1,12 @@ +'use strict' + +/** + * Tries to execute a function and discards any error that occurs. + * @param {Function} fn - Function that might or might not throw an error. + * @returns {?*} Return-value of the function when no error occurred. + */ +module.exports = function(fn) { + + try { return fn() } catch (e) {} + +} \ No newline at end of file diff --git a/deps/npm/node_modules/node-gyp/.travis.yml b/deps/npm/node_modules/node-gyp/.travis.yml index cf0ea43fff2d6d..e43ba548fb784b 100644 --- a/deps/npm/node_modules/node-gyp/.travis.yml +++ b/deps/npm/node_modules/node-gyp/.travis.yml @@ -8,7 +8,7 @@ matrix: python: 2.7 - name: "Python 2.7 on macOS" os: osx - osx_image: xcode11 + osx_image: xcode11.2 language: shell # 'language: python' is not yet supported on macOS env: NODE_GYP_FORCE_PYTHON=python2 before_install: HOMEBREW_NO_AUTO_UPDATE=1 brew install npm @@ -29,16 +29,16 @@ matrix: NODE_GYP_FORCE_PYTHON=/c/Python27/python.exe before_install: choco install python2 - - name: "Node.js 6 & Python 3.7 on Linux" - python: 3.7 + - name: "Node.js 6 & Python 3.8 on Linux" + python: 3.8 env: NODE_GYP_FORCE_PYTHON=python3 before_install: nvm install 6 - - name: "Node.js 8 & Python 3.7 on Linux" - python: 3.7 + - name: "Node.js 8 & Python 3.8 on Linux" + python: 3.8 env: NODE_GYP_FORCE_PYTHON=python3 before_install: nvm install 8 - - name: "Node.js 10 & Python 3.7 on Linux" - python: 3.7 + - name: "Node.js 10 & Python 3.8 on Linux" + python: 3.8 env: NODE_GYP_FORCE_PYTHON=python3 before_install: nvm install 10 - name: "Node.js 12 & Python 3.5 on Linux" @@ -53,12 +53,17 @@ matrix: python: 3.7 env: NODE_GYP_FORCE_PYTHON=python3 before_install: nvm install 12 + - name: "Node.js 12 & Python 3.8 on Linux" + python: 3.8 + env: NODE_GYP_FORCE_PYTHON=python3 + before_install: nvm install 12 + - name: "Python 3.7 on macOS" os: osx - #osx_image: xcode11 + osx_image: xcode11.2 language: shell # 'language: python' is not yet supported on macOS env: NODE_GYP_FORCE_PYTHON=python3 - before_install: HOMEBREW_NO_AUTO_UPDATE=1 brew install npm + before_install: HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade npm || true - name: "Node.js 12 & Python 3.7 on Windows" os: windows language: node_js @@ -66,11 +71,19 @@ matrix: env: >- PATH=/c/Python37:/c/Python37/Scripts:$PATH NODE_GYP_FORCE_PYTHON=/c/Python37/python.exe + before_install: choco install python --version=3.7.4 + - name: "Node.js 12 & Python 3.8 on Windows" + os: windows + language: node_js + node_js: 12 # node + env: >- + PATH=/c/Python38:/c/Python38/Scripts:$PATH + NODE_GYP_FORCE_PYTHON=/c/Python38/python.exe before_install: choco install python install: #- pip install -r requirements.txt - - pip install flake8 # pytest # add another testing frameworks later + - pip install --upgrade flake8 pytest==4.6.6 # pytest 5 no longer supports legacy Python before_script: - flake8 --version # stop the build if there are Python syntax errors or undefined names @@ -82,7 +95,7 @@ before_script: script: - node -e 'require("npmlog").level="verbose"; require("./lib/find-python")(null,()=>{})' - npm test - #- pytest --capture=sys # add other tests here + - GYP_MSVS_VERSION=2015 GYP_MSVS_OVERRIDE_PATH="C:\\Dummy" pytest notifications: on_success: change on_failure: change # `always` will be the setting once code changes slow down diff --git a/deps/npm/node_modules/node-gyp/CHANGELOG.md b/deps/npm/node_modules/node-gyp/CHANGELOG.md index ecc51b360dd183..28f523779841de 100644 --- a/deps/npm/node_modules/node-gyp/CHANGELOG.md +++ b/deps/npm/node_modules/node-gyp/CHANGELOG.md @@ -1,3 +1,30 @@ +v5.0.7 2019-12-16 +================= + +Republish of v5.0.6 with unnecessary tarball removed from pack file. + +v5.0.6 2019-12-16 +================= + +* [[`cdec00286f`](https://github.com/nodejs/node-gyp/commit/cdec00286f)] - **doc**: adjustments to the README.md for new users (Dan Pike) [#1919](https://github.com/nodejs/node-gyp/pull/1919) +* [[`b7c8233ef2`](https://github.com/nodejs/node-gyp/commit/b7c8233ef2)] - **test**: fix Python unittests (cclauss) [#1961](https://github.com/nodejs/node-gyp/pull/1961) +* [[`e12b00ab0a`](https://github.com/nodejs/node-gyp/commit/e12b00ab0a)] - **doc**: macOS Catalina add two commands (Christian Clauss) [#1962](https://github.com/nodejs/node-gyp/pull/1962) +* [[`70b9890c0d`](https://github.com/nodejs/node-gyp/commit/70b9890c0d)] - **test**: add header download test (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796) +* [[`4029fa8629`](https://github.com/nodejs/node-gyp/commit/4029fa8629)] - **test**: configure proper devDir for invoking configure() (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796) +* [[`fe8b02cc8b`](https://github.com/nodejs/node-gyp/commit/fe8b02cc8b)] - **doc**: add macOS\_Catalina.md document (cclauss) [#1940](https://github.com/nodejs/node-gyp/pull/1940) +* [[`8ea47ce365`](https://github.com/nodejs/node-gyp/commit/8ea47ce365)] - **gyp**: python3 fixes: utf8 decode, use of 'None' in eval (Wilfried Goesgens) [#1925](https://github.com/nodejs/node-gyp/pull/1925) +* [[`c7229716ba`](https://github.com/nodejs/node-gyp/commit/c7229716ba)] - **gyp**: iteritems() -\> items() in compile\_commands\_json.py (cclauss) [#1947](https://github.com/nodejs/node-gyp/pull/1947) +* [[`2a18b2a0f8`](https://github.com/nodejs/node-gyp/commit/2a18b2a0f8)] - **gyp**: make cmake python3 compatible (gengjiawen) [#1944](https://github.com/nodejs/node-gyp/pull/1944) +* [[`70f391e844`](https://github.com/nodejs/node-gyp/commit/70f391e844)] - **gyp**: fix TypeError in XcodeVersion() (Christian Clauss) [#1939](https://github.com/nodejs/node-gyp/pull/1939) +* [[`9f4f0fa34e`](https://github.com/nodejs/node-gyp/commit/9f4f0fa34e)] - **gyp**: finish decode stdout on Python 3 (Christian Clauss) [#1937](https://github.com/nodejs/node-gyp/pull/1937) +* [[`7cf507906d`](https://github.com/nodejs/node-gyp/commit/7cf507906d)] - **src,win**: allow 403 errors for arm64 node.lib (Richard Lau) [#1934](https://github.com/nodejs/node-gyp/pull/1934) +* [[`ad0d182c01`](https://github.com/nodejs/node-gyp/commit/ad0d182c01)] - **deps**: update deps to roughly match current npm@6 (Rod Vagg) [#1920](https://github.com/nodejs/node-gyp/pull/1920) +* [[`1553081ed6`](https://github.com/nodejs/node-gyp/commit/1553081ed6)] - **test**: upgrade Linux Travis CI to Python 3.8 (Christian Clauss) [#1923](https://github.com/nodejs/node-gyp/pull/1923) +* [[`0705cae9aa`](https://github.com/nodejs/node-gyp/commit/0705cae9aa)] - **travis**: ignore failed `brew upgrade npm`, update xcode (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932) +* [[`7bfdb6f5bf`](https://github.com/nodejs/node-gyp/commit/7bfdb6f5bf)] - **build**: avoid bare exceptions in xcode\_emulation.py (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932) +* [[`7edf7658fa`](https://github.com/nodejs/node-gyp/commit/7edf7658fa)] - **lib,install**: always download SHA sums on Windows (Sam Hughes) [#1926](https://github.com/nodejs/node-gyp/pull/1926) +* [[`69056d04fe`](https://github.com/nodejs/node-gyp/commit/69056d04fe)] - **travis**: add Windows + Python 3.8 to the mix (Rod Vagg) [#1921](https://github.com/nodejs/node-gyp/pull/1921) + v5.0.5 2019-10-04 ================= diff --git a/deps/npm/node_modules/node-gyp/README.md b/deps/npm/node_modules/node-gyp/README.md index d3930a253d4d1c..e39c5de8ea0453 100644 --- a/deps/npm/node_modules/node-gyp/README.md +++ b/deps/npm/node_modules/node-gyp/README.md @@ -3,8 +3,7 @@ `node-gyp` is a cross-platform command-line tool written in Node.js for compiling native addon modules for Node.js. It contains a fork of the [gyp](https://gyp.gsrc.io) project that was previously used by the Chromium -team and takes away the pain of dealing with the various differences in build -platforms. +team, extended to support the development of Node.js native addons. Note that `node-gyp` is _not_ used to build Node.js itself. @@ -14,23 +13,18 @@ etc.), regardless of what version of Node.js is actually installed on your syste ## Features - * Easy to use, consistent interface - * Same commands to build your module on every platform - * Supports multiple target versions of Node.js + * The same build commands work on any of the supported platforms + * Supports the targetting of different versions of Node.js ## Installation -You can install with `npm`: +You can install `node-gyp` using `npm`: ``` bash $ npm install -g node-gyp ``` -You will also need to install: - -NOTE: node-gyp is compatible with Python v2.7, v3.5, v3.6, or v3.7. If the -Python to use is not explicitly configured (see "Configuring Python Dependency" -below) it will attempt to find a compatible Python executable. +Depending on your operating system, you will need to install: ### On Unix @@ -43,6 +37,7 @@ below) it will attempt to find a compatible Python executable. * Python v2.7, v3.5, v3.6, or v3.7 * [Xcode](https://developer.apple.com/xcode/download/) * You also need to install the `XCode Command Line Tools` by running `xcode-select --install`. Alternatively, if you already have the full Xcode installed, you can find them under the menu `Xcode -> Open Developer Tool -> More Developer Tools...`. This step will install `clang`, `clang++`, and `make`. + * If your Mac has been _upgraded_ to macOS Catalina (10.15), please read [macOS_Catalina.md](macOS_Catalina.md). ### On Windows @@ -66,14 +61,17 @@ Install tools and configuration manually: ### Configuring Python Dependency -If you have multiple Python versions installed, you can identify which Python -version `node-gyp` uses by setting the `--python` variable: +`node-gyp` requires that you have installed a compatible version of Python, one of: v2.7, v3.5, v3.6, +or v3.7. If you have multiple Python versions installed, you can identify which Python +version `node-gyp` should use in one of the following ways: + +1. by setting the `--python` command-line option, e.g.: ``` bash $ node-gyp --python /path/to/executable/python ``` -If `node-gyp` is called by way of `npm`, *and* you have multiple versions of +2. If `node-gyp` is called by way of `npm`, *and* you have multiple versions of Python installed, then you can set `npm`'s 'python' config key to the appropriate value: @@ -81,12 +79,12 @@ value: $ npm config set python /path/to/executable/python ``` -If the `PYTHON` environment variable is set to the path of a Python executable, -it will be used if it is a compatible Python. +3. If the `PYTHON` environment variable is set to the path of a Python executable, +then that version will be used, if it is a compatible version. -If the `NODE_GYP_FORCE_PYTHON` environment variable is set to the path of a +4. If the `NODE_GYP_FORCE_PYTHON` environment variable is set to the path of a Python executable, it will be used instead of any of the other configured or -builtin Python search paths. If its not a compatible Python, no further +builtin Python search paths. If it's not a compatible version, no further searching will be done. ## How to Use @@ -146,7 +144,9 @@ A barebones `gyp` file appropriate for building a Node.js addon could look like: } ``` -Some additional resources for addons and writing `gyp` files: +## Further reading + +Some additional resources for Node.js native addons and writing `gyp` configuration files: * ["Going Native" a nodeschool.io tutorial](http://nodeschool.io/#goingnative) * ["Hello World" node addon example](https://github.com/nodejs/node/tree/master/test/addons/hello-world) @@ -154,7 +154,6 @@ Some additional resources for addons and writing `gyp` files: * [gyp input format reference](https://gyp.gsrc.io/docs/InputFormatReference.md) * [*"binding.gyp" files out in the wild* wiki page](https://github.com/nodejs/node-gyp/wiki/%22binding.gyp%22-files-out-in-the-wild) - ## Commands `node-gyp` responds to the following commands: diff --git a/deps/npm/node_modules/node-gyp/gyp/gyp_main.py b/deps/npm/node_modules/node-gyp/gyp/gyp_main.py index aece53c8eb3b05..f738e8009f71e7 100755 --- a/deps/npm/node_modules/node-gyp/gyp/gyp_main.py +++ b/deps/npm/node_modules/node-gyp/gyp/gyp_main.py @@ -31,7 +31,7 @@ def UnixifyPath(path): out = subprocess.Popen(["cygpath", "-u", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - stdout, stderr = out.communicate() + stdout, _ = out.communicate() if PY3: stdout = stdout.decode("utf-8") return str(stdout) diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py index c082bbea9b41da..ce71c38a9b94fa 100755 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py @@ -1085,6 +1085,7 @@ def testConvertToMSBuildSettings_full_synthetic(self): 'GenerateManifest': 'true', 'IgnoreImportLibrary': 'true', 'LinkIncremental': 'false'}} + self.maxDiff = 9999 # on failure display a long diff actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) @@ -1476,6 +1477,7 @@ def testConvertToMSBuildSettings_actual(self): 'ResourceOutputFileName': '$(IntDir)$(TargetFileName).embed.manifest.resfdsf'} } + self.maxDiff = 9999 # on failure display a long diff actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py index 13d9777f0e1acc..c7cf68d3a1ba90 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py @@ -12,6 +12,8 @@ import gyp import glob +PY3 = bytes != str + class VisualStudioVersion(object): """Information regarding a version of Visual Studio.""" @@ -132,6 +134,8 @@ def _RegistryQueryBase(sysdir, key, value): # Obtain the stdout from reg.exe, reading to the end so p.returncode is valid # Note that the error text may be in [1] in some cases text = p.communicate()[0] + if PY3: + text = text.decode('utf-8') # Check return code from reg.exe; officially 0==success and 1==error if p.returncode: return None @@ -334,6 +338,8 @@ def _ConvertToCygpath(path): if sys.platform == 'cygwin': p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE) path = p.communicate()[0].strip() + if PY3: + path = path.decode('utf-8') return path diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py index 071ad7e242c2e2..d866e81d40b0a4 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import collections import errno import filecmp import os.path @@ -11,6 +10,11 @@ import sys import subprocess +try: + from collections.abc import MutableSet +except ImportError: + from collections import MutableSet + PY3 = bytes != str @@ -496,7 +500,7 @@ def uniquer(seq, idfun=None): # Based on http://code.activestate.com/recipes/576694/. -class OrderedSet(collections.MutableSet): +class OrderedSet(MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py index 996b6f25fdb014..5601a6657e3d03 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py @@ -239,7 +239,10 @@ def StringToCMakeTargetName(a): Invalid for make: ':' Invalid for unknown reasons but cause failures: '.' """ - return a.translate(string.maketrans(' /():."', '_______')) + try: + return a.translate(str.maketrans(' /():."', '_______')) + except AttributeError: + return a.translate(string.maketrans(' /():."', '_______')) def WriteActions(target_name, actions, extra_sources, extra_deps, diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py index 575db63c4e1943..1b8490451f9793 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py @@ -43,7 +43,7 @@ def CalculateVariables(default_variables, params): def AddCommandsForTarget(cwd, target, params, per_config_commands): output_dir = params['generator_flags']['output_dir'] - for configuration_name, configuration in target['configurations'].iteritems(): + for configuration_name, configuration in target['configurations'].items(): builddir_name = os.path.join(output_dir, configuration_name) if IsMac(params): @@ -92,7 +92,7 @@ def resolve(filename): def GenerateOutput(target_list, target_dicts, data, params): per_config_commands = {} - for qualified_target, target in target_dicts.iteritems(): + for qualified_target, target in target_dicts.items(): build_file, target_name, toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) if IsMac(params): @@ -102,7 +102,7 @@ def GenerateOutput(target_list, target_dicts, data, params): AddCommandsForTarget(cwd, target, params, per_config_commands) output_dir = params['generator_flags']['output_dir'] - for configuration_name, commands in per_config_commands.iteritems(): + for configuration_name, commands in per_config_commands.items(): filename = os.path.join(output_dir, configuration_name, 'compile_commands.json') diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py index 6b49ad6760051e..91f187d685ad51 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py @@ -26,6 +26,8 @@ import shlex import xml.etree.cElementTree as ET +PY3 = bytes != str + generator_wants_static_library_dependencies_adjusted = False generator_default_variables = { @@ -97,6 +99,8 @@ def GetAllIncludeDirectories(target_list, target_dicts, proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] + if PY3: + output = output.decode('utf-8') # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: @@ -234,6 +238,8 @@ def GetAllDefines(target_list, target_dicts, data, config_name, params, cpp_proc = subprocess.Popen(args=command, cwd='.', stdin=subprocess.PIPE, stdout=subprocess.PIPE) cpp_output = cpp_proc.communicate()[0] + if PY3: + cpp_output = cpp_output.decode('utf-8') cpp_lines = cpp_output.split('\n') for cpp_line in cpp_lines: if not cpp_line.strip(): diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py index bdf7134537022f..196053679492f2 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py @@ -1776,7 +1776,7 @@ def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. - cmddigest = hashlib.sha1(command if command else self.target).hexdigest() + cmddigest = hashlib.sha1((command or self.target).encode('utf-8')).hexdigest() intermediate = "%s.intermediate" % cmddigest self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:') diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py index b3b4bc105366eb..8dbe0dc05b86b6 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py @@ -12,6 +12,8 @@ import subprocess import sys +from collections import OrderedDict + import gyp.common import gyp.easy_xml as easy_xml import gyp.generator.ninja as ninja_generator @@ -25,15 +27,7 @@ from gyp.common import GypError from gyp.common import OrderedSet -# TODO: Remove once bots are on 2.7, http://crbug.com/241769 -def _import_OrderedDict(): - import collections - try: - return collections.OrderedDict - except AttributeError: - import gyp.ordered_dict - return gyp.ordered_dict.OrderedDict -OrderedDict = _import_OrderedDict() +PY3 = bytes != str # Regular expression for validating Visual Studio GUIDs. If the GUID @@ -124,6 +118,8 @@ def _GetDomainAndUserName(): call = subprocess.Popen(['net', 'config', 'Workstation'], stdout=subprocess.PIPE) config = call.communicate()[0] + if PY3: + config = config.decode('utf-8') username_re = re.compile(r'^User name\s+(\S+)', re.MULTILINE) username_match = username_re.search(config) if username_match: @@ -175,7 +171,7 @@ def _FixPath(path): def _IsWindowsAbsPath(path): - """ + r""" On Cygwin systems Python needs a little help determining if a path is an absolute Windows path or not, so that it does not treat those as relative, which results in bad paths like: diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py index 1ad68e4fc9f072..5ecfbdf004d211 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py @@ -9,7 +9,6 @@ import gyp.generator.ninja as ninja import unittest import sys -import TestCommon class TestPrefixesAndSuffixes(unittest.TestCase): diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py index aba81cf6542e01..2973c078fc82b7 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py @@ -22,6 +22,7 @@ from gyp.common import GypError from gyp.common import OrderedSet +PY3 = bytes != str # A list of types that are treated as linkable. linkable_types = [ @@ -239,7 +240,7 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, if check: build_file_data = CheckedEval(build_file_contents) else: - build_file_data = eval(build_file_contents, {'__builtins__': None}, + build_file_data = eval(build_file_contents, {'__builtins__': {}}, None) except SyntaxError as e: e.filename = build_file_path @@ -909,6 +910,9 @@ def ExpandVariables(input, phase, variables, build_file): (e, contents, build_file)) p_stdout, p_stderr = p.communicate('') + if PY3: + p_stdout = p_stdout.decode('utf-8') + p_stderr = p_stderr.decode('utf-8') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) @@ -1090,7 +1094,7 @@ def EvalSingleCondition( else: ast_code = compile(cond_expr_expanded, '', 'eval') cached_conditions_asts[cond_expr_expanded] = ast_code - if eval(ast_code, {'__builtins__': None}, variables): + if eval(ast_code, {'__builtins__': {}}, variables): return true_dict return false_dict except SyntaxError as e: diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py index b8b7344eff85bf..222befb982a9d4 100755 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py @@ -23,6 +23,8 @@ import sys import tempfile +PY3 = bytes != str + def main(args): executor = MacTool() @@ -243,6 +245,8 @@ def ExecFilterLibtool(self, *cmd_list): env['ZERO_AR_DATE'] = '1' libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) _, err = libtoolout.communicate() + if PY3: + err = err.decode('utf-8') for line in err.splitlines(): if not libtool_re.match(line) and not libtool_re5.match(line): print(line, file=sys.stderr) diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py index 9d50bad1f558c7..9f1f547b907751 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py @@ -16,6 +16,7 @@ import gyp.MSVSUtil import gyp.MSVSVersion +PY3 = bytes != str windows_quoter_regex = re.compile(r'(\\*)"') @@ -126,7 +127,10 @@ def _FindDirectXInstallation(): # Setup params to pass to and attempt to launch reg.exe. cmd = ['reg.exe', 'query', r'HKLM\Software\Microsoft\DirectX', '/s'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - for line in p.communicate()[0].splitlines(): + stdout = p.communicate()[0] + if PY3: + stdout = stdout.decode('utf-8') + for line in stdout.splitlines(): if 'InstallPath' in line: dxsdk_dir = line.split(' ')[3] + "\\" @@ -1038,6 +1042,8 @@ def GenerateEnvironmentFiles(toplevel_build_dir, generator_flags, popen = subprocess.Popen( args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) variables, _ = popen.communicate() + if PY3: + variables = variables.decode('utf-8') env = _ExtractImportantEnvironment(variables) # Inject system includes from gyp files into INCLUDE. @@ -1057,6 +1063,8 @@ def GenerateEnvironmentFiles(toplevel_build_dir, generator_flags, 'for', '%i', 'in', '(cl.exe)', 'do', '@echo', 'LOC:%~$PATH:i')) popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) output, _ = popen.communicate() + if PY3: + output = output.decode('utf-8') cl_paths[arch] = _ExtractCLPath(output) return cl_paths diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py deleted file mode 100644 index 6fe9c1f6c7c22b..00000000000000 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py +++ /dev/null @@ -1,289 +0,0 @@ -# Unmodified from http://code.activestate.com/recipes/576693/ -# other than to add MIT license header (as specified on page, but not in code). -# Linked from Python documentation here: -# http://docs.python.org/2/library/collections.html#collections.OrderedDict -# -# This should be deleted once Py2.7 is available on all bots, see -# http://crbug.com/241769. -# -# Copyright (c) 2009 Raymond Hettinger. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. -# Passes Python2.7's test suite and incorporates all the latest updates. - -try: - from thread import get_ident as _get_ident -except ImportError: - from dummy_thread import get_ident as _get_ident - -try: - from _abcoll import KeysView, ValuesView, ItemsView -except ImportError: - pass - - -class OrderedDict(dict): - 'Dictionary that remembers insertion order' - # An inherited dict maps keys to values. - # The inherited dict provides __getitem__, __len__, __contains__, and get. - # The remaining methods are order-aware. - # Big-O running times for all methods are the same as for regular dictionaries. - - # The internal self.__map dictionary maps keys to links in a doubly linked list. - # The circular doubly linked list starts and ends with a sentinel element. - # The sentinel element never gets deleted (this simplifies the algorithm). - # Each link is stored as a list of length three: [PREV, NEXT, KEY]. - - def __init__(self, *args, **kwds): - '''Initialize an ordered dictionary. Signature is the same as for - regular dictionaries, but keyword arguments are not recommended - because their insertion order is arbitrary. - - ''' - if len(args) > 1: - raise TypeError('expected at most 1 arguments, got %d' % len(args)) - try: - self.__root - except AttributeError: - self.__root = root = [] # sentinel node - root[:] = [root, root, None] - self.__map = {} - self.__update(*args, **kwds) - - def __setitem__(self, key, value, dict_setitem=dict.__setitem__): - 'od.__setitem__(i, y) <==> od[i]=y' - # Setting a new item creates a new link which goes at the end of the linked - # list, and the inherited dictionary is updated with the new key/value pair. - if key not in self: - root = self.__root - last = root[0] - last[1] = root[0] = self.__map[key] = [last, root, key] - dict_setitem(self, key, value) - - def __delitem__(self, key, dict_delitem=dict.__delitem__): - 'od.__delitem__(y) <==> del od[y]' - # Deleting an existing item uses self.__map to find the link which is - # then removed by updating the links in the predecessor and successor nodes. - dict_delitem(self, key) - link_prev, link_next, key = self.__map.pop(key) - link_prev[1] = link_next - link_next[0] = link_prev - - def __iter__(self): - 'od.__iter__() <==> iter(od)' - root = self.__root - curr = root[1] - while curr is not root: - yield curr[2] - curr = curr[1] - - def __reversed__(self): - 'od.__reversed__() <==> reversed(od)' - root = self.__root - curr = root[0] - while curr is not root: - yield curr[2] - curr = curr[0] - - def clear(self): - 'od.clear() -> None. Remove all items from od.' - try: - for node in self.__map.itervalues(): - del node[:] - root = self.__root - root[:] = [root, root, None] - self.__map.clear() - except AttributeError: - pass - dict.clear(self) - - def popitem(self, last=True): - '''od.popitem() -> (k, v), return and remove a (key, value) pair. - Pairs are returned in LIFO order if last is true or FIFO order if false. - - ''' - if not self: - raise KeyError('dictionary is empty') - root = self.__root - if last: - link = root[0] - link_prev = link[0] - link_prev[1] = root - root[0] = link_prev - else: - link = root[1] - link_next = link[1] - root[1] = link_next - link_next[0] = root - key = link[2] - del self.__map[key] - value = dict.pop(self, key) - return key, value - - # -- the following methods do not depend on the internal structure -- - - def keys(self): - 'od.keys() -> list of keys in od' - return list(self) - - def values(self): - 'od.values() -> list of values in od' - return [self[key] for key in self] - - def items(self): - 'od.items() -> list of (key, value) pairs in od' - return [(key, self[key]) for key in self] - - def iterkeys(self): - 'od.iterkeys() -> an iterator over the keys in od' - return iter(self) - - def itervalues(self): - 'od.itervalues -> an iterator over the values in od' - for k in self: - yield self[k] - - def items(self): - 'od.items -> an iterator over the (key, value) items in od' - for k in self: - yield (k, self[k]) - - # Suppress 'OrderedDict.update: Method has no argument': - # pylint: disable=E0211 - def update(*args, **kwds): - '''od.update(E, **F) -> None. Update od from dict/iterable E and F. - - If E is a dict instance, does: for k in E: od[k] = E[k] - If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] - Or if E is an iterable of items, does: for k, v in E: od[k] = v - In either case, this is followed by: for k, v in F.items(): od[k] = v - - ''' - if len(args) > 2: - raise TypeError('update() takes at most 2 positional ' - 'arguments (%d given)' % (len(args),)) - elif not args: - raise TypeError('update() takes at least 1 argument (0 given)') - self = args[0] - # Make progressively weaker assumptions about "other" - other = () - if len(args) == 2: - other = args[1] - if isinstance(other, dict): - for key in other: - self[key] = other[key] - elif hasattr(other, 'keys'): - for key in other.keys(): - self[key] = other[key] - else: - for key, value in other: - self[key] = value - for key, value in kwds.items(): - self[key] = value - - __update = update # let subclasses override update without breaking __init__ - - __marker = object() - - def pop(self, key, default=__marker): - '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. - If key is not found, d is returned if given, otherwise KeyError is raised. - - ''' - if key in self: - result = self[key] - del self[key] - return result - if default is self.__marker: - raise KeyError(key) - return default - - def setdefault(self, key, default=None): - 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' - if key in self: - return self[key] - self[key] = default - return default - - def __repr__(self, _repr_running={}): - 'od.__repr__() <==> repr(od)' - call_key = id(self), _get_ident() - if call_key in _repr_running: - return '...' - _repr_running[call_key] = 1 - try: - if not self: - return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) - finally: - del _repr_running[call_key] - - def __reduce__(self): - 'Return state information for pickling' - items = [[k, self[k]] for k in self] - inst_dict = vars(self).copy() - for k in vars(OrderedDict()): - inst_dict.pop(k, None) - if inst_dict: - return (self.__class__, (items,), inst_dict) - return self.__class__, (items,) - - def copy(self): - 'od.copy() -> a shallow copy of od' - return self.__class__(self) - - @classmethod - def fromkeys(cls, iterable, value=None): - '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S - and values equal to v (which defaults to None). - - ''' - d = cls() - for key in iterable: - d[key] = value - return d - - def __eq__(self, other): - '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive - while comparison to a regular mapping is order-insensitive. - - ''' - if isinstance(other, OrderedDict): - return len(self)==len(other) and self.items() == other.items() - return dict.__eq__(self, other) - - def __ne__(self, other): - return not self == other - - # -- the following methods are only used in Python 2.7 -- - - def viewkeys(self): - "od.viewkeys() -> a set-like object providing a view on od's keys" - return KeysView(self) - - def viewvalues(self): - "od.viewvalues() -> an object providing a view on od's values" - return ValuesView(self) - - def viewitems(self): - "od.viewitems() -> a set-like object providing a view on od's items" - return ItemsView(self) - diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py index bca0b9e346a5ba..0a6daf203931e6 100755 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py @@ -20,6 +20,7 @@ import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +PY3 = bytes != str # A regex matching an argument corresponding to the output filename passed to # link.exe. @@ -124,6 +125,8 @@ def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args): stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = link.communicate() + if PY3: + out = out.decode('utf-8') for line in out.splitlines(): if (not line.startswith(' Creating library ') and not line.startswith('Generating code') and @@ -215,6 +218,8 @@ def ExecManifestWrapper(self, arch, *args): popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() + if PY3: + out = out.decode('utf-8') for line in out.splitlines(): if line and 'manifest authoring warning 81010002' not in line: print(line) @@ -247,6 +252,8 @@ def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() + if PY3: + out = out.decode('utf-8') # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl @@ -266,6 +273,8 @@ def ExecAsmWrapper(self, arch, *args): popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() + if PY3: + out = out.decode('utf-8') for line in out.splitlines(): if (not line.startswith('Copyright (C) Microsoft Corporation') and not line.startswith('Microsoft (R) Macro Assembler') and @@ -281,6 +290,8 @@ def ExecRcWrapper(self, arch, *args): popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() + if PY3: + out = out.decode('utf-8') for line in out.splitlines(): if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and not line.startswith('Copyright (C) Microsoft Corporation') and diff --git a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py index 74735c033a90b1..60171649900aae 100644 --- a/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +++ b/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py @@ -437,7 +437,7 @@ def _GetSdkVersionInfoItem(self, sdk, infoitem): # most sensible route and should still do the right thing. try: return GetStdoutQuiet(['xcodebuild', '-version', '-sdk', sdk, infoitem]) - except: + except GypError: pass def _SdkRoot(self, configname): @@ -855,7 +855,8 @@ def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): # These flags reflect the compilation options used by xcode to compile # extensions. ldflags.append('-lpkstart') - if XcodeVersion() < '0900': + xcode_version, _ = XcodeVersion() + if xcode_version < '0900': ldflags.append(sdk_root + '/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit') ldflags.append('-fapplication-extension') @@ -1088,15 +1089,15 @@ def GetExtraPlistItems(self, configname=None): cache = {} cache['BuildMachineOSBuild'] = self._BuildMachineOSBuild() - xcode, xcode_build = XcodeVersion() - cache['DTXcode'] = xcode + xcode_version, xcode_build = XcodeVersion() + cache['DTXcode'] = xcode_version cache['DTXcodeBuild'] = xcode_build sdk_root = self._SdkRoot(configname) if not sdk_root: sdk_root = self._DefaultSdkRoot() cache['DTSDKName'] = sdk_root - if xcode >= '0430': + if xcode_version >= '0430': cache['DTSDKBuild'] = self._GetSdkVersionInfoItem( sdk_root, 'ProductBuildVersion') else: @@ -1126,7 +1127,7 @@ def _DefaultSdkRoot(self): project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed. """ - xcode_version, xcode_build = XcodeVersion() + xcode_version, _ = XcodeVersion() if xcode_version < '0500': return '' default_sdk_path = self._XcodeSdkPath('') @@ -1135,7 +1136,7 @@ def _DefaultSdkRoot(self): return default_sdk_root try: all_sdks = GetStdout(['xcodebuild', '-showsdks']) - except: + except GypError: # If xcodebuild fails, there will be no valid SDKs return '' for line in all_sdks.splitlines(): @@ -1263,10 +1264,12 @@ def XcodeVersion(): # Xcode 3.2.6 # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0 # BuildVersion: 10M2518 - # Convert that to '0463', '4H1503'. + # Convert that to ('0463', '4H1503') or ('0326', '10M2518'). global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE + version = "" + build = "" try: version_list = GetStdoutQuiet(['xcodebuild', '-version']).splitlines() # In some circumstances xcodebuild exits 0 but doesn't return @@ -1276,21 +1279,16 @@ def XcodeVersion(): # checking that version. if len(version_list) < 2: raise GypError("xcodebuild returned unexpected results") - except: - version = CLTVersion() - if version: - version = ".".join(version.split(".")[:3]) - else: + version = version_list[0].split()[-1] # Last word on first line + build = version_list[-1].split()[-1] # Last word on last line + except GypError: # Xcode not installed so look for XCode Command Line Tools + version = CLTVersion() # macOS Catalina returns 11.0.0.0.1.1567737322 + if not version: raise GypError("No Xcode or CLT version detected!") - # The CLT has no build information, so we return an empty string. - version_list = [version, ''] - version = version_list[0] - build = version_list[-1] - # Be careful to convert "4.2" to "0420" and "10.0" to "1000": - version = format(''.join((version.split()[-1].split('.') + ['0', '0'])[:3]), - '>04s') - if build: - build = build.split()[-1] + # Be careful to convert "4.2.3" to "0423" and "11.0.0" to "1100": + version = version.split(".")[:3] # Just major, minor, micro + version[0] = version[0].zfill(2) # Add a leading zero if major is one digit + version = ("".join(version) + "00")[:4] # Limit to exactly four characters XCODE_VERSION_CACHE = (version, build) return XCODE_VERSION_CACHE @@ -1314,7 +1312,7 @@ def CLTVersion(): try: output = GetStdout(['/usr/sbin/pkgutil', '--pkg-info', key]) return re.search(regex, output).groupdict()['version'] - except: + except GypError: continue @@ -1524,7 +1522,8 @@ def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env['DYLIB_INSTALL_NAME_BASE'] = install_name_base - if XcodeVersion() >= '0500' and not env.get('SDKROOT'): + xcode_version, _ = XcodeVersion() + if xcode_version >= '0500' and not env.get('SDKROOT'): sdk_root = xcode_settings._SdkRoot(configuration) if not sdk_root: sdk_root = xcode_settings._XcodeSdkPath('') diff --git a/deps/npm/node_modules/node-gyp/lib/install.js b/deps/npm/node_modules/node-gyp/lib/install.js index b8705328806661..f68cd7fd6d2a59 100644 --- a/deps/npm/node_modules/node-gyp/lib/install.js +++ b/deps/npm/node_modules/node-gyp/lib/install.js @@ -224,8 +224,8 @@ function install (fs, gyp, argv, callback) { var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) - // Only download SHASUMS.txt if not using tarPath override - if (!tarPath) { + // Only download SHASUMS.txt if we downloaded something in need of SHA verification + if (!tarPath || win) { // download SHASUMS.txt async++ downloadShasums(deref) @@ -323,7 +323,7 @@ function install (fs, gyp, argv, callback) { req.on('error', done) req.on('response', function (res) { - if (res.statusCode === 404) { + if (res.statusCode === 403 || res.statusCode === 404) { if (arch === 'arm64') { // Arm64 is a newer platform on Windows and not all node distributions provide it. log.verbose(`${name} was not found in ${libUrl}`) diff --git a/deps/npm/node_modules/node-gyp/macOS_Catalina.md b/deps/npm/node_modules/node-gyp/macOS_Catalina.md new file mode 100644 index 00000000000000..5f02face57d963 --- /dev/null +++ b/deps/npm/node_modules/node-gyp/macOS_Catalina.md @@ -0,0 +1,74 @@ +# Installation notes for macOS Catalina (v10.15) + +_This document specifically refers to upgrades from previous versions of macOS to Catalina (10.15). It should be removed from the source repository when Catalina ceases to be the latest macOS version or updated to deal with challenges involved in upgrades to the next version of macOS._ + +Lessons learned from: +* https://github.com/nodejs/node-gyp/issues/1779 +* https://github.com/nodejs/node-gyp/issues/1861 +* https://github.com/nodejs/node-gyp/issues/1927 and elsewhere + +Installing `node-gyp` on macOS can be found at https://github.com/nodejs/node-gyp#on-macos + +However, upgrading to macOS Catalina changes some settings that may cause normal `node-gyp` installations to fail. + +### Is my Mac running macOS Catalina? +Let's make first make sure that your Mac is currently running Catalina: +% `sw_vers` + ProductName: Mac OS X + ProductVersion: 10.15 + BuildVersion: 19A602 + +If `ProductVersion` is less then `10.15` then this document is not really for you. + +### The acid test +Next, lets see if `Xcode Command Line Tools` are installed: +1. `/usr/sbin/pkgutil --packages | grep CL` + * If nothing is listed, then [skip to the next section](#Two-roads). + * If `com.apple.pkg.CLTools_Executables` is listed then try: +2. `/usr/sbin/pkgutil --pkg-info com.apple.pkg.CLTools_Executables` + * If `version: 11.0.0` or later is listed then _you are done_! Your Mac should be ready to install `node-gyp`. Doing `clang -v` should show `Apple clang version 11.0.0` or later. + +As you go through the remainder of this document, at anytime you can try these `acid test` commands. If they pass then your Mac should be ready to install `node-gyp`. + +### Two roads +There are two main ways to install `node-gyp` on macOS: +1. With the full Xcode (~7.6 GB download) from the `App Store` app. +2. With the _much_ smaller Xcode Command Line Tools via `xcode-select --install` + +### Installing `node-gyp` using the full Xcode +1. `xcodebuild -version` should show `Xcode 11.1` or later. + * If not, then install/upgrade Xcode from the App Store app. +2. Open the Xcode app and... + * Under __Preferences > Locations__ select the tools if their location is empty. + * Allow Xcode app to do an essential install of the most recent compiler tools. +3. Once all installations are _complete_, quit out of Xcode. +4. `sudo xcodebuild -license accept` # If you agree with the licensing terms. +5. `softwareupdate -l` # No listing is a good sign. + * If Xcode or Tools upgrades are listed, use "Software Upgrade" to install them. +6. `xcode-select -version` # Should return `xcode-select version 2370` or later. +7. `xcode-select -print-path` # Should return `/Applications/Xcode.app/Contents/Developer` +8. Try the [_acid test_ steps above](#The-acid-test) to see if your Mac is ready. +9. If the _acid test_ does _not_ pass then... +10. `sudo xcode-select --reset` # Enter root password. No output is normal. +11. Repeat step 7 above. Is the path different this time? Repeat the _acid test_. + +### Installing `node-gyp` using the Xcode Command Line Tools +1. If the _acid test_ has not succeeded, then try `xcode-select --install` +2. Wait until the install process is _complete_. +3. `softwareupdate -l` # No listing is a good sign. + * If Xcode or Tools upgrades are listed, use "Software Update" to install them. +4. `xcode-select -version` # Should return `xcode-select version 2370` or later. +5. `xcode-select -print-path` # Should return `/Library/Developer/CommandLineTools` +6. Try the [_acid test_ steps above](#The-acid-test) to see if your Mac is ready. +7. If the _acid test_ does _not_ pass then... +8. `sudo xcode-select --reset` # Enter root password. No output is normal. +9. Repeat step 5 above. Is the path different this time? Repeat the _acid test_. + +### I did all that and the acid test still does not pass :-( +1. `sudo rm -rf $(xcode-select -print-path)` # Enter root password. No output is normal. +2. `xcode-select --install` +3. If the [_acid test_](#The-acid-test) still does _not_ pass then... +4. `npm explore npm -g -- npm install node-gyp@latest` +5. `npm explore npm -g -- npm explore npm-lifecycle -- npm install node-gyp@latest` +6. If the _acid test_ still does _not_ pass then... +7. Add a comment to https://github.com/nodejs/node-gyp/issues/1927 so we can improve. diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/.npmignore b/deps/npm/node_modules/node-gyp/node_modules/nopt/.npmignore deleted file mode 100644 index 3c3629e647f5dd..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/.travis.yml b/deps/npm/node_modules/node-gyp/node_modules/nopt/.travis.yml deleted file mode 100644 index 99f2bbf5068a8c..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -language: node_js -node_js: - - '0.8' - - '0.10' - - '0.12' - - 'iojs' -before_install: - - npm install -g npm@latest diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/LICENSE b/deps/npm/node_modules/node-gyp/node_modules/nopt/LICENSE deleted file mode 100644 index 19129e315fe593..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/README.md b/deps/npm/node_modules/node-gyp/node_modules/nopt/README.md deleted file mode 100644 index f21a4b31c5d482..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/README.md +++ /dev/null @@ -1,211 +0,0 @@ -If you want to write an option parser, and have it be good, there are -two ways to do it. The Right Way, and the Wrong Way. - -The Wrong Way is to sit down and write an option parser. We've all done -that. - -The Right Way is to write some complex configurable program with so many -options that you hit the limit of your frustration just trying to -manage them all, and defer it with duct-tape solutions until you see -exactly to the core of the problem, and finally snap and write an -awesome option parser. - -If you want to write an option parser, don't write an option parser. -Write a package manager, or a source control system, or a service -restarter, or an operating system. You probably won't end up with a -good one of those, but if you don't give up, and you are relentless and -diligent enough in your procrastination, you may just end up with a very -nice option parser. - -## USAGE - - // my-program.js - var nopt = require("nopt") - , Stream = require("stream").Stream - , path = require("path") - , knownOpts = { "foo" : [String, null] - , "bar" : [Stream, Number] - , "baz" : path - , "bloo" : [ "big", "medium", "small" ] - , "flag" : Boolean - , "pick" : Boolean - , "many1" : [String, Array] - , "many2" : [path] - } - , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] - , "b7" : ["--bar", "7"] - , "m" : ["--bloo", "medium"] - , "p" : ["--pick"] - , "f" : ["--flag"] - } - // everything is optional. - // knownOpts and shorthands default to {} - // arg list defaults to process.argv - // slice defaults to 2 - , parsed = nopt(knownOpts, shortHands, process.argv, 2) - console.log(parsed) - -This would give you support for any of the following: - -```bash -$ node my-program.js --foo "blerp" --no-flag -{ "foo" : "blerp", "flag" : false } - -$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag -{ bar: 7, foo: "Mr. Hand", flag: true } - -$ node my-program.js --foo "blerp" -f -----p -{ foo: "blerp", flag: true, pick: true } - -$ node my-program.js -fp --foofoo -{ foo: "Mr. Foo", flag: true, pick: true } - -$ node my-program.js --foofoo -- -fp # -- stops the flag parsing. -{ foo: "Mr. Foo", argv: { remain: ["-fp"] } } - -$ node my-program.js --blatzk -fp # unknown opts are ok. -{ blatzk: true, flag: true, pick: true } - -$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value -{ blatzk: 1000, flag: true, pick: true } - -$ node my-program.js --no-blatzk -fp # unless they start with "no-" -{ blatzk: false, flag: true, pick: true } - -$ node my-program.js --baz b/a/z # known paths are resolved. -{ baz: "/Users/isaacs/b/a/z" } - -# if Array is one of the types, then it can take many -# values, and will always be an array. The other types provided -# specify what types are allowed in the list. - -$ node my-program.js --many1 5 --many1 null --many1 foo -{ many1: ["5", "null", "foo"] } - -$ node my-program.js --many2 foo --many2 bar -{ many2: ["/path/to/foo", "path/to/bar"] } -``` - -Read the tests at the bottom of `lib/nopt.js` for more examples of -what this puppy can do. - -## Types - -The following types are supported, and defined on `nopt.typeDefs` - -* String: A normal string. No parsing is done. -* path: A file system path. Gets resolved against cwd if not absolute. -* url: A url. If it doesn't parse, it isn't accepted. -* Number: Must be numeric. -* Date: Must parse as a date. If it does, and `Date` is one of the options, - then it will return a Date object, not a string. -* Boolean: Must be either `true` or `false`. If an option is a boolean, - then it does not need a value, and its presence will imply `true` as - the value. To negate boolean flags, do `--no-whatever` or `--whatever - false` -* NaN: Means that the option is strictly not allowed. Any value will - fail. -* Stream: An object matching the "Stream" class in node. Valuable - for use when validating programmatically. (npm uses this to let you - supply any WriteStream on the `outfd` and `logfd` config options.) -* Array: If `Array` is specified as one of the types, then the value - will be parsed as a list of options. This means that multiple values - can be specified, and that the value will always be an array. - -If a type is an array of values not on this list, then those are -considered valid values. For instance, in the example above, the -`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, -and any other value will be rejected. - -When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be -interpreted as their JavaScript equivalents. - -You can also mix types and values, or multiple types, in a list. For -instance `{ blah: [Number, null] }` would allow a value to be set to -either a Number or null. When types are ordered, this implies a -preference, and the first type that can be used to properly interpret -the value will be used. - -To define a new type, add it to `nopt.typeDefs`. Each item in that -hash is an object with a `type` member and a `validate` method. The -`type` member is an object that matches what goes in the type list. The -`validate` method is a function that gets called with `validate(data, -key, val)`. Validate methods should assign `data[key]` to the valid -value of `val` if it can be handled properly, or return boolean -`false` if it cannot. - -You can also call `nopt.clean(data, types, typeDefs)` to clean up a -config object and remove its invalid properties. - -## Error Handling - -By default, nopt outputs a warning to standard error when invalid values for -known options are found. You can change this behavior by assigning a method -to `nopt.invalidHandler`. This method will be called with -the offending `nopt.invalidHandler(key, val, types)`. - -If no `nopt.invalidHandler` is assigned, then it will console.error -its whining. If it is assigned to boolean `false` then the warning is -suppressed. - -## Abbreviations - -Yes, they are supported. If you define options like this: - -```javascript -{ "foolhardyelephants" : Boolean -, "pileofmonkeys" : Boolean } -``` - -Then this will work: - -```bash -node program.js --foolhar --pil -node program.js --no-f --pileofmon -# etc. -``` - -## Shorthands - -Shorthands are a hash of shorter option names to a snippet of args that -they expand to. - -If multiple one-character shorthands are all combined, and the -combination does not unambiguously match any other option or shorthand, -then they will be broken up into their constituent parts. For example: - -```json -{ "s" : ["--loglevel", "silent"] -, "g" : "--global" -, "f" : "--force" -, "p" : "--parseable" -, "l" : "--long" -} -``` - -```bash -npm ls -sgflp -# just like doing this: -npm ls --loglevel silent --global --force --long --parseable -``` - -## The Rest of the args - -The config object returned by nopt is given a special member called -`argv`, which is an object with the following fields: - -* `remain`: The remaining args after all the parsing has occurred. -* `original`: The args as they originally appeared. -* `cooked`: The args after flags and shorthands are expanded. - -## Slicing - -Node programs are called with more or less the exact argv as it appears -in C land, after the v8 and node-specific options have been plucked off. -As such, `argv[0]` is always `node` and `argv[1]` is always the -JavaScript program being run. - -That's usually not very useful to you. So they're sliced off by -default. If you want them, then you can pass in `0` as the last -argument, or any other number that you'd like to slice off the start of -the list. diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/bin/nopt.js b/deps/npm/node_modules/node-gyp/node_modules/nopt/bin/nopt.js deleted file mode 100755 index 3232d4c570fdcb..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/bin/nopt.js +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env node -var nopt = require("../lib/nopt") - , path = require("path") - , types = { num: Number - , bool: Boolean - , help: Boolean - , list: Array - , "num-list": [Number, Array] - , "str-list": [String, Array] - , "bool-list": [Boolean, Array] - , str: String - , clear: Boolean - , config: Boolean - , length: Number - , file: path - } - , shorthands = { s: [ "--str", "astring" ] - , b: [ "--bool" ] - , nb: [ "--no-bool" ] - , tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ] - , "?": ["--help"] - , h: ["--help"] - , H: ["--help"] - , n: [ "--num", "125" ] - , c: ["--config"] - , l: ["--length"] - , f: ["--file"] - } - , parsed = nopt( types - , shorthands - , process.argv - , 2 ) - -console.log("parsed", parsed) - -if (parsed.help) { - console.log("") - console.log("nopt cli tester") - console.log("") - console.log("types") - console.log(Object.keys(types).map(function M (t) { - var type = types[t] - if (Array.isArray(type)) { - return [t, type.map(function (type) { return type.name })] - } - return [t, type && type.name] - }).reduce(function (s, i) { - s[i[0]] = i[1] - return s - }, {})) - console.log("") - console.log("shorthands") - console.log(shorthands) -} diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/examples/my-program.js b/deps/npm/node_modules/node-gyp/node_modules/nopt/examples/my-program.js deleted file mode 100755 index 142447e18e756c..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/examples/my-program.js +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env node - -//process.env.DEBUG_NOPT = 1 - -// my-program.js -var nopt = require("../lib/nopt") - , Stream = require("stream").Stream - , path = require("path") - , knownOpts = { "foo" : [String, null] - , "bar" : [Stream, Number] - , "baz" : path - , "bloo" : [ "big", "medium", "small" ] - , "flag" : Boolean - , "pick" : Boolean - } - , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] - , "b7" : ["--bar", "7"] - , "m" : ["--bloo", "medium"] - , "p" : ["--pick"] - , "f" : ["--flag", "true"] - , "g" : ["--flag"] - , "s" : "--flag" - } - // everything is optional. - // knownOpts and shorthands default to {} - // arg list defaults to process.argv - // slice defaults to 2 - , parsed = nopt(knownOpts, shortHands, process.argv, 2) - -console.log("parsed =\n"+ require("util").inspect(parsed)) diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/lib/nopt.js b/deps/npm/node_modules/node-gyp/node_modules/nopt/lib/nopt.js deleted file mode 100644 index 97707e784243bc..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/lib/nopt.js +++ /dev/null @@ -1,415 +0,0 @@ -// info about each config option. - -var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG - ? function () { console.error.apply(console, arguments) } - : function () {} - -var url = require("url") - , path = require("path") - , Stream = require("stream").Stream - , abbrev = require("abbrev") - -module.exports = exports = nopt -exports.clean = clean - -exports.typeDefs = - { String : { type: String, validate: validateString } - , Boolean : { type: Boolean, validate: validateBoolean } - , url : { type: url, validate: validateUrl } - , Number : { type: Number, validate: validateNumber } - , path : { type: path, validate: validatePath } - , Stream : { type: Stream, validate: validateStream } - , Date : { type: Date, validate: validateDate } - } - -function nopt (types, shorthands, args, slice) { - args = args || process.argv - types = types || {} - shorthands = shorthands || {} - if (typeof slice !== "number") slice = 2 - - debug(types, shorthands, args, slice) - - args = args.slice(slice) - var data = {} - , key - , remain = [] - , cooked = args - , original = args.slice(0) - - parse(args, data, remain, types, shorthands) - // now data is full - clean(data, types, exports.typeDefs) - data.argv = {remain:remain,cooked:cooked,original:original} - Object.defineProperty(data.argv, 'toString', { value: function () { - return this.original.map(JSON.stringify).join(" ") - }, enumerable: false }) - return data -} - -function clean (data, types, typeDefs) { - typeDefs = typeDefs || exports.typeDefs - var remove = {} - , typeDefault = [false, true, null, String, Array] - - Object.keys(data).forEach(function (k) { - if (k === "argv") return - var val = data[k] - , isArray = Array.isArray(val) - , type = types[k] - if (!isArray) val = [val] - if (!type) type = typeDefault - if (type === Array) type = typeDefault.concat(Array) - if (!Array.isArray(type)) type = [type] - - debug("val=%j", val) - debug("types=", type) - val = val.map(function (val) { - // if it's an unknown value, then parse false/true/null/numbers/dates - if (typeof val === "string") { - debug("string %j", val) - val = val.trim() - if ((val === "null" && ~type.indexOf(null)) - || (val === "true" && - (~type.indexOf(true) || ~type.indexOf(Boolean))) - || (val === "false" && - (~type.indexOf(false) || ~type.indexOf(Boolean)))) { - val = JSON.parse(val) - debug("jsonable %j", val) - } else if (~type.indexOf(Number) && !isNaN(val)) { - debug("convert to number", val) - val = +val - } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { - debug("convert to date", val) - val = new Date(val) - } - } - - if (!types.hasOwnProperty(k)) { - return val - } - - // allow `--no-blah` to set 'blah' to null if null is allowed - if (val === false && ~type.indexOf(null) && - !(~type.indexOf(false) || ~type.indexOf(Boolean))) { - val = null - } - - var d = {} - d[k] = val - debug("prevalidated val", d, val, types[k]) - if (!validate(d, k, val, types[k], typeDefs)) { - if (exports.invalidHandler) { - exports.invalidHandler(k, val, types[k], data) - } else if (exports.invalidHandler !== false) { - debug("invalid: "+k+"="+val, types[k]) - } - return remove - } - debug("validated val", d, val, types[k]) - return d[k] - }).filter(function (val) { return val !== remove }) - - if (!val.length) delete data[k] - else if (isArray) { - debug(isArray, data[k], val) - data[k] = val - } else data[k] = val[0] - - debug("k=%s val=%j", k, val, data[k]) - }) -} - -function validateString (data, k, val) { - data[k] = String(val) -} - -function validatePath (data, k, val) { - if (val === true) return false - if (val === null) return true - - val = String(val) - var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\// - if (val.match(homePattern) && process.env.HOME) { - val = path.resolve(process.env.HOME, val.substr(2)) - } - data[k] = path.resolve(String(val)) - return true -} - -function validateNumber (data, k, val) { - debug("validate Number %j %j %j", k, val, isNaN(val)) - if (isNaN(val)) return false - data[k] = +val -} - -function validateDate (data, k, val) { - debug("validate Date %j %j %j", k, val, Date.parse(val)) - var s = Date.parse(val) - if (isNaN(s)) return false - data[k] = new Date(val) -} - -function validateBoolean (data, k, val) { - if (val instanceof Boolean) val = val.valueOf() - else if (typeof val === "string") { - if (!isNaN(val)) val = !!(+val) - else if (val === "null" || val === "false") val = false - else val = true - } else val = !!val - data[k] = val -} - -function validateUrl (data, k, val) { - val = url.parse(String(val)) - if (!val.host) return false - data[k] = val.href -} - -function validateStream (data, k, val) { - if (!(val instanceof Stream)) return false - data[k] = val -} - -function validate (data, k, val, type, typeDefs) { - // arrays are lists of types. - if (Array.isArray(type)) { - for (var i = 0, l = type.length; i < l; i ++) { - if (type[i] === Array) continue - if (validate(data, k, val, type[i], typeDefs)) return true - } - delete data[k] - return false - } - - // an array of anything? - if (type === Array) return true - - // NaN is poisonous. Means that something is not allowed. - if (type !== type) { - debug("Poison NaN", k, val, type) - delete data[k] - return false - } - - // explicit list of values - if (val === type) { - debug("Explicitly allowed %j", val) - // if (isArray) (data[k] = data[k] || []).push(val) - // else data[k] = val - data[k] = val - return true - } - - // now go through the list of typeDefs, validate against each one. - var ok = false - , types = Object.keys(typeDefs) - for (var i = 0, l = types.length; i < l; i ++) { - debug("test type %j %j %j", k, val, types[i]) - var t = typeDefs[types[i]] - if (t && - ((type && type.name && t.type && t.type.name) ? (type.name === t.type.name) : (type === t.type))) { - var d = {} - ok = false !== t.validate(d, k, val) - val = d[k] - if (ok) { - // if (isArray) (data[k] = data[k] || []).push(val) - // else data[k] = val - data[k] = val - break - } - } - } - debug("OK? %j (%j %j %j)", ok, k, val, types[i]) - - if (!ok) delete data[k] - return ok -} - -function parse (args, data, remain, types, shorthands) { - debug("parse", args, data, remain) - - var key = null - , abbrevs = abbrev(Object.keys(types)) - , shortAbbr = abbrev(Object.keys(shorthands)) - - for (var i = 0; i < args.length; i ++) { - var arg = args[i] - debug("arg", arg) - - if (arg.match(/^-{2,}$/)) { - // done with keys. - // the rest are args. - remain.push.apply(remain, args.slice(i + 1)) - args[i] = "--" - break - } - var hadEq = false - if (arg.charAt(0) === "-" && arg.length > 1) { - if (arg.indexOf("=") !== -1) { - hadEq = true - var v = arg.split("=") - arg = v.shift() - v = v.join("=") - args.splice.apply(args, [i, 1].concat([arg, v])) - } - - // see if it's a shorthand - // if so, splice and back up to re-parse it. - var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) - debug("arg=%j shRes=%j", arg, shRes) - if (shRes) { - debug(arg, shRes) - args.splice.apply(args, [i, 1].concat(shRes)) - if (arg !== shRes[0]) { - i -- - continue - } - } - arg = arg.replace(/^-+/, "") - var no = null - while (arg.toLowerCase().indexOf("no-") === 0) { - no = !no - arg = arg.substr(3) - } - - if (abbrevs[arg]) arg = abbrevs[arg] - - var isArray = types[arg] === Array || - Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1 - - // allow unknown things to be arrays if specified multiple times. - if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { - if (!Array.isArray(data[arg])) - data[arg] = [data[arg]] - isArray = true - } - - var val - , la = args[i + 1] - - var isBool = typeof no === 'boolean' || - types[arg] === Boolean || - Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 || - (typeof types[arg] === 'undefined' && !hadEq) || - (la === "false" && - (types[arg] === null || - Array.isArray(types[arg]) && ~types[arg].indexOf(null))) - - if (isBool) { - // just set and move along - val = !no - // however, also support --bool true or --bool false - if (la === "true" || la === "false") { - val = JSON.parse(la) - la = null - if (no) val = !val - i ++ - } - - // also support "foo":[Boolean, "bar"] and "--foo bar" - if (Array.isArray(types[arg]) && la) { - if (~types[arg].indexOf(la)) { - // an explicit type - val = la - i ++ - } else if ( la === "null" && ~types[arg].indexOf(null) ) { - // null allowed - val = null - i ++ - } else if ( !la.match(/^-{2,}[^-]/) && - !isNaN(la) && - ~types[arg].indexOf(Number) ) { - // number - val = +la - i ++ - } else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) { - // string - val = la - i ++ - } - } - - if (isArray) (data[arg] = data[arg] || []).push(val) - else data[arg] = val - - continue - } - - if (types[arg] === String && la === undefined) - la = "" - - if (la && la.match(/^-{2,}$/)) { - la = undefined - i -- - } - - val = la === undefined ? true : la - if (isArray) (data[arg] = data[arg] || []).push(val) - else data[arg] = val - - i ++ - continue - } - remain.push(arg) - } -} - -function resolveShort (arg, shorthands, shortAbbr, abbrevs) { - // handle single-char shorthands glommed together, like - // npm ls -glp, but only if there is one dash, and only if - // all of the chars are single-char shorthands, and it's - // not a match to some other abbrev. - arg = arg.replace(/^-+/, '') - - // if it's an exact known option, then don't go any further - if (abbrevs[arg] === arg) - return null - - // if it's an exact known shortopt, same deal - if (shorthands[arg]) { - // make it an array, if it's a list of words - if (shorthands[arg] && !Array.isArray(shorthands[arg])) - shorthands[arg] = shorthands[arg].split(/\s+/) - - return shorthands[arg] - } - - // first check to see if this arg is a set of single-char shorthands - var singles = shorthands.___singles - if (!singles) { - singles = Object.keys(shorthands).filter(function (s) { - return s.length === 1 - }).reduce(function (l,r) { - l[r] = true - return l - }, {}) - shorthands.___singles = singles - debug('shorthand singles', singles) - } - - var chrs = arg.split("").filter(function (c) { - return singles[c] - }) - - if (chrs.join("") === arg) return chrs.map(function (c) { - return shorthands[c] - }).reduce(function (l, r) { - return l.concat(r) - }, []) - - - // if it's an arg abbrev, and not a literal shorthand, then prefer the arg - if (abbrevs[arg] && !shorthands[arg]) - return null - - // if it's an abbr for a shorthand, then use that - if (shortAbbr[arg]) - arg = shortAbbr[arg] - - // make it an array, if it's a list of words - if (shorthands[arg] && !Array.isArray(shorthands[arg])) - shorthands[arg] = shorthands[arg].split(/\s+/) - - return shorthands[arg] -} diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/package.json b/deps/npm/node_modules/node-gyp/node_modules/nopt/package.json deleted file mode 100644 index 5179f473b1bbd4..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "nopt@2 || 3", - "_id": "nopt@3.0.6", - "_inBundle": false, - "_integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", - "_location": "/node-gyp/nopt", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "nopt@2 || 3", - "name": "nopt", - "escapedName": "nopt", - "rawSpec": "2 || 3", - "saveSpec": null, - "fetchSpec": "2 || 3" - }, - "_requiredBy": [ - "/node-gyp" - ], - "_resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", - "_shasum": "c6465dbf08abcd4db359317f79ac68a646b28ff9", - "_spec": "nopt@2 || 3", - "_where": "/Users/rebecca/code/npm/node_modules/node-gyp", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "bin": { - "nopt": "./bin/nopt.js" - }, - "bugs": { - "url": "https://github.com/npm/nopt/issues" - }, - "bundleDependencies": false, - "dependencies": { - "abbrev": "1" - }, - "deprecated": false, - "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", - "devDependencies": { - "tap": "^1.2.0" - }, - "homepage": "https://github.com/npm/nopt#readme", - "license": "ISC", - "main": "lib/nopt.js", - "name": "nopt", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/nopt.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "3.0.6" -} diff --git a/deps/npm/node_modules/node-gyp/node_modules/nopt/test/basic.js b/deps/npm/node_modules/node-gyp/node_modules/nopt/test/basic.js deleted file mode 100644 index d399de9209932c..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/nopt/test/basic.js +++ /dev/null @@ -1,273 +0,0 @@ -var nopt = require("../") - , test = require('tap').test - - -test("passing a string results in a string", function (t) { - var parsed = nopt({ key: String }, {}, ["--key", "myvalue"], 0) - t.same(parsed.key, "myvalue") - t.end() -}) - -// https://github.com/npm/nopt/issues/31 -test("Empty String results in empty string, not true", function (t) { - var parsed = nopt({ empty: String }, {}, ["--empty"], 0) - t.same(parsed.empty, "") - t.end() -}) - -test("~ path is resolved to $HOME", function (t) { - var path = require("path") - if (!process.env.HOME) process.env.HOME = "/tmp" - var parsed = nopt({key: path}, {}, ["--key=~/val"], 0) - t.same(parsed.key, path.resolve(process.env.HOME, "val")) - t.end() -}) - -// https://github.com/npm/nopt/issues/24 -test("Unknown options are not parsed as numbers", function (t) { - var parsed = nopt({"parse-me": Number}, null, ['--leave-as-is=1.20', '--parse-me=1.20'], 0) - t.equal(parsed['leave-as-is'], '1.20') - t.equal(parsed['parse-me'], 1.2) - t.end() -}); - -// https://github.com/npm/nopt/issues/48 -test("Check types based on name of type", function (t) { - var parsed = nopt({"parse-me": {name: "Number"}}, null, ['--parse-me=1.20'], 0) - t.equal(parsed['parse-me'], 1.2) - t.end() -}) - - -test("Missing types are not parsed", function (t) { - var parsed = nopt({"parse-me": {}}, null, ['--parse-me=1.20'], 0) - //should only contain argv - t.equal(Object.keys(parsed).length, 1) - t.end() -}) - -test("Types passed without a name are not parsed", function (t) { - var parsed = nopt({"parse-me": {}}, {}, ['--parse-me=1.20'], 0) - //should only contain argv - t.equal(Object.keys(parsed).length, 1) - t.end() -}) - -test("other tests", function (t) { - - var util = require("util") - , Stream = require("stream") - , path = require("path") - , url = require("url") - - , shorthands = - { s : ["--loglevel", "silent"] - , d : ["--loglevel", "info"] - , dd : ["--loglevel", "verbose"] - , ddd : ["--loglevel", "silly"] - , noreg : ["--no-registry"] - , reg : ["--registry"] - , "no-reg" : ["--no-registry"] - , silent : ["--loglevel", "silent"] - , verbose : ["--loglevel", "verbose"] - , h : ["--usage"] - , H : ["--usage"] - , "?" : ["--usage"] - , help : ["--usage"] - , v : ["--version"] - , f : ["--force"] - , desc : ["--description"] - , "no-desc" : ["--no-description"] - , "local" : ["--no-global"] - , l : ["--long"] - , p : ["--parseable"] - , porcelain : ["--parseable"] - , g : ["--global"] - } - - , types = - { aoa: Array - , nullstream: [null, Stream] - , date: Date - , str: String - , browser : String - , cache : path - , color : ["always", Boolean] - , depth : Number - , description : Boolean - , dev : Boolean - , editor : path - , force : Boolean - , global : Boolean - , globalconfig : path - , group : [String, Number] - , gzipbin : String - , logfd : [Number, Stream] - , loglevel : ["silent","win","error","warn","info","verbose","silly"] - , long : Boolean - , "node-version" : [false, String] - , npaturl : url - , npat : Boolean - , "onload-script" : [false, String] - , outfd : [Number, Stream] - , parseable : Boolean - , pre: Boolean - , prefix: path - , proxy : url - , "rebuild-bundle" : Boolean - , registry : url - , searchopts : String - , searchexclude: [null, String] - , shell : path - , t: [Array, String] - , tag : String - , tar : String - , tmp : path - , "unsafe-perm" : Boolean - , usage : Boolean - , user : String - , username : String - , userconfig : path - , version : Boolean - , viewer: path - , _exit : Boolean - , path: path - } - - ; [["-v", {version:true}, []] - ,["---v", {version:true}, []] - ,["ls -s --no-reg connect -d", - {loglevel:"info",registry:null},["ls","connect"]] - ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]] - ,["ls --registry blargle", {}, ["ls"]] - ,["--no-registry", {registry:null}, []] - ,["--no-color true", {color:false}, []] - ,["--no-color false", {color:true}, []] - ,["--no-color", {color:false}, []] - ,["--color false", {color:false}, []] - ,["--color --logfd 7", {logfd:7,color:true}, []] - ,["--color=true", {color:true}, []] - ,["--logfd=10", {logfd:10}, []] - ,["--tmp=/tmp -tar=gtar",{tmp:"/tmp",tar:"gtar"},[]] - ,["--tmp=tmp -tar=gtar", - {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]] - ,["--logfd x", {}, []] - ,["a -true -- -no-false", {true:true},["a","-no-false"]] - ,["a -no-false", {false:false},["a"]] - ,["a -no-no-true", {true:true}, ["a"]] - ,["a -no-no-no-false", {false:false}, ["a"]] - ,["---NO-no-No-no-no-no-nO-no-no"+ - "-No-no-no-no-no-no-no-no-no"+ - "-no-no-no-no-NO-NO-no-no-no-no-no-no"+ - "-no-body-can-do-the-boogaloo-like-I-do" - ,{"body-can-do-the-boogaloo-like-I-do":false}, []] - ,["we are -no-strangers-to-love "+ - "--you-know=the-rules --and=so-do-i "+ - "---im-thinking-of=a-full-commitment "+ - "--no-you-would-get-this-from-any-other-guy "+ - "--no-gonna-give-you-up "+ - "-no-gonna-let-you-down=true "+ - "--no-no-gonna-run-around false "+ - "--desert-you=false "+ - "--make-you-cry false "+ - "--no-tell-a-lie "+ - "--no-no-and-hurt-you false" - ,{"strangers-to-love":false - ,"you-know":"the-rules" - ,"and":"so-do-i" - ,"you-would-get-this-from-any-other-guy":false - ,"gonna-give-you-up":false - ,"gonna-let-you-down":false - ,"gonna-run-around":false - ,"desert-you":false - ,"make-you-cry":false - ,"tell-a-lie":false - ,"and-hurt-you":false - },["we", "are"]] - ,["-t one -t two -t three" - ,{t: ["one", "two", "three"]} - ,[]] - ,["-t one -t null -t three four five null" - ,{t: ["one", "null", "three"]} - ,["four", "five", "null"]] - ,["-t foo" - ,{t:["foo"]} - ,[]] - ,["--no-t" - ,{t:["false"]} - ,[]] - ,["-no-no-t" - ,{t:["true"]} - ,[]] - ,["-aoa one -aoa null -aoa 100" - ,{aoa:["one", null, '100']} - ,[]] - ,["-str 100" - ,{str:"100"} - ,[]] - ,["--color always" - ,{color:"always"} - ,[]] - ,["--no-nullstream" - ,{nullstream:null} - ,[]] - ,["--nullstream false" - ,{nullstream:null} - ,[]] - ,["--notadate=2011-01-25" - ,{notadate: "2011-01-25"} - ,[]] - ,["--date 2011-01-25" - ,{date: new Date("2011-01-25")} - ,[]] - ,["-cl 1" - ,{config: true, length: 1} - ,[] - ,{config: Boolean, length: Number, clear: Boolean} - ,{c: "--config", l: "--length"}] - ,["--acount bla" - ,{"acount":true} - ,["bla"] - ,{account: Boolean, credentials: Boolean, options: String} - ,{a:"--account", c:"--credentials",o:"--options"}] - ,["--clear" - ,{clear:true} - ,[] - ,{clear:Boolean,con:Boolean,len:Boolean,exp:Boolean,add:Boolean,rep:Boolean} - ,{c:"--con",l:"--len",e:"--exp",a:"--add",r:"--rep"}] - ,["--file -" - ,{"file":"-"} - ,[] - ,{file:String} - ,{}] - ,["--file -" - ,{"file":true} - ,["-"] - ,{file:Boolean} - ,{}] - ,["--path" - ,{"path":null} - ,[]] - ,["--path ." - ,{"path":process.cwd()} - ,[]] - ].forEach(function (test) { - var argv = test[0].split(/\s+/) - , opts = test[1] - , rem = test[2] - , actual = nopt(test[3] || types, test[4] || shorthands, argv, 0) - , parsed = actual.argv - delete actual.argv - for (var i in opts) { - var e = JSON.stringify(opts[i]) - , a = JSON.stringify(actual[i] === undefined ? null : actual[i]) - if (e && typeof e === "object") { - t.deepEqual(e, a) - } else { - t.equal(e, a) - } - } - t.deepEqual(rem, parsed.remain) - }) - t.end() -}) diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/LICENSE b/deps/npm/node_modules/node-gyp/node_modules/semver/LICENSE deleted file mode 100644 index 19129e315fe593..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/README.md b/deps/npm/node_modules/node-gyp/node_modules/semver/README.md deleted file mode 100644 index cbd956549dbb01..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/README.md +++ /dev/null @@ -1,350 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Usage - - $ npm install semver - $ node - var semver = require('semver') - - semver.valid('1.2.3') // '1.2.3' - semver.valid('a.b.c') // null - semver.clean(' =v1.2.3 ') // '1.2.3' - semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true - semver.gt('1.2.3', '9.8.7') // false - semver.lt('1.2.3', '9.8.7') // true - -As a command-line utility: - - $ semver -h - - SemVer 5.1.0 - - A JavaScript implementation of the http://semver.org/ specification - Copyright Isaac Z. Schlueter - - Usage: semver [options] [ [...]] - Prints valid versions sorted by SemVer precedence - - Options: - -r --range - Print versions that match the specified range. - - -i --increment [] - Increment a version by the specified level. Level can - be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. - Only one version may be specified. - - --preid - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - - -l --loose - Interpret versions and ranges loosely - - Program exits successfully if any valid version satisfies - all supplied ranges, and prints all satisfying versions. - - If no satisfying versions are found, then exits failure. - - Versions are printed in ascending order, so supplying - multiple versions to the utility will just sort them. - -## Versions - -A "version" is described by the `v2.0.0` specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -A `version range` is a set of `comparators` which specify versions -that satisfy the range. - -A `comparator` is composed of an `operator` and a `version`. The set -of primitive `operators` is: - -* `<` Less than -* `<=` Less than or equal to -* `>` Greater than -* `>=` Greater than or equal to -* `=` Equal. If no operator is specified, then equality is assumed, - so this operator is optional, but MAY be included. - -For example, the comparator `>=1.2.7` would match the versions -`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` -or `1.1.0`. - -Comparators can be joined by whitespace to form a `comparator set`, -which is satisfied by the **intersection** of all of the comparators -it includes. - -A range is composed of one or more comparator sets, joined by `||`. A -version matches a range if and only if every comparator in at least -one of the `||`-separated comparator sets is satisfied by the version. - -For example, the range `>=1.2.7 <1.3.0` would match the versions -`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, -or `1.1.0`. - -The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, -`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. - -### Prerelease Tags - -If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then -it will only be allowed to satisfy comparator sets if at least one -comparator with the same `[major, minor, patch]` tuple also has a -prerelease tag. - -For example, the range `>1.2.3-alpha.3` would be allowed to match the -version `1.2.3-alpha.7`, but it would *not* be satisfied by -`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater -than" `1.2.3-alpha.3` according to the SemVer sort rules. The version -range only accepts prerelease tags on the `1.2.3` version. The -version `3.4.5` *would* satisfy the range, because it does not have a -prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. - -The purpose for this behavior is twofold. First, prerelease versions -frequently are updated very quickly, and contain many breaking changes -that are (by the author's design) not yet fit for public consumption. -Therefore, by default, they are excluded from range matching -semantics. - -Second, a user who has opted into using a prerelease version has -clearly indicated the intent to use *that specific* set of -alpha/beta/rc versions. By including a prerelease tag in the range, -the user is indicating that they are aware of the risk. However, it -is still not appropriate to assume that they have opted into taking a -similar risk on the *next* set of prerelease versions. - -#### Prerelease Identifiers - -The method `.inc` takes an additional `identifier` string argument that -will append the value of the string as a prerelease identifier: - -```javascript -> semver.inc('1.2.3', 'prerelease', 'beta') -'1.2.4-beta.0' -``` - -command-line example: - -```shell -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```shell -$ semver 1.2.4-beta.0 -i prerelease -1.2.4-beta.1 -``` - -### Advanced Range Syntax - -Advanced range syntax desugars to primitive comparators in -deterministic ways. - -Advanced ranges may be combined in the same way as primitive -comparators using white space or `||`. - -#### Hyphen Ranges `X.Y.Z - A.B.C` - -Specifies an inclusive set. - -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` - -If a partial version is provided as the first version in the inclusive -range, then the missing pieces are replaced with zeroes. - -* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` - -If a partial version is provided as the second version in the -inclusive range, then all versions that start with the supplied parts -of the tuple are accepted, but nothing that would be greater than the -provided tuple parts. - -* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` -* `1.2.3 - 2` := `>=1.2.3 <3.0.0` - -#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` - -Any of `X`, `x`, or `*` may be used to "stand in" for one of the -numeric values in the `[major, minor, patch]` tuple. - -* `*` := `>=0.0.0` (Any version satisfies) -* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) -* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) - -A partial version range is treated as an X-Range, so the special -character is in fact optional. - -* `""` (empty string) := `*` := `>=0.0.0` -* `1` := `1.x.x` := `>=1.0.0 <2.0.0` -* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` - -#### Tilde Ranges `~1.2.3` `~1.2` `~1` - -Allows patch-level changes if a minor version is specified on the -comparator. Allows minor-level changes if not. - -* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) -* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) -* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` -* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) -* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) -* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. - -#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` - -Allows changes that do not modify the left-most non-zero digit in the -`[major, minor, patch]` tuple. In other words, this allows patch and -minor updates for versions `1.0.0` and above, patch updates for -versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. - -Many authors treat a `0.x` version as if the `x` were the major -"breaking-change" indicator. - -Caret ranges are ideal when an author may make breaking changes -between `0.2.4` and `0.3.0` releases, which is a common practice. -However, it presumes that there will *not* be breaking changes between -`0.2.4` and `0.2.5`. It allows for changes that are presumed to be -additive (but non-breaking), according to commonly observed practices. - -* `^1.2.3` := `>=1.2.3 <2.0.0` -* `^0.2.3` := `>=0.2.3 <0.3.0` -* `^0.0.3` := `>=0.0.3 <0.0.4` -* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. -* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the - `0.0.3` version *only* will be allowed, if they are greater than or - equal to `beta`. So, `0.0.3-pr.2` would be allowed. - -When parsing caret ranges, a missing `patch` value desugars to the -number `0`, but will allow flexibility within that value, even if the -major and minor versions are both `0`. - -* `^1.2.x` := `>=1.2.0 <2.0.0` -* `^0.0.x` := `>=0.0.0 <0.1.0` -* `^0.0` := `>=0.0.0 <0.1.0` - -A missing `minor` and `patch` values will desugar to zero, but also -allow flexibility within those values, even if the major version is -zero. - -* `^1.x` := `>=1.0.0 <2.0.0` -* `^0.x` := `>=0.0.0 <1.0.0` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `loose` boolean argument that, if -true, will be more forgiving about not-quite-valid semver strings. -The resulting output will always be 100% strict, of course. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* `valid(v)`: Return the parsed version, or null if it's not valid. -* `inc(v, release)`: Return the version incremented by the release - type (`major`, `premajor`, `minor`, `preminor`, `patch`, - `prepatch`, or `prerelease`), or null if it's not valid - * `premajor` in one call will bump the version up to the next major - version and down to a prerelease of that major version. - `preminor`, and `prepatch` work the same way. - * If called from a non-prerelease version, the `prerelease` will work the - same as `prepatch`. It increments the patch version, then makes a - prerelease. If the input version is already a prerelease it simply - increments it. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. - -### Comparison - -* `gt(v1, v2)`: `v1 > v2` -* `gte(v1, v2)`: `v1 >= v2` -* `lt(v1, v2)`: `v1 < v2` -* `lte(v1, v2)`: `v1 <= v2` -* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. -* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if - `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. -* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions - in descending order when passed to `Array.sort()`. -* `diff(v1, v2)`: Returns difference between two versions by the release type - (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), - or null if the versions are the same. - - -### Ranges - -* `validRange(range)`: Return the valid range or null if it's not valid -* `satisfies(version, range)`: Return true if the version satisfies the - range. -* `maxSatisfying(versions, range)`: Return the highest version in the list - that satisfies the range, or `null` if none of them do. -* `minSatisfying(versions, range)`: Return the lowest version in the list - that satisfies the range, or `null` if none of them do. -* `gtr(version, range)`: Return `true` if version is greater than all the - versions possible in the range. -* `ltr(version, range)`: Return `true` if version is less than all the - versions possible in the range. -* `outside(version, range, hilo)`: Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because `2.0.1` satisfies, which is higher), nor less than the -range (since `1.2.8` satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/bin/semver b/deps/npm/node_modules/node-gyp/node_modules/semver/bin/semver deleted file mode 100755 index c5f2e857e82790..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/bin/semver +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - , versions = [] - , range = [] - , gt = [] - , lt = [] - , eq = [] - , inc = null - , version = require("../package.json").version - , loose = false - , identifier = undefined - , semver = require("../semver") - , reverse = false - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var i = a.indexOf('=') - if (i !== -1) { - a = a.slice(0, i) - argv.unshift(a.slice(i + 1)) - } - switch (a) { - case "-rv": case "-rev": case "--rev": case "--reverse": - reverse = true - break - case "-l": case "--loose": - loose = true - break - case "-v": case "--version": - versions.push(argv.shift()) - break - case "-i": case "--inc": case "--increment": - switch (argv[0]) { - case "major": case "minor": case "patch": case "prerelease": - case "premajor": case "preminor": case "prepatch": - inc = argv.shift() - break - default: - inc = "patch" - break - } - break - case "--preid": - identifier = argv.shift() - break - case "-r": case "--range": - range.push(argv.shift()) - break - case "-h": case "--help": case "-?": - return help() - default: - versions.push(a) - break - } - } - - versions = versions.filter(function (v) { - return semver.valid(v, loose) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) - return failInc() - - for (var i = 0, l = range.length; i < l ; i ++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], loose) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error("--inc can only be used on a single version with no range") - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? "rcompare" : "compare" - versions.sort(function (a, b) { - return semver[compare](a, b, loose) - }).map(function (v) { - return semver.clean(v, loose) - }).map(function (v) { - return inc ? semver.inc(v, inc, loose, identifier) : v - }).forEach(function (v,i,_) { console.log(v) }) -} - -function help () { - console.log(["SemVer " + version - ,"" - ,"A JavaScript implementation of the http://semver.org/ specification" - ,"Copyright Isaac Z. Schlueter" - ,"" - ,"Usage: semver [options] [ [...]]" - ,"Prints valid versions sorted by SemVer precedence" - ,"" - ,"Options:" - ,"-r --range " - ," Print versions that match the specified range." - ,"" - ,"-i --increment []" - ," Increment a version by the specified level. Level can" - ," be one of: major, minor, patch, premajor, preminor," - ," prepatch, or prerelease. Default level is 'patch'." - ," Only one version may be specified." - ,"" - ,"--preid " - ," Identifier to be used to prefix premajor, preminor," - ," prepatch or prerelease version increments." - ,"" - ,"-l --loose" - ," Interpret versions and ranges loosely" - ,"" - ,"Program exits successfully if any valid version satisfies" - ,"all supplied ranges, and prints all satisfying versions." - ,"" - ,"If no satisfying versions are found, then exits failure." - ,"" - ,"Versions are printed in ascending order, so supplying" - ,"multiple versions to the utility will just sort them." - ].join("\n")) -} diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/package.json b/deps/npm/node_modules/node-gyp/node_modules/semver/package.json deleted file mode 100644 index 8793bae37c297c..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "_from": "semver@~5.3.0", - "_id": "semver@5.3.0", - "_inBundle": false, - "_integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", - "_location": "/node-gyp/semver", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "semver@~5.3.0", - "name": "semver", - "escapedName": "semver", - "rawSpec": "~5.3.0", - "saveSpec": null, - "fetchSpec": "~5.3.0" - }, - "_requiredBy": [ - "/node-gyp" - ], - "_resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", - "_shasum": "9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f", - "_spec": "semver@~5.3.0", - "_where": "/Users/rebecca/code/npm/node_modules/node-gyp", - "bin": { - "semver": "./bin/semver" - }, - "bugs": { - "url": "https://github.com/npm/node-semver/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The semantic version parser used by npm.", - "devDependencies": { - "tap": "^2.0.0" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "homepage": "https://github.com/npm/node-semver#readme", - "license": "ISC", - "main": "semver.js", - "name": "semver", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/node-semver.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "5.3.0" -} diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/range.bnf b/deps/npm/node_modules/node-gyp/node_modules/semver/range.bnf deleted file mode 100644 index 25ebd5c8325488..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/deps/npm/node_modules/node-gyp/node_modules/semver/semver.js b/deps/npm/node_modules/node-gyp/node_modules/semver/semver.js deleted file mode 100644 index 5f1a3c5c9e5dc9..00000000000000 --- a/deps/npm/node_modules/node-gyp/node_modules/semver/semver.js +++ /dev/null @@ -1,1203 +0,0 @@ -exports = module.exports = SemVer; - -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; - -var MAX_LENGTH = 256; -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; - -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; - -src[FULL] = '^' + FULLPLAIN + '$'; - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; - -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; - -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; - -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; - -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; - -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; - -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; - - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; - - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; - -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; - -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} - -exports.parse = parse; -function parse(version, loose) { - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - if (version.length > MAX_LENGTH) - return null; - - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; - - try { - return new SemVer(version, loose); - } catch (er) { - return null; - } -} - -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); - } - - if (version.length > MAX_LENGTH) - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - - if (!(this instanceof SemVer)) - return new SemVer(version, loose); - - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - - if (!m) - throw new TypeError('Invalid Version: ' + version); - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) - throw new TypeError('Invalid major version') - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) - throw new TypeError('Invalid minor version') - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) - throw new TypeError('Invalid patch version') - - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) - return num; - } - return id; - }); - - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} - -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; - -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.length && !other.prerelease.length) - return 0; - - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function(release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) - this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) - this.minor++; - this.patch = 0; - this.prerelease = []; - break; - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) - this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) - this.prerelease = [identifier, 0]; - } else - this.prerelease = [identifier, 0]; - } - break; - - default: - throw new Error('invalid increment argument: ' + release); - } - this.format(); - this.raw = this.version; - return this; -}; - -exports.inc = inc; -function inc(version, release, loose, identifier) { - if (typeof(loose) === 'string') { - identifier = loose; - loose = undefined; - } - - try { - return new SemVer(version, loose).inc(release, identifier).version; - } catch (er) { - return null; - } -} - -exports.diff = diff; -function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre'+key; - } - } - } - return 'prerelease'; - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; - } - } - } - } -} - -exports.compareIdentifiers = compareIdentifiers; - -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} - -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} - -exports.major = major; -function major(a, loose) { - return new SemVer(a, loose).major; -} - -exports.minor = minor; -function minor(a, loose) { - return new SemVer(a, loose).minor; -} - -exports.patch = patch; -function patch(a, loose) { - return new SemVer(a, loose).patch; -} - -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(b); -} - -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} - -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} - -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} - -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} - -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} - -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} - -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} - -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} - -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} - -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a === b; - break; - case '!==': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a !== b; - break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} - -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); - - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; - - debug('comp', this); -} - -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - - if (!m) - throw new TypeError('Invalid comparator: ' + comp); - - this.operator = m[1]; - if (this.operator === '=') - this.operator = ''; - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else - this.semver = new SemVer(m[2], this.loose); -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); - - if (this.semver === ANY) - return true; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - return cmp(version, this.operator, this.semver, this.loose); -}; - - -exports.Range = Range; -function Range(range, loose) { - if ((range instanceof Range) && range.loose === loose) - return range; - - if (!(this instanceof Range)) - return new Range(range, loose); - - this.loose = loose; - - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); -} - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; - -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); - - return set; -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; -} - -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - - debug('tilde return', ret); - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } - - debug('caret return', ret); - return ret; - }); -} - -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; - } - - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } - - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false; - } - - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return rcompare(a, b, loose); - })[0] || null; -} - -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return compare(a, b, loose); - })[0] || null; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} diff --git a/deps/npm/node_modules/node-gyp/package.json b/deps/npm/node_modules/node-gyp/package.json index a5a39e3f2ba925..afa45f3969095a 100644 --- a/deps/npm/node_modules/node-gyp/package.json +++ b/deps/npm/node_modules/node-gyp/package.json @@ -1,63 +1,61 @@ { - "_from": "node-gyp@5.0.5", - "_id": "node-gyp@5.0.5", + "_from": "node-gyp@5.0.7", + "_id": "node-gyp@5.0.7", "_inBundle": false, - "_integrity": "sha512-WABl9s4/mqQdZneZHVWVG4TVr6QQJZUC6PAx47ITSk9lreZ1n+7Z9mMAIbA3vnO4J9W20P7LhCxtzfWsAD/KDw==", + "_integrity": "sha512-K8aByl8OJD51V0VbUURTKsmdswkQQusIvlvmTyhHlIT1hBvaSxzdxpSle857XuXa7uc02UEZx9OR5aDxSWS5Qw==", "_location": "/node-gyp", - "_phantomChildren": { - "abbrev": "1.1.1" - }, + "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, - "raw": "node-gyp@5.0.5", + "raw": "node-gyp@5.0.7", "name": "node-gyp", "escapedName": "node-gyp", - "rawSpec": "5.0.5", + "rawSpec": "5.0.7", "saveSpec": null, - "fetchSpec": "5.0.5" + "fetchSpec": "5.0.7" }, "_requiredBy": [ "#USER", "/", "/npm-lifecycle" ], - "_resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-5.0.5.tgz", - "_shasum": "f6cf1da246eb8c42b097d7cd4d6c3ce23a4163af", - "_spec": "node-gyp@5.0.5", - "_where": "/Users/isaacs/dev/npm/cli", + "_resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-5.0.7.tgz", + "_shasum": "dd4225e735e840cf2870e4037c2ed9c28a31719e", + "_spec": "node-gyp@5.0.7", + "_where": "/Users/mperrotte/npminc/cli", "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://tootallnate.net" }, "bin": { - "node-gyp": "./bin/node-gyp.js" + "node-gyp": "bin/node-gyp.js" }, "bugs": { "url": "https://github.com/nodejs/node-gyp/issues" }, "bundleDependencies": false, "dependencies": { - "env-paths": "^1.0.0", - "glob": "^7.0.3", - "graceful-fs": "^4.1.2", - "mkdirp": "^0.5.0", - "nopt": "2 || 3", - "npmlog": "0 || 1 || 2 || 3 || 4", - "request": "^2.87.0", - "rimraf": "2", - "semver": "~5.3.0", + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.2", + "mkdirp": "^0.5.1", + "nopt": "^4.0.1", + "npmlog": "^4.1.2", + "request": "^2.88.0", + "rimraf": "^2.6.3", + "semver": "^5.7.1", "tar": "^4.4.12", - "which": "1" + "which": "^1.3.1" }, "deprecated": false, "description": "Node.js native addon build tool", "devDependencies": { - "bindings": "~1.2.1", - "nan": "^2.0.0", - "require-inject": "~1.3.0", - "standard": "~14.3.1", + "bindings": "^1.5.0", + "nan": "^2.14.0", + "require-inject": "^1.4.4", + "standard": "^14.3.1", "tap": "~12.7.0" }, "engines": { @@ -86,5 +84,5 @@ "lint": "standard */*.js test/**/*.js", "test": "npm run lint && tap --timeout=120 test/test-*" }, - "version": "5.0.5" + "version": "5.0.7" } diff --git a/deps/npm/node_modules/node-gyp/test/common.js b/deps/npm/node_modules/node-gyp/test/common.js new file mode 100644 index 00000000000000..b714ee29029d36 --- /dev/null +++ b/deps/npm/node_modules/node-gyp/test/common.js @@ -0,0 +1,3 @@ +const envPaths = require('env-paths') + +module.exports.devDir = () => envPaths('node-gyp', { suffix: '' }).cache diff --git a/deps/npm/node_modules/node-gyp/test/test-configure-python.js b/deps/npm/node_modules/node-gyp/test/test-configure-python.js index 518bf036d0ecb3..d08f9e5ed38efd 100644 --- a/deps/npm/node_modules/node-gyp/test/test-configure-python.js +++ b/deps/npm/node_modules/node-gyp/test/test-configure-python.js @@ -2,6 +2,7 @@ const test = require('tap').test const path = require('path') +const devDir = require('./common').devDir() const gyp = require('../lib/node-gyp') const requireInject = require('require-inject') const configure = requireInject('../lib/configure', { @@ -30,6 +31,7 @@ test('configure PYTHONPATH with no existing env', function (t) { t.equal(process.env.PYTHONPATH, EXPECTED_PYPATH) return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) @@ -49,6 +51,7 @@ test('configure PYTHONPATH with existing env of one dir', function (t) { return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) @@ -70,5 +73,6 @@ test('configure PYTHONPATH with existing env of multiple dirs', function (t) { return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) diff --git a/deps/npm/node_modules/node-gyp/test/test-download.js b/deps/npm/node_modules/node-gyp/test/test-download.js index dbffb20246267b..738a43f276b093 100644 --- a/deps/npm/node_modules/node-gyp/test/test-download.js +++ b/deps/npm/node_modules/node-gyp/test/test-download.js @@ -6,8 +6,13 @@ const path = require('path') const http = require('http') const https = require('https') const install = require('../lib/install') +const semver = require('semver') +const devDir = require('./common').devDir() +const rimraf = require('rimraf') +const gyp = require('../lib/node-gyp') +const log = require('npmlog') -require('npmlog').level = 'warn' +log.level = 'warn' test('download over http', function (t) { t.plan(2) @@ -103,3 +108,66 @@ test('check certificate splitting', function (t) { t.strictEqual(cas.length, 2) t.notStrictEqual(cas[0], cas[1]) }) + +// only run this test if we are running a version of Node with predictable version path behavior + +test('download headers (actual)', function (t) { + if (process.env.FAST_TEST || + process.release.name !== 'node' || + semver.prerelease(process.version) !== null || + semver.satisfies(process.version, '<10')) { + return t.skip('Skipping acutal download of headers due to test environment configuration') + } + + t.plan(17) + + const expectedDir = path.join(devDir, process.version.replace(/^v/, '')) + rimraf(expectedDir, (err) => { + t.ifError(err) + + const prog = gyp() + prog.parseArgv([]) + prog.devDir = devDir + log.level = 'warn' + install(prog, [], (err) => { + t.ifError(err) + + fs.readFile(path.join(expectedDir, 'installVersion'), 'utf8', (err, data) => { + t.ifError(err) + t.strictEqual(data, '9\n', 'correct installVersion') + }) + + fs.readdir(path.join(expectedDir, 'include/node'), (err, list) => { + t.ifError(err) + + t.ok(list.includes('common.gypi')) + t.ok(list.includes('config.gypi')) + t.ok(list.includes('node.h')) + t.ok(list.includes('node_version.h')) + t.ok(list.includes('openssl')) + t.ok(list.includes('uv')) + t.ok(list.includes('uv.h')) + t.ok(list.includes('v8-platform.h')) + t.ok(list.includes('v8.h')) + t.ok(list.includes('zlib.h')) + }) + + fs.readFile(path.join(expectedDir, 'include/node/node_version.h'), 'utf8', (err, contents) => { + t.ifError(err) + + const lines = contents.split('\n') + + // extract the 3 version parts from the defines to build a valid version string and + // and check them against our current env version + const version = ['major', 'minor', 'patch'].reduce((version, type) => { + const re = new RegExp(`^#define\\sNODE_${type.toUpperCase()}_VERSION`) + const line = lines.find((l) => re.test(l)) + const i = line ? parseInt(line.replace(/^[^0-9]+([0-9]+).*$/, '$1'), 10) : 'ERROR' + return `${version}${type !== 'major' ? '.' : 'v'}${i}` + }, '') + + t.strictEqual(version, process.version) + }) + }) + }) +}) diff --git a/deps/npm/node_modules/os-locale/index.js b/deps/npm/node_modules/os-locale/index.js index 1ada7a4949c7c6..8c73c99f20e2f1 100644 --- a/deps/npm/node_modules/os-locale/index.js +++ b/deps/npm/node_modules/os-locale/index.js @@ -3,33 +3,51 @@ const execa = require('execa'); const lcid = require('lcid'); const mem = require('mem'); -const defaultOpts = {spawn: true}; +const defaultOptions = {spawn: true}; const defaultLocale = 'en_US'; -function getEnvLocale(env) { - env = env || process.env; +function getEnvLocale(env = process.env) { return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE; } -function parseLocale(x) { - const env = x.split('\n').reduce((env, def) => { - def = def.split('='); - env[def[0]] = def[1].replace(/^"|"$/g, ''); +function parseLocale(string) { + const env = string.split('\n').reduce((env, def) => { + const [key, value] = def.split('='); + env[key] = value.replace(/^"|"$/g, ''); return env; }, {}); + return getEnvLocale(env); } -function getLocale(str) { - return (str && str.replace(/[.:].*/, '')); +function getLocale(string) { + return (string && string.replace(/[.:].*/, '')); +} + +function getLocales() { + return execa.stdout('locale', ['-a']); +} + +function getLocalesSync() { + return execa.sync('locale', ['-a']).stdout; +} + +function getSupportedLocale(locale, locales = '') { + return locales.includes(locale) ? locale : defaultLocale; } function getAppleLocale() { - return execa.stdout('defaults', ['read', '-g', 'AppleLocale']); + return Promise.all([ + execa.stdout('defaults', ['read', '-globalDomain', 'AppleLocale']), + getLocales() + ]).then(results => getSupportedLocale(results[0], results[1])); } function getAppleLocaleSync() { - return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout; + return getSupportedLocale( + execa.sync('defaults', ['read', '-globalDomain', 'AppleLocale']).stdout, + getLocalesSync() + ); } function getUnixLocale() { @@ -58,17 +76,16 @@ function getWinLocale() { } function getWinLocaleSync() { - const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout; + const {stdout} = execa.sync('wmic', ['os', 'get', 'locale']); const lcidCode = parseInt(stdout.replace('Locale', ''), 16); return lcid.from(lcidCode); } -module.exports = mem(opts => { - opts = opts || defaultOpts; +module.exports = mem((options = defaultOptions) => { const envLocale = getEnvLocale(); - let thenable; - if (envLocale || opts.spawn === false) { + let thenable; + if (envLocale || options.spawn === false) { thenable = Promise.resolve(getLocale(envLocale)); } else if (process.platform === 'win32') { thenable = getWinLocale(); @@ -76,25 +93,21 @@ module.exports = mem(opts => { thenable = getUnixLocale(); } - return thenable.then(locale => locale || defaultLocale) + return thenable + .then(locale => locale || defaultLocale) .catch(() => defaultLocale); }); -module.exports.sync = mem(opts => { - opts = opts || defaultOpts; +module.exports.sync = mem((options = defaultOptions) => { const envLocale = getEnvLocale(); - let res; - if (envLocale || opts.spawn === false) { + let res; + if (envLocale || options.spawn === false) { res = getLocale(envLocale); } else { try { - if (process.platform === 'win32') { - res = getWinLocaleSync(); - } else { - res = getUnixLocaleSync(); - } - } catch (err) {} + res = process.platform === 'win32' ? getWinLocaleSync() : getUnixLocaleSync(); + } catch (_) {} } return res || defaultLocale; diff --git a/deps/npm/node_modules/os-locale/license b/deps/npm/node_modules/os-locale/license index 654d0bfe943437..e7af2f77107d73 100644 --- a/deps/npm/node_modules/os-locale/license +++ b/deps/npm/node_modules/os-locale/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md new file mode 100644 index 00000000000000..ded9620b18d252 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md @@ -0,0 +1,100 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02) + + +### Bug Fixes + +* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005) + + + + +## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31) + + +### Bug Fixes + +* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90) + + + + +## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23) + + + + +## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23) + + + + +## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23) + + + + +# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23) + + +### Bug Fixes + +* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51) +* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Features + +* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Chores + +* upgrade tooling +* upgrate project to es6 (node v4) + + +### BREAKING CHANGES + +* remove support for older nodejs versions, only `node >= 4` is supported + + + +## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0) + + + +## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS v7 + + + +# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30) + + +## Features + +* add support for `options.shell` +* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module + + +## Chores + +* refactor some code to make it more clear +* update README caveats diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE new file mode 100644 index 00000000000000..8407b9a30f51b0 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Made With MOXY Lda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md new file mode 100644 index 00000000000000..72c718c9d5bec2 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md @@ -0,0 +1,94 @@ +# cross-spawn + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [![Greenkeeper badge][greenkeeper-image]][greenkeeper-url] + +[npm-url]:https://npmjs.org/package/cross-spawn +[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg +[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg +[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn +[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg +[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn +[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg +[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn +[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg +[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn +[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg +[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev +[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg +[greenkeeper-image]:https://badges.greenkeeper.io/moxystudio/node-cross-spawn.svg +[greenkeeper-url]:https://greenkeeper.io/ + +A cross platform solution to node's spawn and spawnSync. + + +## Installation + +`$ npm install cross-spawn` + + +## Why + +Node has issues when using spawn on Windows: + +- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) +- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) +- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) +- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) +- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) +- No `options.shell` support on node `` where `` must not contain any arguments. +If you would like to have the shebang support improved, feel free to contribute via a pull-request. + +Remember to always test your code on Windows! + + +## Tests + +`$ npm test` +`$ npm test -- --watch` during development + +## License + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js new file mode 100644 index 00000000000000..5509742ca9fa8f --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js @@ -0,0 +1,39 @@ +'use strict'; + +const cp = require('child_process'); +const parse = require('./lib/parse'); +const enoent = require('./lib/enoent'); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js new file mode 100644 index 00000000000000..14df9b623d0a20 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js @@ -0,0 +1,59 @@ +'use strict'; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed, 'spawn'); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js new file mode 100644 index 00000000000000..962827a94e8c07 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js @@ -0,0 +1,125 @@ +'use strict'; + +const path = require('path'); +const niceTry = require('nice-try'); +const resolveCommand = require('./util/resolveCommand'); +const escape = require('./util/escape'); +const readShebang = require('./util/readShebang'); +const semver = require('semver'); + +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0 +const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parseShell(parsed) { + // If node supports the shell option, there's no need to mimic its behavior + if (supportsShellOption) { + return parsed; + } + + // Mimic node shell option + // See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + if (isWin) { + parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } else { + if (typeof parsed.options.shell === 'string') { + parsed.command = parsed.options.shell; + } else if (process.platform === 'android') { + parsed.command = '/system/bin/sh'; + } else { + parsed.command = '/bin/sh'; + } + + parsed.args = ['-c', shellCommand]; + } + + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parseShell(parsed) : parseNonShell(parsed); +} + +module.exports = parse; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js new file mode 100644 index 00000000000000..b0bb84c3a14092 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js @@ -0,0 +1,45 @@ +'use strict'; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js new file mode 100644 index 00000000000000..bd4f1280c9cadb --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js @@ -0,0 +1,32 @@ +'use strict'; + +const fs = require('fs'); +const shebangCommand = require('shebang-command'); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + let buffer; + + if (Buffer.alloc) { + // Node.js v4.5+ / v5.10+ + buffer = Buffer.alloc(size); + } else { + // Old Node.js API + buffer = new Buffer(size); + buffer.fill(0); // zero-fill + } + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +module.exports = readShebang; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js new file mode 100644 index 00000000000000..2fd5ad27056078 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js @@ -0,0 +1,47 @@ +'use strict'; + +const path = require('path'); +const which = require('which'); +const pathKey = require('path-key')(); + +function resolveCommandAttempt(parsed, withoutPathExt) { + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (hasCustomCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: (parsed.options.env || process.env)[pathKey], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + process.chdir(cwd); + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +module.exports = resolveCommand; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json new file mode 100644 index 00000000000000..3fdff9f498b270 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json @@ -0,0 +1,107 @@ +{ + "_from": "cross-spawn@^6.0.0", + "_id": "cross-spawn@6.0.5", + "_inBundle": false, + "_integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "_location": "/os-locale/cross-spawn", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cross-spawn@^6.0.0", + "name": "cross-spawn", + "escapedName": "cross-spawn", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/os-locale/execa" + ], + "_resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "_shasum": "4a5ec7c64dfae22c3a14124dbacdee846d80cbc4", + "_spec": "cross-spawn@^6.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale/node_modules/execa", + "author": { + "name": "André Cruz", + "email": "andre@moxy.studio" + }, + "bugs": { + "url": "https://github.com/moxystudio/node-cross-spawn/issues" + }, + "bundleDependencies": false, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "dependencies": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "deprecated": false, + "description": "Cross platform child_process#spawn and child_process#spawnSync", + "devDependencies": { + "@commitlint/cli": "^6.0.0", + "@commitlint/config-conventional": "^6.0.2", + "babel-core": "^6.26.0", + "babel-jest": "^22.1.0", + "babel-preset-moxy": "^2.2.1", + "eslint": "^4.3.0", + "eslint-config-moxy": "^5.0.0", + "husky": "^0.14.3", + "jest": "^22.0.0", + "lint-staged": "^7.0.0", + "mkdirp": "^0.5.1", + "regenerator-runtime": "^0.11.1", + "rimraf": "^2.6.2", + "standard-version": "^4.2.0" + }, + "engines": { + "node": ">=4.8" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/moxystudio/node-cross-spawn", + "keywords": [ + "spawn", + "spawnSync", + "windows", + "cross-platform", + "path-ext", + "shebang", + "cmd", + "execute" + ], + "license": "MIT", + "lint-staged": { + "*.js": [ + "eslint --fix", + "git add" + ] + }, + "main": "index.js", + "name": "cross-spawn", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/moxystudio/node-cross-spawn.git" + }, + "scripts": { + "commitmsg": "commitlint -e $GIT_PARAMS", + "lint": "eslint .", + "precommit": "lint-staged", + "prerelease": "npm t && npm run lint", + "release": "standard-version", + "test": "jest --env node --coverage" + }, + "standard-version": { + "scripts": { + "posttag": "git push --follow-tags origin master && npm publish" + } + }, + "version": "6.0.5" +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/index.js b/deps/npm/node_modules/os-locale/node_modules/execa/index.js new file mode 100644 index 00000000000000..aad9ac88775cbc --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/index.js @@ -0,0 +1,361 @@ +'use strict'; +const path = require('path'); +const childProcess = require('child_process'); +const crossSpawn = require('cross-spawn'); +const stripEof = require('strip-eof'); +const npmRunPath = require('npm-run-path'); +const isStream = require('is-stream'); +const _getStream = require('get-stream'); +const pFinally = require('p-finally'); +const onExit = require('signal-exit'); +const errname = require('./lib/errname'); +const stdio = require('./lib/stdio'); + +const TEN_MEGABYTES = 1000 * 1000 * 10; + +function handleArgs(cmd, args, opts) { + let parsed; + + opts = Object.assign({ + extendEnv: true, + env: {} + }, opts); + + if (opts.extendEnv) { + opts.env = Object.assign({}, process.env, opts.env); + } + + if (opts.__winShell === true) { + delete opts.__winShell; + parsed = { + command: cmd, + args, + options: opts, + file: cmd, + original: { + cmd, + args + } + }; + } else { + parsed = crossSpawn._parse(cmd, args, opts); + } + + opts = Object.assign({ + maxBuffer: TEN_MEGABYTES, + buffer: true, + stripEof: true, + preferLocal: true, + localDir: parsed.options.cwd || process.cwd(), + encoding: 'utf8', + reject: true, + cleanup: true + }, parsed.options); + + opts.stdio = stdio(opts); + + if (opts.preferLocal) { + opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir})); + } + + if (opts.detached) { + // #115 + opts.cleanup = false; + } + + if (process.platform === 'win32' && path.basename(parsed.command) === 'cmd.exe') { + // #116 + parsed.args.unshift('/q'); + } + + return { + cmd: parsed.command, + args: parsed.args, + opts, + parsed + }; +} + +function handleInput(spawned, input) { + if (input === null || input === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +} + +function handleOutput(opts, val) { + if (val && opts.stripEof) { + val = stripEof(val); + } + + return val; +} + +function handleShell(fn, cmd, opts) { + let file = '/bin/sh'; + let args = ['-c', cmd]; + + opts = Object.assign({}, opts); + + if (process.platform === 'win32') { + opts.__winShell = true; + file = process.env.comspec || 'cmd.exe'; + args = ['/s', '/c', `"${cmd}"`]; + opts.windowsVerbatimArguments = true; + } + + if (opts.shell) { + file = opts.shell; + delete opts.shell; + } + + return fn(file, args, opts); +} + +function getStream(process, stream, {encoding, buffer, maxBuffer}) { + if (!process[stream]) { + return null; + } + + let ret; + + if (!buffer) { + // TODO: Use `ret = util.promisify(stream.finished)(process[stream]);` when targeting Node.js 10 + ret = new Promise((resolve, reject) => { + process[stream] + .once('end', resolve) + .once('error', reject); + }); + } else if (encoding) { + ret = _getStream(process[stream], { + encoding, + maxBuffer + }); + } else { + ret = _getStream.buffer(process[stream], {maxBuffer}); + } + + return ret.catch(err => { + err.stream = stream; + err.message = `${stream} ${err.message}`; + throw err; + }); +} + +function makeError(result, options) { + const {stdout, stderr} = result; + + let err = result.error; + const {code, signal} = result; + + const {parsed, joinedCmd} = options; + const timedOut = options.timedOut || false; + + if (!err) { + let output = ''; + + if (Array.isArray(parsed.opts.stdio)) { + if (parsed.opts.stdio[2] !== 'inherit') { + output += output.length > 0 ? stderr : `\n${stderr}`; + } + + if (parsed.opts.stdio[1] !== 'inherit') { + output += `\n${stdout}`; + } + } else if (parsed.opts.stdio !== 'inherit') { + output = `\n${stderr}${stdout}`; + } + + err = new Error(`Command failed: ${joinedCmd}${output}`); + err.code = code < 0 ? errname(code) : code; + } + + err.stdout = stdout; + err.stderr = stderr; + err.failed = true; + err.signal = signal || null; + err.cmd = joinedCmd; + err.timedOut = timedOut; + + return err; +} + +function joinCmd(cmd, args) { + let joinedCmd = cmd; + + if (Array.isArray(args) && args.length > 0) { + joinedCmd += ' ' + args.join(' '); + } + + return joinedCmd; +} + +module.exports = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const {encoding, buffer, maxBuffer} = parsed.opts; + const joinedCmd = joinCmd(cmd, args); + + let spawned; + try { + spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts); + } catch (err) { + return Promise.reject(err); + } + + let removeExitHandler; + if (parsed.opts.cleanup) { + removeExitHandler = onExit(() => { + spawned.kill(); + }); + } + + let timeoutId = null; + let timedOut = false; + + const cleanup = () => { + if (timeoutId) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (removeExitHandler) { + removeExitHandler(); + } + }; + + if (parsed.opts.timeout > 0) { + timeoutId = setTimeout(() => { + timeoutId = null; + timedOut = true; + spawned.kill(parsed.opts.killSignal); + }, parsed.opts.timeout); + } + + const processDone = new Promise(resolve => { + spawned.on('exit', (code, signal) => { + cleanup(); + resolve({code, signal}); + }); + + spawned.on('error', err => { + cleanup(); + resolve({error: err}); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', err => { + cleanup(); + resolve({error: err}); + }); + } + }); + + function destroy() { + if (spawned.stdout) { + spawned.stdout.destroy(); + } + + if (spawned.stderr) { + spawned.stderr.destroy(); + } + } + + const handlePromise = () => pFinally(Promise.all([ + processDone, + getStream(spawned, 'stdout', {encoding, buffer, maxBuffer}), + getStream(spawned, 'stderr', {encoding, buffer, maxBuffer}) + ]).then(arr => { + const result = arr[0]; + result.stdout = arr[1]; + result.stderr = arr[2]; + + if (result.error || result.code !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed, + timedOut + }); + + // TODO: missing some timeout logic for killed + // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203 + // err.killed = spawned.killed || killed; + err.killed = err.killed || spawned.killed; + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + killed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; + }), destroy); + + crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); + + handleInput(spawned, parsed.opts.input); + + spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected); + spawned.catch = onrejected => handlePromise().catch(onrejected); + + return spawned; +}; + +// TODO: set `stderr: 'ignore'` when that option is implemented +module.exports.stdout = (...args) => module.exports(...args).then(x => x.stdout); + +// TODO: set `stdout: 'ignore'` when that option is implemented +module.exports.stderr = (...args) => module.exports(...args).then(x => x.stderr); + +module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts); + +module.exports.sync = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const joinedCmd = joinCmd(cmd, args); + + if (isStream(parsed.opts.input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } + + const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts); + result.code = result.status; + + if (result.error || result.status !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed + }); + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; +}; + +module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts); diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js b/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js new file mode 100644 index 00000000000000..a93a435dfc6663 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js @@ -0,0 +1,38 @@ +'use strict'; +// Older verions of Node.js might not have `util.getSystemErrorName()`. +// In that case, fall back to a deprecated internal. +const util = require('util'); + +let uv; + +if (typeof util.getSystemErrorName === 'function') { + module.exports = util.getSystemErrorName; +} else { + try { + uv = process.binding('uv'); + + if (typeof uv.errname !== 'function') { + throw new TypeError('uv.errname is not a function'); + } + } catch (err) { + console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); + uv = null; + } + + module.exports = code => errname(uv, code); +} + +// Used for testing the fallback behavior +module.exports.__test__ = errname; + +function errname(uv, code) { + if (uv) { + return uv.errname(code); + } + + if (!(code < 0)) { + throw new Error('err >= 0'); + } + + return `Unknown system error ${code}`; +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js b/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js new file mode 100644 index 00000000000000..a82d46838ac9b9 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js @@ -0,0 +1,41 @@ +'use strict'; +const alias = ['stdin', 'stdout', 'stderr']; + +const hasAlias = opts => alias.some(x => Boolean(opts[x])); + +module.exports = opts => { + if (!opts) { + return null; + } + + if (opts.stdio && hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); + } + + if (typeof opts.stdio === 'string') { + return opts.stdio; + } + + const stdio = opts.stdio || []; + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const result = []; + const len = Math.max(stdio.length, alias.length); + + for (let i = 0; i < len; i++) { + let value = null; + + if (stdio[i] !== undefined) { + value = stdio[i]; + } else if (opts[alias[i]] !== undefined) { + value = opts[alias[i]]; + } + + result[i] = value; + } + + return result; +}; diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/license b/deps/npm/node_modules/os-locale/node_modules/execa/license new file mode 100644 index 00000000000000..e7af2f77107d73 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/package.json b/deps/npm/node_modules/os-locale/node_modules/execa/package.json new file mode 100644 index 00000000000000..7ab0a5777c7cd5 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/package.json @@ -0,0 +1,101 @@ +{ + "_from": "execa@^1.0.0", + "_id": "execa@1.0.0", + "_inBundle": false, + "_integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "_location": "/os-locale/execa", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "execa@^1.0.0", + "name": "execa", + "escapedName": "execa", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/os-locale" + ], + "_resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "_shasum": "c6236a5bb4df6d6f15e88e7f017798216749ddd8", + "_spec": "execa@^1.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/execa/issues" + }, + "bundleDependencies": false, + "dependencies": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "deprecated": false, + "description": "A better `child_process`", + "devDependencies": { + "ava": "*", + "cat-names": "^1.0.2", + "coveralls": "^3.0.1", + "delay": "^3.0.0", + "is-running": "^2.0.0", + "nyc": "^13.0.1", + "tempfile": "^2.0.0", + "xo": "*" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/sindresorhus/execa#readme", + "keywords": [ + "exec", + "child", + "process", + "execute", + "fork", + "execfile", + "spawn", + "file", + "shell", + "bin", + "binary", + "binaries", + "npm", + "path", + "local" + ], + "license": "MIT", + "name": "execa", + "nyc": { + "reporter": [ + "text", + "lcov" + ], + "exclude": [ + "**/fixtures/**", + "**/test.js", + "**/test/**" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/execa.git" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "version": "1.0.0" +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/readme.md b/deps/npm/node_modules/os-locale/node_modules/execa/readme.md new file mode 100644 index 00000000000000..f3f533d92915eb --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/readme.md @@ -0,0 +1,327 @@ +# execa [![Build Status: Linux](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/x5ajamxtjtt93cqv/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/execa/branch/master) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master) + +> A better [`child_process`](https://nodejs.org/api/child_process.html) + + +## Why + +- Promise interface. +- [Strips EOF](https://github.com/sindresorhus/strip-eof) from the output so you don't have to `stdout.trim()`. +- Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform. +- [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why) +- Higher max buffer. 10 MB instead of 200 KB. +- [Executes locally installed binaries by name.](#preferlocal) +- [Cleans up spawned processes when the parent process dies.](#cleanup) + + +## Install + +``` +$ npm install execa +``` + + + + + + +## Usage + +```js +const execa = require('execa'); + +(async () => { + const {stdout} = await execa('echo', ['unicorns']); + console.log(stdout); + //=> 'unicorns' +})(); +``` + +Additional examples: + +```js +const execa = require('execa'); + +(async () => { + // Pipe the child process stdout to the current stdout + execa('echo', ['unicorns']).stdout.pipe(process.stdout); + + + // Run a shell command + const {stdout} = await execa.shell('echo unicorns'); + //=> 'unicorns' + + + // Catching an error + try { + await execa.shell('exit 3'); + } catch (error) { + console.log(error); + /* + { + message: 'Command failed: /bin/sh -c exit 3' + killed: false, + code: 3, + signal: null, + cmd: '/bin/sh -c exit 3', + stdout: '', + stderr: '', + timedOut: false + } + */ + } +})(); + +// Catching an error with a sync method +try { + execa.shellSync('exit 3'); +} catch (error) { + console.log(error); + /* + { + message: 'Command failed: /bin/sh -c exit 3' + code: 3, + signal: null, + cmd: '/bin/sh -c exit 3', + stdout: '', + stderr: '', + timedOut: false + } + */ +} +``` + + +## API + +### execa(file, [arguments], [options]) + +Execute a file. + +Think of this as a mix of `child_process.execFile` and `child_process.spawn`. + +Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties. + +### execa.stdout(file, [arguments], [options]) + +Same as `execa()`, but returns only `stdout`. + +### execa.stderr(file, [arguments], [options]) + +Same as `execa()`, but returns only `stderr`. + +### execa.shell(command, [options]) + +Execute a command through the system shell. Prefer `execa()` whenever possible, as it's both faster and safer. + +Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess). + +The `child_process` instance is enhanced to also be promise for a result object with `stdout` and `stderr` properties. + +### execa.sync(file, [arguments], [options]) + +Execute a file synchronously. + +Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options). + +This method throws an `Error` if the command fails. + +### execa.shellSync(file, [options]) + +Execute a command synchronously through the system shell. + +Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options). + +### options + +Type: `Object` + +#### cwd + +Type: `string`
+Default: `process.cwd()` + +Current working directory of the child process. + +#### env + +Type: `Object`
+Default: `process.env` + +Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this. + +#### extendEnv + +Type: `boolean`
+Default: `true` + +Set to `false` if you don't want to extend the environment variables when providing the `env` property. + +#### argv0 + +Type: `string` + +Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified. + +#### stdio + +Type: `string[]` `string`
+Default: `pipe` + +Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration. + +#### detached + +Type: `boolean` + +Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached). + +#### uid + +Type: `number` + +Sets the user identity of the process. + +#### gid + +Type: `number` + +Sets the group identity of the process. + +#### shell + +Type: `boolean` `string`
+Default: `false` + +If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows. + +#### stripEof + +Type: `boolean`
+Default: `true` + +[Strip EOF](https://github.com/sindresorhus/strip-eof) (last newline) from the output. + +#### preferLocal + +Type: `boolean`
+Default: `true` + +Prefer locally installed binaries when looking for a binary to execute.
+If you `$ npm install foo`, you can then `execa('foo')`. + +#### localDir + +Type: `string`
+Default: `process.cwd()` + +Preferred path to find locally installed binaries in (use with `preferLocal`). + +#### input + +Type: `string` `Buffer` `stream.Readable` + +Write some input to the `stdin` of your binary.
+Streams are not allowed when using the synchronous methods. + +#### reject + +Type: `boolean`
+Default: `true` + +Setting this to `false` resolves the promise with the error instead of rejecting it. + +#### cleanup + +Type: `boolean`
+Default: `true` + +Keep track of the spawned process and `kill` it when the parent process exits. + +#### encoding + +Type: `string`
+Default: `utf8` + +Specify the character encoding used to decode the `stdout` and `stderr` output. + +#### timeout + +Type: `number`
+Default: `0` + +If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds. + +#### buffer + +Type: `boolean`
+Default: `true` + +Buffer the output from the spawned process. When buffering is disabled you must consume the output of the `stdout` and `stderr` streams because the promise will not be resolved/rejected until they have completed. + +#### maxBuffer + +Type: `number`
+Default: `10000000` (10MB) + +Largest amount of data in bytes allowed on `stdout` or `stderr`. + +#### killSignal + +Type: `string` `number`
+Default: `SIGTERM` + +Signal value to be used when the spawned process will be killed. + +#### stdin + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stdout + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stderr + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### windowsVerbatimArguments + +Type: `boolean`
+Default: `false` + +If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`. + + +## Tips + +### Save and pipe output from a child process + +Let's say you want to show the output of a child process in real-time while also saving it to a variable. + +```js +const execa = require('execa'); +const getStream = require('get-stream'); + +const stream = execa('echo', ['foo']).stdout; + +stream.pipe(process.stdout); + +getStream(stream).then(value => { + console.log('child output:', value); +}); +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/os-locale/package.json b/deps/npm/node_modules/os-locale/package.json index 3777aec6a39517..fb6646ec9974b8 100644 --- a/deps/npm/node_modules/os-locale/package.json +++ b/deps/npm/node_modules/os-locale/package.json @@ -1,27 +1,39 @@ { - "_from": "os-locale@^2.0.0", - "_id": "os-locale@2.1.0", + "_from": "os-locale@^3.1.0", + "_id": "os-locale@3.1.0", "_inBundle": false, - "_integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", + "_integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", "_location": "/os-locale", - "_phantomChildren": {}, + "_phantomChildren": { + "get-stream": "4.1.0", + "is-stream": "1.1.0", + "nice-try": "1.0.5", + "npm-run-path": "2.0.2", + "p-finally": "1.0.0", + "path-key": "2.0.1", + "semver": "5.7.1", + "shebang-command": "1.2.0", + "signal-exit": "3.0.2", + "strip-eof": "1.0.0", + "which": "1.3.1" + }, "_requested": { "type": "range", "registry": true, - "raw": "os-locale@^2.0.0", + "raw": "os-locale@^3.1.0", "name": "os-locale", "escapedName": "os-locale", - "rawSpec": "^2.0.0", + "rawSpec": "^3.1.0", "saveSpec": null, - "fetchSpec": "^2.0.0" + "fetchSpec": "^3.1.0" }, "_requiredBy": [ "/yargs" ], - "_resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", - "_shasum": "42bc2900a6b5b8bd17376c8e882b65afccf24bf2", - "_spec": "os-locale@^2.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/yargs", + "_resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", + "_shasum": "a802a6ee17f24c10483ab9935719cef4ed16bf1a", + "_spec": "os-locale@^3.1.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/yargs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -32,19 +44,19 @@ }, "bundleDependencies": false, "dependencies": { - "execa": "^0.7.0", - "lcid": "^1.0.0", - "mem": "^1.1.0" + "execa": "^1.0.0", + "lcid": "^2.0.0", + "mem": "^4.0.0" }, "deprecated": false, "description": "Get the system locale", "devDependencies": { - "ava": "*", - "import-fresh": "^2.0.0", - "xo": "*" + "ava": "^1.0.1", + "import-fresh": "^3.0.0", + "xo": "^0.23.0" }, "engines": { - "node": ">=4" + "node": ">=6" }, "files": [ "index.js" @@ -73,5 +85,5 @@ "scripts": { "test": "xo && ava" }, - "version": "2.1.0" + "version": "3.1.0" } diff --git a/deps/npm/node_modules/os-locale/readme.md b/deps/npm/node_modules/os-locale/readme.md index 7c80d33589e4bb..8f9c280eedb85e 100644 --- a/deps/npm/node_modules/os-locale/readme.md +++ b/deps/npm/node_modules/os-locale/readme.md @@ -6,11 +6,24 @@ Useful for localizing your module or app. POSIX systems: The returned locale refers to the [`LC_MESSAGE`](http://www.gnu.org/software/libc/manual/html_node/Locale-Categories.html#Locale-Categories) category, suitable for selecting the language used in the user interface for message translation. +--- + +
+ + Get professional support for 'os-locale' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- ## Install ``` -$ npm install --save os-locale +$ npm install os-locale ``` @@ -19,10 +32,10 @@ $ npm install --save os-locale ```js const osLocale = require('os-locale'); -osLocale().then(locale => { - console.log(locale); +(async () => { + console.log(await osLocale()); //=> 'en_US' -}); +})(); ``` @@ -48,6 +61,11 @@ Default: `true` Set to `false` to avoid spawning subprocesses and instead only resolve the locale from environment variables. +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + ## License MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/p-defer/index.js b/deps/npm/node_modules/p-defer/index.js new file mode 100644 index 00000000000000..eaef75e4e5f723 --- /dev/null +++ b/deps/npm/node_modules/p-defer/index.js @@ -0,0 +1,11 @@ +'use strict'; +module.exports = () => { + const ret = {}; + + ret.promise = new Promise((resolve, reject) => { + ret.resolve = resolve; + ret.reject = reject; + }); + + return ret; +}; diff --git a/deps/npm/node_modules/p-defer/license b/deps/npm/node_modules/p-defer/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/deps/npm/node_modules/p-defer/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/npm/node_modules/p-defer/package.json b/deps/npm/node_modules/p-defer/package.json new file mode 100644 index 00000000000000..ee706cd9308589 --- /dev/null +++ b/deps/npm/node_modules/p-defer/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "p-defer@1.0.0", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "p-defer@1.0.0", + "_id": "p-defer@1.0.0", + "_inBundle": false, + "_integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", + "_location": "/p-defer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "p-defer@1.0.0", + "name": "p-defer", + "escapedName": "p-defer", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/map-age-cleaner" + ], + "_resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "/Users/mperrotte/npminc/cli", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-defer/issues" + }, + "description": "Create a deferred promise", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/p-defer#readme", + "keywords": [ + "promise", + "defer", + "deferred", + "resolve", + "reject", + "lazy", + "later", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-defer", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-defer.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "1.0.0", + "xo": { + "esnext": true + } +} diff --git a/deps/npm/node_modules/p-defer/readme.md b/deps/npm/node_modules/p-defer/readme.md new file mode 100644 index 00000000000000..b94f137129d9df --- /dev/null +++ b/deps/npm/node_modules/p-defer/readme.md @@ -0,0 +1,47 @@ +# p-defer [![Build Status](https://travis-ci.org/sindresorhus/p-defer.svg?branch=master)](https://travis-ci.org/sindresorhus/p-defer) + +> Create a deferred promise + +[**Don't use this unless you know what you're doing!**](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern) Prefer the `Promise` constructor. + + +## Install + +``` +$ npm install --save p-defer +``` + + +## Usage + +```js +const pDefer = require('p-defer'); + +function delay(ms) { + const deferred = pDefer(); + setTimeout(deferred.resolve, ms, '🦄'); + return deferred.promise; +} + +delay(100).then(console.log); +//=> '🦄' +``` + +*The above is just an example. Use [`delay`](https://github.com/sindresorhus/delay) if you need to delay a promise.* + + +## API + +### pDefer() + +Returns an `Object` with a `promise` property and functions to `resolve()` and `reject()`. + + +## Related + +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/p-is-promise/index.d.ts b/deps/npm/node_modules/p-is-promise/index.d.ts new file mode 100644 index 00000000000000..662d9e0c420f60 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/index.d.ts @@ -0,0 +1,23 @@ +declare const pIsPromise: { + /** + Check if `input` is a ES2015 promise. + + @param input - Value to be checked. + + @example + ``` + import isPromise = require('p-is-promise'); + + isPromise(Promise.resolve('🦄')); + //=> true + ``` + */ + (input: unknown): input is Promise; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pIsPromise(input: unknown): input is Promise; + // export = pIsPromise; + default: typeof pIsPromise; +}; + +export = pIsPromise; diff --git a/deps/npm/node_modules/p-is-promise/index.js b/deps/npm/node_modules/p-is-promise/index.js new file mode 100644 index 00000000000000..389d38fc55f6f4 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/index.js @@ -0,0 +1,15 @@ +'use strict'; + +const isPromise = input => ( + input instanceof Promise || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) +); + +module.exports = isPromise; +// TODO: Remove this for the next major release +module.exports.default = isPromise; diff --git a/deps/npm/node_modules/p-is-promise/license b/deps/npm/node_modules/p-is-promise/license new file mode 100644 index 00000000000000..e7af2f77107d73 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/p-is-promise/package.json b/deps/npm/node_modules/p-is-promise/package.json new file mode 100644 index 00000000000000..3315effdfb15df --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "p-is-promise@2.1.0", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "p-is-promise@2.1.0", + "_id": "p-is-promise@2.1.0", + "_inBundle": false, + "_integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==", + "_location": "/p-is-promise", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "p-is-promise@2.1.0", + "name": "p-is-promise", + "escapedName": "p-is-promise", + "rawSpec": "2.1.0", + "saveSpec": null, + "fetchSpec": "2.1.0" + }, + "_requiredBy": [ + "/nyc/mem" + ], + "_resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", + "_spec": "2.1.0", + "_where": "/Users/mperrotte/npminc/cli", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-is-promise/issues" + }, + "description": "Check if something is a promise", + "devDependencies": { + "ava": "^1.4.1", + "bluebird": "^3.5.4", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/p-is-promise#readme", + "keywords": [ + "promise", + "is", + "detect", + "check", + "kind", + "type", + "thenable", + "es2015", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-is-promise", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-is-promise.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.1.0" +} diff --git a/deps/npm/node_modules/p-is-promise/readme.md b/deps/npm/node_modules/p-is-promise/readme.md new file mode 100644 index 00000000000000..0e0e48171a919d --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/readme.md @@ -0,0 +1,43 @@ +# p-is-promise [![Build Status](https://travis-ci.org/sindresorhus/p-is-promise.svg?branch=master)](https://travis-ci.org/sindresorhus/p-is-promise) + +> Check if something is a promise + +Why not [`is-promise`](https://github.com/then/is-promise)? That module [checks for a thenable](https://github.com/then/is-promise/issues/6), not an ES2015 promise. This one is stricter. + +You most likely don't need this. Just pass your value to `Promise.resolve()` and let it handle it. + +Can be useful if you need to create a fast path for a synchronous operation. + + +## Install + +``` +$ npm install p-is-promise +``` + + +## Usage + +```js +const pIsPromise = require('p-is-promise'); +const Bluebird = require('bluebird'); + +pIsPromise(Promise.resolve('🦄')); +//=> true + +pIsPromise(Bluebird.resolve('🦄')); +//=> true + +pIsPromise('🦄'); +//=> false +``` + + +## Related + +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/yargs/CHANGELOG.md b/deps/npm/node_modules/yargs/CHANGELOG.md index 0eaf2f33edddb4..2cccca04c4113c 100644 --- a/deps/npm/node_modules/yargs/CHANGELOG.md +++ b/deps/npm/node_modules/yargs/CHANGELOG.md @@ -2,6 +2,25 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +# [11.1.1](https://github.com/yargs/yargs/compare/v11.1.0...v11.1.1) (2019-10-06) + +* backport security fix for os-locale. + + +# [11.1.0](https://github.com/yargs/yargs/compare/v11.0.0...v11.1.0) (2018-03-04) + + +### Bug Fixes + +* choose correct config directory when require.main does not exist ([#1056](https://github.com/yargs/yargs/issues/1056)) ([a04678c](https://github.com/yargs/yargs/commit/a04678c)) + + +### Features + +* allow hidden options to be displayed with --show-hidden ([#1061](https://github.com/yargs/yargs/issues/1061)) ([ea862ae](https://github.com/yargs/yargs/commit/ea862ae)) +* extend *.rc files in addition to json ([#1080](https://github.com/yargs/yargs/issues/1080)) ([11691a6](https://github.com/yargs/yargs/commit/11691a6)) + # [11.0.0](https://github.com/yargs/yargs/compare/v10.1.2...v11.0.0) (2018-01-22) diff --git a/deps/npm/node_modules/yargs/lib/apply-extends.js b/deps/npm/node_modules/yargs/lib/apply-extends.js index 3005848e3cdb78..530b022ac57b5a 100644 --- a/deps/npm/node_modules/yargs/lib/apply-extends.js +++ b/deps/npm/node_modules/yargs/lib/apply-extends.js @@ -6,9 +6,9 @@ const YError = require('./yerror') let previouslyVisitedConfigs = [] -function checkForCircularExtends (path) { - if (previouslyVisitedConfigs.indexOf(path) > -1) { - throw new YError(`Circular extended configurations: '${path}'.`) +function checkForCircularExtends (cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`) } } diff --git a/deps/npm/node_modules/yargs/package.json b/deps/npm/node_modules/yargs/package.json index 1fe51fedd4392b..fd0a1265c23ddb 100644 --- a/deps/npm/node_modules/yargs/package.json +++ b/deps/npm/node_modules/yargs/package.json @@ -1,8 +1,8 @@ { "_from": "yargs@^11.0.0", - "_id": "yargs@11.0.0", + "_id": "yargs@11.1.1", "_inBundle": false, - "_integrity": "sha512-Rjp+lMYQOWtgqojx1dEWorjCofi1YN7AoFvYV7b1gx/7dAAeuI4kN5SZiEvr0ZmsZTOpDRcCqrpI10L31tFkBw==", + "_integrity": "sha512-PRU7gJrJaXv3q3yQZ/+/X6KBswZiaQ+zOmdprZcouPYtQgvNU35i+68M4b1ZHLZtYFT5QObFLV+ZkmJYcwKdiw==", "_location": "/yargs", "_phantomChildren": {}, "_requested": { @@ -18,10 +18,10 @@ "_requiredBy": [ "/libnpx" ], - "_resolved": "https://registry.npmjs.org/yargs/-/yargs-11.0.0.tgz", - "_shasum": "c052931006c5eee74610e5fc0354bedfd08a201b", + "_resolved": "https://registry.npmjs.org/yargs/-/yargs-11.1.1.tgz", + "_shasum": "5052efe3446a4df5ed669c995886cc0f13702766", "_spec": "yargs@^11.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/libnpx", + "_where": "/Users/mperrotte/npminc/cli/node_modules/libnpx", "bugs": { "url": "https://github.com/yargs/yargs/issues" }, @@ -31,7 +31,7 @@ "decamelize": "^1.1.1", "find-up": "^2.1.0", "get-caller-file": "^1.0.1", - "os-locale": "^2.0.0", + "os-locale": "^3.1.0", "require-directory": "^2.1.1", "require-main-filename": "^1.0.1", "set-blocking": "^2.0.0", @@ -47,7 +47,7 @@ "chalk": "^1.1.3", "coveralls": "^2.11.11", "cpr": "^2.0.0", - "cross-spawn": "^5.0.1", + "cross-spawn": "^6.0.4", "es6-promise": "^4.0.2", "hashish": "0.0.4", "mocha": "^3.0.1", @@ -97,5 +97,5 @@ "**/example/**" ] }, - "version": "11.0.0" + "version": "11.1.1" } diff --git a/deps/npm/node_modules/yargs/yargs.js b/deps/npm/node_modules/yargs/yargs.js index 9b50b8bfeb0a44..38f1b2ea6e67f5 100644 --- a/deps/npm/node_modules/yargs/yargs.js +++ b/deps/npm/node_modules/yargs/yargs.js @@ -476,17 +476,17 @@ function Yargs (processArgs, cwd, parentRequire) { return self } - self.pkgConf = function pkgConf (key, path) { - argsert(' [string]', [key, path], arguments.length) + self.pkgConf = function pkgConf (key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length) let conf = null // prefer cwd to require-main-filename in this method // since we're looking for e.g. "nyc" config in nyc consumer // rather than "yargs" config in nyc (where nyc is the main filename) - const obj = pkgUp(path || cwd) + const obj = pkgUp(rootPath || cwd) // If an object exists in the key, add it to options.configObjects if (obj[key] && typeof obj[key] === 'object') { - conf = applyExtends(obj[key], path || cwd) + conf = applyExtends(obj[key], rootPath || cwd) options.configObjects = (options.configObjects || []).concat(conf) } @@ -494,16 +494,24 @@ function Yargs (processArgs, cwd, parentRequire) { } const pkgs = {} - function pkgUp (path) { - const npath = path || '*' + function pkgUp (rootPath) { + const npath = rootPath || '*' if (pkgs[npath]) return pkgs[npath] const findUp = require('find-up') let obj = {} try { + let startDir = rootPath || require('require-main-filename')(parentRequire || require) + + // When called in an environment that lacks require.main.filename, such as a jest test runner, + // startDir is already process.cwd(), and should not be shortened. + // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. + if (!rootPath && path.extname(startDir)) { + startDir = path.dirname(startDir) + } + const pkgJsonPath = findUp.sync('package.json', { - cwd: path || require('path').dirname(require('require-main-filename')(parentRequire || require)), - normalize: false + cwd: startDir }) obj = JSON.parse(fs.readFileSync(pkgJsonPath)) } catch (noop) {} diff --git a/deps/npm/package.json b/deps/npm/package.json index c5843fb74fe7f6..3c37420f4c5ec2 100644 --- a/deps/npm/package.json +++ b/deps/npm/package.json @@ -1,5 +1,5 @@ { - "version": "6.13.6", + "version": "6.13.7", "name": "npm", "description": "a package manager for JavaScript", "keywords": [ @@ -39,7 +39,7 @@ "ansistyles": "~0.1.3", "aproba": "^2.0.0", "archy": "~1.0.0", - "bin-links": "^1.1.6", + "bin-links": "^1.1.7", "bluebird": "^3.5.5", "byte-size": "^5.0.1", "cacache": "^12.0.3", @@ -80,7 +80,7 @@ "libnpmorg": "^1.0.1", "libnpmsearch": "^2.0.2", "libnpmteam": "^1.0.2", - "libnpx": "^10.2.0", + "libnpx": "^10.2.2", "lock-verify": "^2.1.0", "lockfile": "^1.0.4", "lodash._baseuniq": "~4.6.0", @@ -93,7 +93,7 @@ "mississippi": "^3.0.0", "mkdirp": "~0.5.1", "move-concurrently": "^1.0.1", - "node-gyp": "^5.0.5", + "node-gyp": "^5.0.7", "nopt": "~4.0.1", "normalize-package-data": "^2.5.0", "npm-audit-report": "^1.3.2", @@ -296,7 +296,8 @@ "licenses": "licensee --production --errors-only", "tap": "tap -J --timeout 300 --no-esm", "tap-cover": "tap -J --nyc-arg=--cache --coverage --timeout 600 --no-esm", - "pretest": "standard", + "lint": "standard", + "pretest": "npm run lint", "test": "npm run test-tap --", "test:nocleanup": "NO_TEST_CLEANUP=1 npm run test --", "sudotest": "sudo npm run tap -- \"test/tap/*.js\"", diff --git a/deps/npm/scripts/docs-build.js b/deps/npm/scripts/docs-build.js index e3cd2e9826f1e6..390ea20be706e1 100644 --- a/deps/npm/scripts/docs-build.js +++ b/deps/npm/scripts/docs-build.js @@ -15,7 +15,7 @@ fs.readFile(src, 'utf8', function (err, data) { } var result = data.replace(/@VERSION@/g, npm.version) - .replace(/---([\s\S]+)---/g, '') + .replace(/^---([\s\S]+?)---/g, '') .replace(/\[([^\]]+)\]\(\/cli-commands\/([^)]+)\)/g, replacer) .replace(/\[([^\]]+)\]\(\/configuring-npm\/([^)]+)\)/g, replacer) .replace(/\[([^\]]+)\]\(\/using-npm\/([^)]+)\)/g, replacer) diff --git a/deps/npm/scripts/release.sh b/deps/npm/scripts/release.sh index e071c7ededaf75..31fb6fa1941418 100644 --- a/deps/npm/scripts/release.sh +++ b/deps/npm/scripts/release.sh @@ -12,6 +12,8 @@ node ./bin/npm-cli.js pack --loglevel error >/dev/null mv *.tgz release cd release tar xzf *.tgz +cp ../.npmrc package/ +cp -r ../tap-snapshots package/ cp -r ../test package/ mkdir node_modules diff --git a/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js b/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js new file mode 100644 index 00000000000000..eb3183a27d7b41 --- /dev/null +++ b/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js @@ -0,0 +1,61 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/tap/fund.js TAP fund containing multi-level nested deps with no funding > should omit dependencies with no funding declared 1`] = ` +nested-no-funding-packages@1.0.0 ++-- lorem@1.0.0 +| \`-- url: https://example.com/lorem +\`-- bar@1.0.0 + +-- type: individual + +-- url: http://example.com/donate + \`-- sub-bar@1.0.0 + \`-- url: https://example.com/sponsor + + +` + +exports[`test/tap/fund.js TAP fund does not support global > should throw EFUNDGLOBAL error 1`] = ` + +` + +exports[`test/tap/fund.js TAP fund does not support global > should write error msgs to stderr 1`] = ` +npm ERR! code EFUNDGLOBAL +npm ERR! \`npm fund\` does not support globals +` + +exports[`test/tap/fund.js TAP fund does not support global, using --json option > should write error msgs to stderr 1`] = ` +npm ERR! code EFUNDGLOBAL +npm ERR! \`npm fund\` does not support globals +` + +exports[`test/tap/fund.js TAP fund in which same maintainer owns all its deps > should print stack packages together 1`] = ` +maintainer-owns-all-deps@1.0.0, dep-bar@1.0.0, dep-sub-foo@1.0.0, dep-foo@1.0.0 ++-- type: individual +\`-- url: http://example.com/donate + + +` + +exports[`test/tap/fund.js TAP fund using package argument with no browser > should open funding url 1`] = ` +individual funding available at the following URL: + +http://example.com/donate + +` + +exports[`test/tap/fund.js TAP fund using string shorthand > should open string-only url 1`] = ` +Funding available at the following URL: + +https://example.com/sponsor + +` + +exports[`test/tap/fund.js TAP fund with no package containing funding > should print empty funding info 1`] = ` +no-funding-package@0.0.0 + + +` diff --git a/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js b/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js new file mode 100644 index 00000000000000..3fba79edb8d42b --- /dev/null +++ b/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js @@ -0,0 +1,21 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/tap/repo.js TAP npm repo underscore --json > should print json result 1`] = ` +{ + "title": "repository available at the following URL", + "url": "https://github.com/jashkenas/underscore" +} + +` + +exports[`test/tap/repo.js TAP npm repo underscore --no-browser > should print alternative msg 1`] = ` +repository available at the following URL: + +https://github.com/jashkenas/underscore + +` diff --git a/deps/npm/test/fixtures/config/userconfig-with-gc b/deps/npm/test/fixtures/config/userconfig-with-gc index 866f78dab61ce5..a3a837eb78dd47 100644 --- a/deps/npm/test/fixtures/config/userconfig-with-gc +++ b/deps/npm/test/fixtures/config/userconfig-with-gc @@ -1,4 +1,4 @@ -globalconfig = /Users/ruyadorno/Documents/workspace/cli/test/fixtures/config/globalconfig +globalconfig = /Users/mperrotte/npminc/cli/test/fixtures/config/globalconfig email = i@izs.me env-thing = ${random_env_var} init.author.name = Isaac Z. Schlueter diff --git a/deps/npm/test/tap/ci.js b/deps/npm/test/tap/ci.js index f6359578055bb7..e1c2d73b7a43d5 100644 --- a/deps/npm/test/tap/ci.js +++ b/deps/npm/test/tap/ci.js @@ -15,7 +15,10 @@ const File = Tacks.File const cacheDir = common.cache const testDir = common.pkg -const EXEC_OPTS = { cwd: testDir } +const EXEC_OPTS = { + cwd: testDir, + nodeExecPath: process.execPath +} const PKG = { name: 'top', diff --git a/deps/npm/test/tap/prepare.js b/deps/npm/test/tap/prepare.js index 1169089b17e4d8..d0966000735c47 100644 --- a/deps/npm/test/tap/prepare.js +++ b/deps/npm/test/tap/prepare.js @@ -55,7 +55,11 @@ test('test', function (t) { common.npm([ 'pack', '--loglevel', 'warn' - ], { cwd: pkg, env: env }, function (err, code, stdout, stderr) { + ], { + cwd: pkg, + env: env, + nodeExecPath: process.execPath + }, function (err, code, stdout, stderr) { t.equal(code, 0, 'pack finished successfully') t.ifErr(err, 'pack finished successfully') diff --git a/deps/npm/test/tap/prepublish-only.js b/deps/npm/test/tap/prepublish-only.js index 56881494d23814..988d507c6359f4 100644 --- a/deps/npm/test/tap/prepublish-only.js +++ b/deps/npm/test/tap/prepublish-only.js @@ -98,7 +98,8 @@ test('test', function (t) { common.npm( [ 'publish', - '--loglevel', 'warn' + '--loglevel', 'warn', + '--scripts-prepend-node-path' ], { cwd: pkg, diff --git a/deps/npm/test/tap/publish-scoped.js b/deps/npm/test/tap/publish-scoped.js index 78ca4699d3a31b..82873688cdce9e 100644 --- a/deps/npm/test/tap/publish-scoped.js +++ b/deps/npm/test/tap/publish-scoped.js @@ -46,7 +46,7 @@ test('npm publish should honor scoping', function (t) { fs.writeFileSync(configFile, configuration.join('\n') + '\n') - common.npm(['publish'], {'cwd': pkg}, function (err, code, stdout, stderr) { + common.npm(['publish'], {'cwd': pkg, nodeExecPath: process.execPath}, function (err, code, stdout, stderr) { if (err) throw err t.is(code, 0, 'published without error') server.done() diff --git a/deps/npm/test/tap/publish.js b/deps/npm/test/tap/publish.js index 0913576a31b446..453abcecd47abd 100644 --- a/deps/npm/test/tap/publish.js +++ b/deps/npm/test/tap/publish.js @@ -52,7 +52,10 @@ test('basic npm publish', (t) => { `--//localhost:${server.port}/:username=username`, `--//localhost:${server.port}/:_password=` + Buffer.from('password').toString('base64'), `--//localhost:${server.port}/:email=` + 'ogd@aoaioxxysz.net' - ], {'cwd': testDir}) + ], { + 'cwd': testDir, + nodeExecPath: process.execPath + }) .spread((code, stdout, stderr) => { t.comment(stdout) t.comment(stderr) diff --git a/deps/npm/test/tap/umask-lifecycle.js b/deps/npm/test/tap/umask-lifecycle.js index 8b365d62335d79..dc365c94abbd56 100644 --- a/deps/npm/test/tap/umask-lifecycle.js +++ b/deps/npm/test/tap/umask-lifecycle.js @@ -40,12 +40,13 @@ test('setup', function (t) { }) test('umask script', function (t) { - common.npm(['run', 'umask'], { + common.npm(['run', 'umask', '--scripts-prepend-node-path'], { cwd: pkg, env: { PATH: process.env.PATH, Path: process.env.Path, - 'npm_config_loglevel': 'warn' + 'npm_config_loglevel': 'warn', + nodeExecPath: process.execPath } }, function (er, code, sout, serr) { t.equal(sout, expected) diff --git a/deps/npm/test/tap/version-no-package.js b/deps/npm/test/tap/version-no-package.js index aa553b080148a9..60c0e3be7adb90 100644 --- a/deps/npm/test/tap/version-no-package.js +++ b/deps/npm/test/tap/version-no-package.js @@ -7,7 +7,7 @@ test('npm version in a prefix with no package.json', function (t) { process.chdir(pkg) common.npm( ['version', '--json', '--prefix', pkg], - { cwd: pkg }, + { cwd: pkg, nodeExecPath: process.execPath }, function (er, code, stdout, stderr) { t.ifError(er, "npm version doesn't care that there's no package.json") t.notOk(code, 'npm version ran without barfing') diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index b57ff4716a8240..9c2146dab9da7e 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,3 +1,26 @@ +2020.01.24, Version 1.34.2 (Stable), f868c9ab0c307525a16fff99fd21e32a6ebc3837 + +Changes since version 1.34.1: + +* misc: adjust stalebot deadlines (Jameson Nash) + +* test: fix env-vars flakiness (cjihrig) + +* test: avoid truncating output lines (Jameson Nash) + +* darwin: stop calling SetApplicationIsDaemon() (Ben Noordhuis) + +* ibmi: implement uv_interface_addresses() (Xu Meng) + +* osx,fsevent: fix race during uv_loop_close (Jameson Nash) + +* osx,fsevent: clear pointer when deleting it [NFCI] (Jameson Nash) + +* Revert "aix: replace ECONNRESET with EOF if already closed" (Jameson Nash) + +* unix: handle uv__open_cloexec return value correctly (Anna Henningsen) + + 2020.01.13, Version 1.34.1 (Stable), 8aa5636ec72990bb2856f81e14c95813024a5c2b Changes since version 1.34.0: diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index ea7fea90125fd3..fba960b6b33731 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.34.1], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.34.2], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/include/uv/version.h b/deps/uv/include/uv/version.h index cfa321148039b4..623ca3ef2cba71 100644 --- a/deps/uv/include/uv/version.h +++ b/deps/uv/include/uv/version.h @@ -32,7 +32,7 @@ #define UV_VERSION_MAJOR 1 #define UV_VERSION_MINOR 34 -#define UV_VERSION_PATCH 1 +#define UV_VERSION_PATCH 2 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/src/unix/aix-common.c b/deps/uv/src/unix/aix-common.c index e96e34c46373bb..c18a5298cec6a4 100644 --- a/deps/uv/src/unix/aix-common.c +++ b/deps/uv/src/unix/aix-common.c @@ -155,183 +155,3 @@ int uv_exepath(char* buffer, size_t* size) { return UV_EINVAL; } } - - -int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { - uv_interface_address_t* address; - int sockfd, sock6fd, inet6, i, r, size = 1; - struct ifconf ifc; - struct ifreq *ifr, *p, flg; - struct in6_ifreq if6; - struct sockaddr_dl* sa_addr; - - ifc.ifc_req = NULL; - sock6fd = -1; - r = 0; - *count = 0; - *addresses = NULL; - - if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { - r = UV__ERR(errno); - goto cleanup; - } - - if (0 > (sock6fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP))) { - r = UV__ERR(errno); - goto cleanup; - } - - if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - - ifc.ifc_req = (struct ifreq*)uv__malloc(size); - if (ifc.ifc_req == NULL) { - r = UV_ENOMEM; - goto cleanup; - } - ifc.ifc_len = size; - if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - -#define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) - - /* Count all up and running ipv4/ipv6 addresses */ - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (!(p->ifr_addr.sa_family == AF_INET6 || - p->ifr_addr.sa_family == AF_INET)) - continue; - - memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); - if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - - if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) - continue; - - (*count)++; - } - - if (*count == 0) - goto cleanup; - - /* Alloc the return interface structs */ - *addresses = uv__calloc(*count, sizeof(**addresses)); - if (!(*addresses)) { - r = UV_ENOMEM; - goto cleanup; - } - address = *addresses; - - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (!(p->ifr_addr.sa_family == AF_INET6 || - p->ifr_addr.sa_family == AF_INET)) - continue; - - inet6 = (p->ifr_addr.sa_family == AF_INET6); - - memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); - if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) - goto syserror; - - if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) - continue; - - /* All conditions above must match count loop */ - - address->name = uv__strdup(p->ifr_name); - - if (inet6) - address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr); - else - address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr); - - if (inet6) { - memset(&if6, 0, sizeof(if6)); - r = uv__strscpy(if6.ifr_name, p->ifr_name, sizeof(if6.ifr_name)); - if (r == UV_E2BIG) - goto cleanup; - r = 0; - memcpy(&if6.ifr_Addr, &p->ifr_addr, sizeof(if6.ifr_Addr)); - if (ioctl(sock6fd, SIOCGIFNETMASK6, &if6) == -1) - goto syserror; - address->netmask.netmask6 = *((struct sockaddr_in6*) &if6.ifr_Addr); - /* Explicitly set family as the ioctl call appears to return it as 0. */ - address->netmask.netmask6.sin6_family = AF_INET6; - } else { - if (ioctl(sockfd, SIOCGIFNETMASK, p) == -1) - goto syserror; - address->netmask.netmask4 = *((struct sockaddr_in*) &p->ifr_addr); - /* Explicitly set family as the ioctl call appears to return it as 0. */ - address->netmask.netmask4.sin_family = AF_INET; - } - - address->is_internal = flg.ifr_flags & IFF_LOOPBACK ? 1 : 0; - - address++; - } - - /* Fill in physical addresses. */ - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (p->ifr_addr.sa_family != AF_LINK) - continue; - - address = *addresses; - for (i = 0; i < *count; i++) { - if (strcmp(address->name, p->ifr_name) == 0) { - sa_addr = (struct sockaddr_dl*) &p->ifr_addr; - memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr)); - } - address++; - } - } - -#undef ADDR_SIZE - goto cleanup; - -syserror: - uv_free_interface_addresses(*addresses, *count); - *addresses = NULL; - *count = 0; - r = UV_ENOSYS; - -cleanup: - if (sockfd != -1) - uv__close(sockfd); - if (sock6fd != -1) - uv__close(sock6fd); - uv__free(ifc.ifc_req); - return r; -} - - -void uv_free_interface_addresses(uv_interface_address_t* addresses, - int count) { - int i; - - for (i = 0; i < count; ++i) { - uv__free(addresses[i].name); - } - - uv__free(addresses); -} diff --git a/deps/uv/src/unix/aix.c b/deps/uv/src/unix/aix.c index 1f36926c02e2a8..417ee5512fa252 100644 --- a/deps/uv/src/unix/aix.c +++ b/deps/uv/src/unix/aix.c @@ -1039,6 +1039,186 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { } +int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { + uv_interface_address_t* address; + int sockfd, sock6fd, inet6, i, r, size = 1; + struct ifconf ifc; + struct ifreq *ifr, *p, flg; + struct in6_ifreq if6; + struct sockaddr_dl* sa_addr; + + ifc.ifc_req = NULL; + sock6fd = -1; + r = 0; + *count = 0; + *addresses = NULL; + + if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { + r = UV__ERR(errno); + goto cleanup; + } + + if (0 > (sock6fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP))) { + r = UV__ERR(errno); + goto cleanup; + } + + if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + + ifc.ifc_req = (struct ifreq*)uv__malloc(size); + if (ifc.ifc_req == NULL) { + r = UV_ENOMEM; + goto cleanup; + } + ifc.ifc_len = size; + if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + +#define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) + + /* Count all up and running ipv4/ipv6 addresses */ + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (!(p->ifr_addr.sa_family == AF_INET6 || + p->ifr_addr.sa_family == AF_INET)) + continue; + + memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); + if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + + if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) + continue; + + (*count)++; + } + + if (*count == 0) + goto cleanup; + + /* Alloc the return interface structs */ + *addresses = uv__calloc(*count, sizeof(**addresses)); + if (!(*addresses)) { + r = UV_ENOMEM; + goto cleanup; + } + address = *addresses; + + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (!(p->ifr_addr.sa_family == AF_INET6 || + p->ifr_addr.sa_family == AF_INET)) + continue; + + inet6 = (p->ifr_addr.sa_family == AF_INET6); + + memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); + if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) + goto syserror; + + if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) + continue; + + /* All conditions above must match count loop */ + + address->name = uv__strdup(p->ifr_name); + + if (inet6) + address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr); + else + address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr); + + if (inet6) { + memset(&if6, 0, sizeof(if6)); + r = uv__strscpy(if6.ifr_name, p->ifr_name, sizeof(if6.ifr_name)); + if (r == UV_E2BIG) + goto cleanup; + r = 0; + memcpy(&if6.ifr_Addr, &p->ifr_addr, sizeof(if6.ifr_Addr)); + if (ioctl(sock6fd, SIOCGIFNETMASK6, &if6) == -1) + goto syserror; + address->netmask.netmask6 = *((struct sockaddr_in6*) &if6.ifr_Addr); + /* Explicitly set family as the ioctl call appears to return it as 0. */ + address->netmask.netmask6.sin6_family = AF_INET6; + } else { + if (ioctl(sockfd, SIOCGIFNETMASK, p) == -1) + goto syserror; + address->netmask.netmask4 = *((struct sockaddr_in*) &p->ifr_addr); + /* Explicitly set family as the ioctl call appears to return it as 0. */ + address->netmask.netmask4.sin_family = AF_INET; + } + + address->is_internal = flg.ifr_flags & IFF_LOOPBACK ? 1 : 0; + + address++; + } + + /* Fill in physical addresses. */ + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (p->ifr_addr.sa_family != AF_LINK) + continue; + + address = *addresses; + for (i = 0; i < *count; i++) { + if (strcmp(address->name, p->ifr_name) == 0) { + sa_addr = (struct sockaddr_dl*) &p->ifr_addr; + memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr)); + } + address++; + } + } + +#undef ADDR_SIZE + goto cleanup; + +syserror: + uv_free_interface_addresses(*addresses, *count); + *addresses = NULL; + *count = 0; + r = UV_ENOSYS; + +cleanup: + if (sockfd != -1) + uv__close(sockfd); + if (sock6fd != -1) + uv__close(sock6fd); + uv__free(ifc.ifc_req); + return r; +} + + +void uv_free_interface_addresses(uv_interface_address_t* addresses, + int count) { + int i; + + for (i = 0; i < count; ++i) { + uv__free(addresses[i].name); + } + + uv__free(addresses); +} + + void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { struct pollfd* events; uintptr_t i; diff --git a/deps/uv/src/unix/darwin-proctitle.c b/deps/uv/src/unix/darwin-proctitle.c index 97eaa05391be82..2daf3e3474acff 100644 --- a/deps/uv/src/unix/darwin-proctitle.c +++ b/deps/uv/src/unix/darwin-proctitle.c @@ -72,8 +72,6 @@ int uv__set_process_title(const char* title) { CFStringRef* display_name_key; CFDictionaryRef (*pCFBundleGetInfoDictionary)(CFBundleRef); CFBundleRef (*pCFBundleGetMainBundle)(void); - CFBundleRef hi_services_bundle; - OSStatus (*pSetApplicationIsDaemon)(int); CFDictionaryRef (*pLSApplicationCheckIn)(int, CFDictionaryRef); void (*pLSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t, void*); @@ -144,30 +142,19 @@ int uv__set_process_title(const char* title) { if (pCFBundleGetInfoDictionary == NULL || pCFBundleGetMainBundle == NULL) goto out; - /* Black 10.9 magic, to remove (Not responding) mark in Activity Monitor */ - hi_services_bundle = - pCFBundleGetBundleWithIdentifier(S("com.apple.HIServices")); - err = UV_ENOENT; - if (hi_services_bundle == NULL) - goto out; - - *(void **)(&pSetApplicationIsDaemon) = pCFBundleGetFunctionPointerForName( - hi_services_bundle, - S("SetApplicationIsDaemon")); *(void **)(&pLSApplicationCheckIn) = pCFBundleGetFunctionPointerForName( launch_services_bundle, S("_LSApplicationCheckIn")); + + if (pLSApplicationCheckIn == NULL) + goto out; + *(void **)(&pLSSetApplicationLaunchServicesServerConnectionStatus) = pCFBundleGetFunctionPointerForName( launch_services_bundle, S("_LSSetApplicationLaunchServicesServerConnectionStatus")); - if (pSetApplicationIsDaemon == NULL || - pLSApplicationCheckIn == NULL || - pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) { - goto out; - } - if (pSetApplicationIsDaemon(1) != noErr) + if (pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) goto out; pLSSetApplicationLaunchServicesServerConnectionStatus(0, NULL); @@ -178,6 +165,10 @@ int uv__set_process_title(const char* title) { asn = pLSGetCurrentApplicationASN(); + err = UV_EBUSY; + if (asn == NULL) + goto out; + err = UV_EINVAL; if (pLSSetApplicationInformationItem(-2, /* Magic value. */ asn, diff --git a/deps/uv/src/unix/fsevents.c b/deps/uv/src/unix/fsevents.c index deeaa63d4730de..448921f813d789 100644 --- a/deps/uv/src/unix/fsevents.c +++ b/deps/uv/src/unix/fsevents.c @@ -747,6 +747,8 @@ static void* uv__cf_loop_runner(void* arg) { state->signal_source, *pkCFRunLoopDefaultMode); + state->loop = NULL; + return NULL; } @@ -799,13 +801,14 @@ int uv__cf_loop_signal(uv_loop_t* loop, uv_mutex_lock(&loop->cf_mutex); QUEUE_INSERT_TAIL(&loop->cf_signals, &item->member); - uv_mutex_unlock(&loop->cf_mutex); state = loop->cf_state; assert(state != NULL); pCFRunLoopSourceSignal(state->signal_source); pCFRunLoopWakeUp(state->loop); + uv_mutex_unlock(&loop->cf_mutex); + return 0; } diff --git a/deps/uv/src/unix/ibmi.c b/deps/uv/src/unix/ibmi.c index 8b355033e29ce5..4dd8bb6e3758e3 100644 --- a/deps/uv/src/unix/ibmi.c +++ b/deps/uv/src/unix/ibmi.c @@ -56,6 +56,7 @@ #include #include +#include typedef struct { @@ -98,24 +99,91 @@ typedef struct { } SSTS0200; +typedef struct { + char header[208]; + unsigned char loca_adapter_address[12]; +} LIND0500; + + +typedef struct { + int bytes_provided; + int bytes_available; + char msgid[7]; +} errcode_s; + + +static const unsigned char e2a[256] = { + 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, + 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, + 144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26, + 32, 160, 161, 162, 163, 164, 165, 166, 167, 168, 91, 46, 60, 40, 43, 33, + 38, 169, 170, 171, 172, 173, 174, 175, 176, 177, 93, 36, 42, 41, 59, 94, + 45, 47, 178, 179, 180, 181, 182, 183, 184, 185, 124, 44, 37, 95, 62, 63, + 186, 187, 188, 189, 190, 191, 192, 193, 194, 96, 58, 35, 64, 39, 61, 34, + 195, 97, 98, 99, 100, 101, 102, 103, 104, 105, 196, 197, 198, 199, 200, 201, + 202, 106, 107, 108, 109, 110, 111, 112, 113, 114, 203, 204, 205, 206, 207, 208, + 209, 126, 115, 116, 117, 118, 119, 120, 121, 122, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, + 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 232, 233, 234, 235, 236, 237, + 125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 238, 239, 240, 241, 242, 243, + 92, 159, 83, 84, 85, 86, 87, 88, 89, 90, 244, 245, 246, 247, 248, 249, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 250, 251, 252, 253, 254, 255}; + + +static const unsigned char a2e[256] = { + 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, + 64, 79, 127, 123, 91, 108, 80, 125, 77, 93, 92, 78, 107, 96, 75, 97, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 122, 94, 76, 126, 110, 111, + 124, 193, 194, 195, 196, 197, 198, 199, 200, 201, 209, 210, 211, 212, 213, 214, + 215, 216, 217, 226, 227, 228, 229, 230, 231, 232, 233, 74, 224, 90, 95, 109, + 121, 129, 130, 131, 132, 133, 134, 135, 136, 137, 145, 146, 147, 148, 149, 150, + 151, 152, 153, 162, 163, 164, 165, 166, 167, 168, 169, 192, 106, 208, 161, 7, + 32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, + 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62, 225, + 65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 98, 99, 100, 101, 102, 103, 104, 105, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 128, 138, 139, 140, 141, 142, 143, 144, 154, 155, 156, 157, 158, + 159, 160, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, 202, 203, 204, 205, 206, 207, 218, 219, + 220, 221, 222, 223, 234, 235, 236, 237, 238, 239, 250, 251, 252, 253, 254, 255}; + + +static void iconv_e2a(unsigned char src[], unsigned char dst[], size_t length) { + size_t i; + for (i = 0; i < length; i++) + dst[i] = e2a[src[i]]; +} + + +static void iconv_a2e(const char* src, unsigned char dst[], size_t length) { + size_t srclen; + size_t i; + + srclen = strlen(src); + if (srclen > length) + abort(); + for (i = 0; i < srclen; i++) + dst[i] = a2e[src[i]]; + /* padding the remaining part with spaces */ + for (; i < length; i++) + dst[i] = a2e[' ']; +} + + static int get_ibmi_system_status(SSTS0200* rcvr) { /* rcvrlen is input parameter 2 to QWCRSSTS */ unsigned int rcvrlen = sizeof(*rcvr); + unsigned char format[8], reset_status[10]; - /* format is input parameter 3 to QWCRSSTS ("SSTS0200" in EBCDIC) */ - unsigned char format[] = {0xE2, 0xE2, 0xE3, 0xE2, 0xF0, 0xF2, 0xF0, 0xF0}; - - /* reset_status is input parameter 4 to QWCRSSTS ("*NO " in EBCDIC) */ - unsigned char reset_status[] = { - 0x5C, 0xD5, 0xD6, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 - }; + /* format is input parameter 3 to QWCRSSTS */ + iconv_a2e("SSTS0200", format, sizeof(format)); + /* reset_status is input parameter 4 */ + iconv_a2e("*NO", reset_status, sizeof(reset_status)); /* errcode is input parameter 5 to QWCRSSTS */ - struct _errcode { - int bytes_provided; - int bytes_available; - char msgid[7]; - } errcode; + errcode_s errcode; /* qwcrssts_pointer is the 16-byte tagged system pointer to QWCRSSTS */ ILEpointer __attribute__((aligned(16))) qwcrssts_pointer; @@ -145,7 +213,7 @@ static int get_ibmi_system_status(SSTS0200* rcvr) { qwcrssts_argv[5] = NULL; /* Call the IBM i QWCRSSTS API from PASE */ - rc = _PGMCALL(&qwcrssts_pointer, (void**)&qwcrssts_argv, 0); + rc = _PGMCALL(&qwcrssts_pointer, qwcrssts_argv, 0); return rc; } @@ -166,10 +234,13 @@ uint64_t uv_get_free_memory(void) { uint64_t current_unprotected_storage_used = rcvr.current_unprotected_storage_used * 1024ULL; - uint64_t free_storage_size = - (main_storage_size - current_unprotected_storage_used) * 1024ULL; + /* Current unprotected storage includes the storage used for memory + * and disks so it is possible to exceed the amount of main storage. + */ + if (main_storage_size <= current_unprotected_storage_used) + return 0ULL; - return free_storage_size < 0 ? 0 : free_storage_size; + return (main_storage_size - current_unprotected_storage_used) * 1024ULL; } @@ -247,3 +318,159 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { return 0; } + + +static int get_ibmi_physical_address(const char* line, char (*phys_addr)[6]) { + LIND0500 rcvr; + /* rcvrlen is input parameter 2 to QDCRLIND */ + unsigned int rcvrlen = sizeof(rcvr); + unsigned char format[8], line_name[10]; + unsigned char mac_addr[sizeof(rcvr.loca_adapter_address)]; + int c[6]; + + /* format is input parameter 3 to QDCRLIND */ + iconv_a2e("LIND0500", format, sizeof(format)); + + /* line_name is input parameter 4 to QDCRLIND */ + iconv_a2e(line, line_name, sizeof(line_name)); + + /* err is input parameter 5 to QDCRLIND */ + errcode_s err; + + /* qwcrssts_pointer is the 16-byte tagged system pointer to QDCRLIND */ + ILEpointer __attribute__((aligned(16))) qdcrlind_pointer; + + /* qwcrssts_argv is the array of argument pointers to QDCRLIND */ + void* qdcrlind_argv[6]; + + /* Set the IBM i pointer to the QSYS/QDCRLIND *PGM object */ + int rc = _RSLOBJ2(&qdcrlind_pointer, RSLOBJ_TS_PGM, "QDCRLIND", "QSYS"); + + if (rc != 0) + return rc; + + /* initialize the QDCRLIND returned info structure */ + memset(&rcvr, 0, sizeof(rcvr)); + + /* initialize the QDCRLIND error code structure */ + memset(&err, 0, sizeof(err)); + err.bytes_provided = sizeof(err); + + /* initialize the array of argument pointers for the QDCRLIND API */ + qdcrlind_argv[0] = &rcvr; + qdcrlind_argv[1] = &rcvrlen; + qdcrlind_argv[2] = &format; + qdcrlind_argv[3] = &line_name; + qdcrlind_argv[4] = &err; + qdcrlind_argv[5] = NULL; + + /* Call the IBM i QDCRLIND API from PASE */ + rc = _PGMCALL(&qdcrlind_pointer, qdcrlind_argv, 0); + if (rc != 0) + return rc; + + /* convert ebcdic loca_adapter_address to ascii first */ + iconv_e2a(rcvr.loca_adapter_address, mac_addr, + sizeof(rcvr.loca_adapter_address)); + + /* convert loca_adapter_address(char[12]) to phys_addr(char[6]) */ + int r = sscanf(mac_addr, "%02x%02x%02x%02x%02x%02x", + &c[0], &c[1], &c[2], &c[3], &c[4], &c[5]); + + if (r == ARRAY_SIZE(c)) { + (*phys_addr)[0] = c[0]; + (*phys_addr)[1] = c[1]; + (*phys_addr)[2] = c[2]; + (*phys_addr)[3] = c[3]; + (*phys_addr)[4] = c[4]; + (*phys_addr)[5] = c[5]; + } else { + memset(*phys_addr, 0, sizeof(*phys_addr)); + rc = -1; + } + return rc; +} + + +int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { + uv_interface_address_t* address; + struct ifaddrs_pase *ifap = NULL, *cur; + int inet6, r = 0; + + *count = 0; + *addresses = NULL; + + if (Qp2getifaddrs(&ifap)) + return UV_ENOSYS; + + /* The first loop to get the size of the array to be allocated */ + for (cur = ifap; cur; cur = cur->ifa_next) { + if (!(cur->ifa_addr->sa_family == AF_INET6 || + cur->ifa_addr->sa_family == AF_INET)) + continue; + + if (!(cur->ifa_flags & IFF_UP && cur->ifa_flags & IFF_RUNNING)) + continue; + + (*count)++; + } + + if (*count == 0) { + Qp2freeifaddrs(ifap); + return 0; + } + + /* Alloc the return interface structs */ + *addresses = uv__calloc(*count, sizeof(**addresses)); + if (*addresses == NULL) { + Qp2freeifaddrs(ifap); + return UV_ENOMEM; + } + address = *addresses; + + /* The second loop to fill in the array */ + for (cur = ifap; cur; cur = cur->ifa_next) { + if (!(cur->ifa_addr->sa_family == AF_INET6 || + cur->ifa_addr->sa_family == AF_INET)) + continue; + + if (!(cur->ifa_flags & IFF_UP && cur->ifa_flags & IFF_RUNNING)) + continue; + + address->name = uv__strdup(cur->ifa_name); + + inet6 = (cur->ifa_addr->sa_family == AF_INET6); + + if (inet6) { + address->address.address6 = *((struct sockaddr_in6*)cur->ifa_addr); + address->netmask.netmask6 = *((struct sockaddr_in6*)cur->ifa_netmask); + address->netmask.netmask6.sin6_family = AF_INET6; + } else { + address->address.address4 = *((struct sockaddr_in*)cur->ifa_addr); + address->netmask.netmask4 = *((struct sockaddr_in*)cur->ifa_netmask); + address->netmask.netmask4.sin_family = AF_INET; + } + address->is_internal = cur->ifa_flags & IFF_LOOPBACK ? 1 : 0; + if (!address->is_internal) { + int rc = get_ibmi_physical_address(address->name, &address->phys_addr); + if (rc != 0) + r = rc; + } + + address++; + } + + Qp2freeifaddrs(ifap); + return r; +} + + +void uv_free_interface_addresses(uv_interface_address_t* addresses, int count) { + int i; + + for (i = 0; i < count; ++i) { + uv__free(addresses[i].name); + } + + uv__free(addresses); +} diff --git a/deps/uv/src/unix/linux-core.c b/deps/uv/src/unix/linux-core.c index 740e422d46edb8..f8d9ff5868ab58 100644 --- a/deps/uv/src/unix/linux-core.c +++ b/deps/uv/src/unix/linux-core.c @@ -990,7 +990,7 @@ static uint64_t uv__read_proc_meminfo(const char* what) { rc = 0; fd = uv__open_cloexec("/proc/meminfo", O_RDONLY); - if (fd == -1) + if (fd < 0) return 0; n = read(fd, buf, sizeof(buf) - 1); diff --git a/deps/uv/src/unix/random-devurandom.c b/deps/uv/src/unix/random-devurandom.c index 9aa762e372ea3f..05e52a56a364ea 100644 --- a/deps/uv/src/unix/random-devurandom.c +++ b/deps/uv/src/unix/random-devurandom.c @@ -37,8 +37,8 @@ int uv__random_readpath(const char* path, void* buf, size_t buflen) { fd = uv__open_cloexec(path, O_RDONLY); - if (fd == -1) - return UV__ERR(errno); + if (fd < 0) + return fd; if (fstat(fd, &s)) { uv__close(fd); diff --git a/deps/uv/src/unix/stream.c b/deps/uv/src/unix/stream.c index 8c1329306d7068..8327f9ccfcea75 100644 --- a/deps/uv/src/unix/stream.c +++ b/deps/uv/src/unix/stream.c @@ -1185,10 +1185,6 @@ static void uv__read(uv_stream_t* stream) { } else if (errno == ECONNRESET && stream->type == UV_NAMED_PIPE) { uv__stream_eof(stream, &buf); return; -#elif defined(_AIX) - } else if (errno == ECONNRESET && (stream->flags & UV_DISCONNECT)) { - uv__stream_eof(stream, &buf); - return; #endif } else { /* Error. User should call uv_close(). */ diff --git a/deps/uv/test/runner-unix.c b/deps/uv/test/runner-unix.c index 716c15ff088fa9..dbb33bfa3edfd2 100644 --- a/deps/uv/test/runner-unix.c +++ b/deps/uv/test/runner-unix.c @@ -371,8 +371,8 @@ int process_copy_output(process_info_t* p, FILE* stream) { } /* TODO: what if the line is longer than buf */ - while (fgets(buf, sizeof(buf), p->stdout_file) != NULL) - print_lines(buf, strlen(buf), stream); + while ((r = fread(buf, 1, sizeof(buf), p->stdout_file)) != 0) + print_lines(buf, r, stream); if (ferror(p->stdout_file)) { perror("read"); @@ -398,7 +398,8 @@ int process_read_last_line(process_info_t *p, buffer[0] = '\0'; while (fgets(buffer, buffer_len, p->stdout_file) != NULL) { - for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++); + for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++) + ; *ptr = '\0'; } diff --git a/deps/uv/test/runner-win.c b/deps/uv/test/runner-win.c index 4167a386921ec7..e69b7447dcee0c 100644 --- a/deps/uv/test/runner-win.c +++ b/deps/uv/test/runner-win.c @@ -222,28 +222,19 @@ long int process_output_size(process_info_t *p) { int process_copy_output(process_info_t* p, FILE* stream) { char buf[1024]; int fd, r; - FILE* f; fd = _open_osfhandle((intptr_t)p->stdio_out, _O_RDONLY | _O_TEXT); if (fd == -1) return -1; - f = _fdopen(fd, "rt"); - if (f == NULL) { - _close(fd); - return -1; - } - r = fseek(f, 0, SEEK_SET); + r = _lseek(fd, 0, SEEK_SET); if (r < 0) return -1; - while (fgets(buf, sizeof(buf), f) != NULL) - print_lines(buf, strlen(buf), stream); - - if (ferror(f)) - return -1; + while ((r = _read(fd, buf, sizeof(buf))) != 0) + print_lines(buf, r, stream); - fclose(f); + _close(fd); return 0; } diff --git a/deps/uv/test/runner.c b/deps/uv/test/runner.c index aec560a59dbc5c..a0f5df8947bac8 100644 --- a/deps/uv/test/runner.c +++ b/deps/uv/test/runner.c @@ -419,13 +419,18 @@ void print_lines(const char* buffer, size_t size, FILE* stream) { start = buffer; while ((end = memchr(start, '\n', &buffer[size] - start))) { - fprintf(stream, "# %.*s\n", (int) (end - start), start); + fputs("# ", stream); + fwrite(start, 1, (int)(end - start), stream); + fputs("\n", stream); fflush(stream); start = end + 1; } - if (start < &buffer[size]) { - fprintf(stream, "# %s\n", start); + end = &buffer[size]; + if (start < end) { + fputs("# ", stream); + fwrite(start, 1, (int)(end - start), stream); + fputs("\n", stream); fflush(stream); } } diff --git a/deps/uv/test/test-env-vars.c b/deps/uv/test/test-env-vars.c index 3c9de95b102a07..f61c1c6c115cae 100644 --- a/deps/uv/test/test-env-vars.c +++ b/deps/uv/test/test-env-vars.c @@ -102,6 +102,12 @@ TEST_IMPL(env_vars) { ASSERT(r == 0); r = uv_os_setenv(name2, ""); ASSERT(r == 0); +#ifdef _WIN32 + /* Create a special environment variable on Windows in case there are no + naturally occurring ones. */ + r = uv_os_setenv("=Z:", "\\"); + ASSERT(r == 0); +#endif r = uv_os_environ(&envitems, &envcount); ASSERT(r == 0); diff --git a/deps/uv/test/test-get-memory.c b/deps/uv/test/test-get-memory.c index 0e0864038b3219..6a9a46dc81dcef 100644 --- a/deps/uv/test/test-get-memory.c +++ b/deps/uv/test/test-get-memory.c @@ -32,7 +32,12 @@ TEST_IMPL(get_memory) { (unsigned long long) total_mem, (unsigned long long) constrained_mem); + /* On IBMi PASE, the amount of memory in use includes storage used for + * memory and disks so it is possible to exceed the amount of main storage. + */ +#ifndef __PASE__ ASSERT(free_mem > 0); +#endif ASSERT(total_mem > 0); ASSERT(total_mem > free_mem); diff --git a/deps/uvwasi/include/fd_table.h b/deps/uvwasi/include/fd_table.h index 639ff9abc8d34f..fa8a44e7468d41 100644 --- a/deps/uvwasi/include/fd_table.h +++ b/deps/uvwasi/include/fd_table.h @@ -4,7 +4,6 @@ #include #include "uv.h" #include "wasi_types.h" -#include "uv_mapping.h" struct uvwasi_s; @@ -32,26 +31,39 @@ uvwasi_errno_t uvwasi_fd_table_init(struct uvwasi_s* uvwasi, uint32_t init_size); void uvwasi_fd_table_free(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table); +uvwasi_errno_t uvwasi_fd_table_insert(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + uv_file fd, + const char* mapped_path, + const char* real_path, + uvwasi_filetype_t type, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting, + int preopen, + struct uvwasi_fd_wrap_t** wrap); uvwasi_errno_t uvwasi_fd_table_insert_preopen(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uv_file fd, const char* path, const char* real_path); -uvwasi_errno_t uvwasi_fd_table_insert_fd(struct uvwasi_s* uvwasi, - struct uvwasi_fd_table_t* table, - const uv_file fd, - const int flags, - const char* path, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - struct uvwasi_fd_wrap_t* wrap); -uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, +uvwasi_errno_t uvwasi_fd_table_get(struct uvwasi_fd_table_t* table, const uvwasi_fd_t id, struct uvwasi_fd_wrap_t** wrap, uvwasi_rights_t rights_base, uvwasi_rights_t rights_inheriting); -uvwasi_errno_t uvwasi_fd_table_remove(struct uvwasi_s* uvwasi, - struct uvwasi_fd_table_t* table, - const uvwasi_fd_t id); +uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id, + struct uvwasi_fd_wrap_t** wrap, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting); +uvwasi_errno_t uvwasi_fd_table_remove_nolock(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id); +uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t dst, + const uvwasi_fd_t src); +uvwasi_errno_t uvwasi_fd_table_lock(struct uvwasi_fd_table_t* table); +uvwasi_errno_t uvwasi_fd_table_unlock(struct uvwasi_fd_table_t* table); #endif /* __UVWASI_FD_TABLE_H__ */ diff --git a/deps/uvwasi/include/uvwasi.h b/deps/uvwasi/include/uvwasi.h index 2fbcbc583dcbfb..9ca30459e23a73 100644 --- a/deps/uvwasi/include/uvwasi.h +++ b/deps/uvwasi/include/uvwasi.h @@ -5,13 +5,13 @@ extern "C" { #endif +#include "uv.h" #include "wasi_types.h" -#include "uv_mapping.h" #include "fd_table.h" #define UVWASI_VERSION_MAJOR 0 #define UVWASI_VERSION_MINOR 0 -#define UVWASI_VERSION_PATCH 3 +#define UVWASI_VERSION_PATCH 5 #define UVWASI_VERSION_HEX ((UVWASI_VERSION_MAJOR << 16) | \ (UVWASI_VERSION_MINOR << 8) | \ (UVWASI_VERSION_PATCH)) diff --git a/deps/uvwasi/include/clocks.h b/deps/uvwasi/src/clocks.h similarity index 100% rename from deps/uvwasi/include/clocks.h rename to deps/uvwasi/src/clocks.h diff --git a/deps/uvwasi/src/fd_table.c b/deps/uvwasi/src/fd_table.c index f3855d4da54dbe..bc32f4dd28bbce 100644 --- a/deps/uvwasi/src/fd_table.c +++ b/deps/uvwasi/src/fd_table.c @@ -9,183 +9,21 @@ #include "uv.h" #include "fd_table.h" #include "wasi_types.h" +#include "wasi_rights.h" #include "uv_mapping.h" #include "uvwasi_alloc.h" -#define UVWASI__RIGHTS_ALL (UVWASI_RIGHT_FD_DATASYNC | \ - UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_SEEK | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_TELL | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_FD_ALLOCATE | \ - UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ - UVWASI_RIGHT_PATH_CREATE_FILE | \ - UVWASI_RIGHT_PATH_LINK_SOURCE | \ - UVWASI_RIGHT_PATH_LINK_TARGET | \ - UVWASI_RIGHT_PATH_OPEN | \ - UVWASI_RIGHT_FD_READDIR | \ - UVWASI_RIGHT_PATH_READLINK | \ - UVWASI_RIGHT_PATH_RENAME_SOURCE | \ - UVWASI_RIGHT_PATH_RENAME_TARGET | \ - UVWASI_RIGHT_PATH_FILESTAT_GET | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_SYMLINK | \ - UVWASI_RIGHT_PATH_UNLINK_FILE | \ - UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ - UVWASI_RIGHT_POLL_FD_READWRITE | \ - UVWASI_RIGHT_SOCK_SHUTDOWN) - -#define UVWASI__RIGHTS_BLOCK_DEVICE_BASE UVWASI__RIGHTS_ALL -#define UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING UVWASI__RIGHTS_ALL - -#define UVWASI__RIGHTS_CHARACTER_DEVICE_BASE UVWASI__RIGHTS_ALL -#define UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING UVWASI__RIGHTS_ALL - -#define UVWASI__RIGHTS_REGULAR_FILE_BASE (UVWASI_RIGHT_FD_DATASYNC | \ - UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_SEEK | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_TELL | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_FD_ALLOCATE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES |\ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_REGULAR_FILE_INHERITING 0 - -#define UVWASI__RIGHTS_DIRECTORY_BASE (UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ - UVWASI_RIGHT_PATH_CREATE_FILE | \ - UVWASI_RIGHT_PATH_LINK_SOURCE | \ - UVWASI_RIGHT_PATH_LINK_TARGET | \ - UVWASI_RIGHT_PATH_OPEN | \ - UVWASI_RIGHT_FD_READDIR | \ - UVWASI_RIGHT_PATH_READLINK | \ - UVWASI_RIGHT_PATH_RENAME_SOURCE | \ - UVWASI_RIGHT_PATH_RENAME_TARGET | \ - UVWASI_RIGHT_PATH_FILESTAT_GET | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_PATH_SYMLINK | \ - UVWASI_RIGHT_PATH_UNLINK_FILE | \ - UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_DIRECTORY_INHERITING (UVWASI__RIGHTS_DIRECTORY_BASE | \ - UVWASI__RIGHTS_REGULAR_FILE_BASE) - -#define UVWASI__RIGHTS_SOCKET_BASE (UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_POLL_FD_READWRITE | \ - UVWASI_RIGHT_SOCK_SHUTDOWN) -#define UVWASI__RIGHTS_SOCKET_INHERITING UVWASI__RIGHTS_ALL; - -#define UVWASI__RIGHTS_TTY_BASE (UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_TTY_INHERITING 0 - -static uvwasi_errno_t uvwasi__get_type_and_rights(uv_file fd, - int flags, - uvwasi_filetype_t* type, - uvwasi_rights_t* rights_base, - uvwasi_rights_t* rights_inheriting) { - uv_fs_t req; - uvwasi_filetype_t filetype; - int read_or_write_only; - int r; - - r = uv_fs_fstat(NULL, &req, fd, NULL); - filetype = uvwasi__stat_to_filetype(&req.statbuf); - uv_fs_req_cleanup(&req); - if (r != 0) - return uvwasi__translate_uv_error(r); - - *type = filetype; - switch (filetype) { - case UVWASI_FILETYPE_REGULAR_FILE: - *rights_base = UVWASI__RIGHTS_REGULAR_FILE_BASE; - *rights_inheriting = UVWASI__RIGHTS_REGULAR_FILE_INHERITING; - break; - - case UVWASI_FILETYPE_DIRECTORY: - *rights_base = UVWASI__RIGHTS_DIRECTORY_BASE; - *rights_inheriting = UVWASI__RIGHTS_DIRECTORY_INHERITING; - break; - - /* uvwasi__stat_to_filetype() cannot differentiate socket types. It only - returns UVWASI_FILETYPE_SOCKET_STREAM. */ - case UVWASI_FILETYPE_SOCKET_STREAM: - if (uv_guess_handle(fd) == UV_UDP) - *type = UVWASI_FILETYPE_SOCKET_DGRAM; - - *rights_base = UVWASI__RIGHTS_SOCKET_BASE; - *rights_inheriting = UVWASI__RIGHTS_SOCKET_INHERITING; - break; - - case UVWASI_FILETYPE_CHARACTER_DEVICE: - if (uv_guess_handle(fd) == UV_TTY) { - *rights_base = UVWASI__RIGHTS_TTY_BASE; - *rights_inheriting = UVWASI__RIGHTS_TTY_INHERITING; - } else { - *rights_base = UVWASI__RIGHTS_CHARACTER_DEVICE_BASE; - *rights_inheriting = UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING; - } - break; - - case UVWASI_FILETYPE_BLOCK_DEVICE: - *rights_base = UVWASI__RIGHTS_BLOCK_DEVICE_BASE; - *rights_inheriting = UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING; - break; - - default: - *rights_base = 0; - *rights_inheriting = 0; - } - - if (*type == UVWASI_FILETYPE_UNKNOWN) - return UVWASI_EINVAL; - - /* Disable read/write bits depending on access mode. */ - read_or_write_only = flags & (UV_FS_O_RDONLY | UV_FS_O_WRONLY | UV_FS_O_RDWR); - - if (read_or_write_only == UV_FS_O_RDONLY) - *rights_base &= ~UVWASI_RIGHT_FD_WRITE; - else if (read_or_write_only == UV_FS_O_WRONLY) - *rights_base &= ~UVWASI_RIGHT_FD_READ; - - return UVWASI_ESUCCESS; -} - - -static uvwasi_errno_t uvwasi__fd_table_insert(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - uv_file fd, - const char* mapped_path, - const char* real_path, - uvwasi_filetype_t type, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - int preopen, - struct uvwasi_fd_wrap_t** wrap) { +uvwasi_errno_t uvwasi_fd_table_insert(uvwasi_t* uvwasi, + struct uvwasi_fd_table_t* table, + uv_file fd, + const char* mapped_path, + const char* real_path, + uvwasi_filetype_t type, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting, + int preopen, + struct uvwasi_fd_wrap_t** wrap) { struct uvwasi_fd_wrap_t* entry; struct uvwasi_fd_wrap_t** new_fds; uvwasi_errno_t err; @@ -263,11 +101,13 @@ static uvwasi_errno_t uvwasi__fd_table_insert(uvwasi_t* uvwasi, entry->rights_base = rights_base; entry->rights_inheriting = rights_inheriting; entry->preopen = preopen; - table->used++; - if (wrap != NULL) + if (wrap != NULL) { + uv_mutex_lock(&entry->mutex); *wrap = entry; + } + table->used++; err = UVWASI_ESUCCESS; exit: uv_rwlock_wrunlock(&table->rwlock); @@ -314,28 +154,30 @@ uvwasi_errno_t uvwasi_fd_table_init(uvwasi_t* uvwasi, /* Create the stdio FDs. */ for (i = 0; i < 3; ++i) { - err = uvwasi__get_type_and_rights(i, - UV_FS_O_RDWR, - &type, - &base, - &inheriting); + err = uvwasi__get_filetype_by_fd(i, &type); + if (err != UVWASI_ESUCCESS) + goto error_exit; + + err = uvwasi__get_rights(i, UV_FS_O_RDWR, type, &base, &inheriting); if (err != UVWASI_ESUCCESS) goto error_exit; - err = uvwasi__fd_table_insert(uvwasi, - table, - i, - "", - "", - type, - base, - inheriting, - 0, - &wrap); + err = uvwasi_fd_table_insert(uvwasi, + table, + i, + "", + "", + type, + base, + inheriting, + 0, + &wrap); if (err != UVWASI_ESUCCESS) goto error_exit; - if (wrap->id != i || wrap->id != (uvwasi_fd_t) wrap->fd) { + r = wrap->id != i || wrap->id != (uvwasi_fd_t) wrap->fd; + uv_mutex_unlock(&wrap->mutex); + if (r) { err = UVWASI_EBADF; goto error_exit; } @@ -386,14 +228,18 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(uvwasi_t* uvwasi, if (table == NULL || path == NULL || real_path == NULL) return UVWASI_EINVAL; - err = uvwasi__get_type_and_rights(fd, 0, &type, &base, &inheriting); + err = uvwasi__get_filetype_by_fd(fd, &type); if (err != UVWASI_ESUCCESS) return err; if (type != UVWASI_FILETYPE_DIRECTORY) return UVWASI_ENOTDIR; - err = uvwasi__fd_table_insert(uvwasi, + err = uvwasi__get_rights(fd, 0, type, &base, &inheriting); + if (err != UVWASI_ESUCCESS) + return err; + + return uvwasi_fd_table_insert(uvwasi, table, fd, path, @@ -403,122 +249,164 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(uvwasi_t* uvwasi, UVWASI__RIGHTS_DIRECTORY_INHERITING, 1, NULL); - if (err != UVWASI_ESUCCESS) - return err; - - return UVWASI_ESUCCESS; } -uvwasi_errno_t uvwasi_fd_table_insert_fd(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - const uv_file fd, - const int flags, - const char* path, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - struct uvwasi_fd_wrap_t* wrap) { - struct uvwasi_fd_wrap_t* fd_wrap; - uvwasi_filetype_t type; - uvwasi_rights_t max_base; - uvwasi_rights_t max_inheriting; - uvwasi_errno_t r; +uvwasi_errno_t uvwasi_fd_table_get(struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id, + struct uvwasi_fd_wrap_t** wrap, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting) { + uvwasi_errno_t err; - if (table == NULL || path == NULL || wrap == NULL) + if (table == NULL) return UVWASI_EINVAL; - r = uvwasi__get_type_and_rights(fd, flags, &type, &max_base, &max_inheriting); - if (r != UVWASI_ESUCCESS) - return r; - - r = uvwasi__fd_table_insert(uvwasi, - table, - fd, - path, - path, - type, - rights_base & max_base, - rights_inheriting & max_inheriting, - 0, - &fd_wrap); - if (r != UVWASI_ESUCCESS) - return r; - - *wrap = *fd_wrap; - return UVWASI_ESUCCESS; + uv_rwlock_wrlock(&table->rwlock); + err = uvwasi_fd_table_get_nolock(table, + id, + wrap, + rights_base, + rights_inheriting); + uv_rwlock_wrunlock(&table->rwlock); + return err; } -uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, - const uvwasi_fd_t id, - struct uvwasi_fd_wrap_t** wrap, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting) { +/* uvwasi_fd_table_get_nolock() retrieves a file descriptor and locks its mutex, + but does not lock the file descriptor table like uvwasi_fd_table_get() does. +*/ +uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id, + struct uvwasi_fd_wrap_t** wrap, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting) { struct uvwasi_fd_wrap_t* entry; - uvwasi_errno_t err; if (table == NULL || wrap == NULL) return UVWASI_EINVAL; - uv_rwlock_rdlock((uv_rwlock_t *)&table->rwlock); - - if (id >= table->size) { - err = UVWASI_EBADF; - goto exit; - } + if (id >= table->size) + return UVWASI_EBADF; entry = table->fds[id]; - if (entry == NULL || entry->id != id) { - err = UVWASI_EBADF; - goto exit; - } + if (entry == NULL || entry->id != id) + return UVWASI_EBADF; /* Validate that the fd has the necessary rights. */ if ((~entry->rights_base & rights_base) != 0 || (~entry->rights_inheriting & rights_inheriting) != 0) { - err = UVWASI_ENOTCAPABLE; - goto exit; + return UVWASI_ENOTCAPABLE; } uv_mutex_lock(&entry->mutex); *wrap = entry; - err = UVWASI_ESUCCESS; -exit: - uv_rwlock_rdunlock((uv_rwlock_t *)&table->rwlock); - return err; + return UVWASI_ESUCCESS; } -uvwasi_errno_t uvwasi_fd_table_remove(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - const uvwasi_fd_t id) { +uvwasi_errno_t uvwasi_fd_table_remove_nolock(uvwasi_t* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id) { struct uvwasi_fd_wrap_t* entry; - uvwasi_errno_t err; if (table == NULL) return UVWASI_EINVAL; + if (id >= table->size) + return UVWASI_EBADF; + + entry = table->fds[id]; + + if (entry == NULL || entry->id != id) + return UVWASI_EBADF; + + uv_mutex_destroy(&entry->mutex); + uvwasi__free(uvwasi, entry); + table->fds[id] = NULL; + table->used--; + return UVWASI_ESUCCESS; +} + + +uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t dst, + const uvwasi_fd_t src) { + struct uvwasi_fd_wrap_t* dst_entry; + struct uvwasi_fd_wrap_t* src_entry; + uv_fs_t req; + uvwasi_errno_t err; + int r; + + if (uvwasi == NULL || table == NULL) + return UVWASI_EINVAL; + + if (dst == src) + return UVWASI_ESUCCESS; + uv_rwlock_wrlock(&table->rwlock); - if (id >= table->size) { + if (dst >= table->size || src >= table->size) { err = UVWASI_EBADF; goto exit; } - entry = table->fds[id]; + dst_entry = table->fds[dst]; + src_entry = table->fds[src]; - if (entry == NULL || entry->id != id) { + if (dst_entry == NULL || dst_entry->id != dst || + src_entry == NULL || src_entry->id != src) { err = UVWASI_EBADF; goto exit; } - uv_mutex_destroy(&entry->mutex); - uvwasi__free(uvwasi, entry); - table->fds[id] = NULL; + uv_mutex_lock(&dst_entry->mutex); + uv_mutex_lock(&src_entry->mutex); + + /* Close the existing destination descriptor. */ + r = uv_fs_close(NULL, &req, dst_entry->fd, NULL); + uv_fs_req_cleanup(&req); + if (r != 0) { + uv_mutex_unlock(&src_entry->mutex); + uv_mutex_unlock(&dst_entry->mutex); + err = uvwasi__translate_uv_error(r); + goto exit; + } + + /* Move the source entry to the destination slot in the table. */ + table->fds[dst] = table->fds[src]; + table->fds[dst]->id = dst; + uv_mutex_unlock(&table->fds[dst]->mutex); + table->fds[src] = NULL; table->used--; + + /* Clean up what's left of the old destination entry. */ + uv_mutex_unlock(&dst_entry->mutex); + uv_mutex_destroy(&dst_entry->mutex); + uvwasi__free(uvwasi, dst_entry); + err = UVWASI_ESUCCESS; exit: uv_rwlock_wrunlock(&table->rwlock); return err; } + + +uvwasi_errno_t uvwasi_fd_table_lock(struct uvwasi_fd_table_t* table) { + if (table == NULL) + return UVWASI_EINVAL; + + uv_rwlock_wrlock(&table->rwlock); + return UVWASI_ESUCCESS; +} + + +uvwasi_errno_t uvwasi_fd_table_unlock(struct uvwasi_fd_table_t* table) { + if (table == NULL) + return UVWASI_EINVAL; + + uv_rwlock_wrunlock(&table->rwlock); + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/src/uv_mapping.c b/deps/uvwasi/src/uv_mapping.c index 846dcedbeb6b4f..da922de8da68f5 100644 --- a/deps/uvwasi/src/uv_mapping.c +++ b/deps/uvwasi/src/uv_mapping.c @@ -241,3 +241,33 @@ void uvwasi__stat_to_filestat(const uv_stat_t* stat, uvwasi_filestat_t* fs) { fs->st_mtim = uvwasi__timespec_to_timestamp(&stat->st_mtim); fs->st_ctim = uvwasi__timespec_to_timestamp(&stat->st_ctim); } + + +uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type) { + uv_fs_t req; + int r; + + r = uv_fs_fstat(NULL, &req, fd, NULL); + if (r != 0) { + uv_fs_req_cleanup(&req); + + /* Windows can't stat a TTY. */ + if (uv_guess_handle(fd) == UV_TTY) { + *type = UVWASI_FILETYPE_CHARACTER_DEVICE; + return UVWASI_ESUCCESS; + } + + *type = UVWASI_FILETYPE_UNKNOWN; + return uvwasi__translate_uv_error(r); + } + + *type = uvwasi__stat_to_filetype(&req.statbuf); + uv_fs_req_cleanup(&req); + + if (*type == UVWASI_FILETYPE_SOCKET_STREAM && + uv_guess_handle(fd) == UV_UDP) { + *type = UVWASI_FILETYPE_SOCKET_DGRAM; + } + + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/include/uv_mapping.h b/deps/uvwasi/src/uv_mapping.h similarity index 86% rename from deps/uvwasi/include/uv_mapping.h rename to deps/uvwasi/src/uv_mapping.h index d835ca507a4856..5a0542afb4dd8b 100644 --- a/deps/uvwasi/include/uv_mapping.h +++ b/deps/uvwasi/src/uv_mapping.h @@ -11,5 +11,6 @@ int uvwasi__translate_to_uv_signal(uvwasi_signal_t sig); uvwasi_timestamp_t uvwasi__timespec_to_timestamp(const uv_timespec_t* ts); uvwasi_filetype_t uvwasi__stat_to_filetype(const uv_stat_t* stat); void uvwasi__stat_to_filestat(const uv_stat_t* stat, uvwasi_filestat_t* fs); +uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type); #endif /* __UVWASI_UV_MAPPING_H__ */ diff --git a/deps/uvwasi/src/uvwasi.c b/deps/uvwasi/src/uvwasi.c index 28c6dcc26104c9..53b7699f590e53 100644 --- a/deps/uvwasi/src/uvwasi.c +++ b/deps/uvwasi/src/uvwasi.c @@ -7,16 +7,14 @@ # include # include # include -# define SLASH '/' -# define SLASH_STR "/" # define IS_SLASH(c) ((c) == '/') #else -# define SLASH '\\' -# define SLASH_STR "\\" +# include # define IS_SLASH(c) ((c) == '/' || (c) == '\\') #endif /* _WIN32 */ #define UVWASI__READDIR_NUM_ENTRIES 1 +#define UVWASI__MAX_SYMLINK_FOLLOWS 32 #include "uvwasi.h" #include "uvwasi_alloc.h" @@ -24,6 +22,7 @@ #include "uv_mapping.h" #include "fd_table.h" #include "clocks.h" +#include "wasi_rights.h" /* TODO(cjihrig): PATH_MAX_BYTES shouldn't be stack allocated. On Windows, paths can be 32k long, and this PATH_MAX_BYTES is an artificial limitation. */ @@ -86,120 +85,312 @@ static int uvwasi__is_absolute_path(const char* path, size_t path_len) { } +static char* uvwasi__strchr_slash(const char* s) { + /* strchr() that identifies /, as well as \ on Windows. */ + do { + if (IS_SLASH(*s)) + return (char*) s; + } while (*s++); + + return NULL; +} + + +static uvwasi_errno_t uvwasi__normalize_path(const char* path, + size_t path_len, + char* normalized_path, + size_t normalized_len) { + const char* cur; + char* ptr; + char* next; + size_t cur_len; + + if (path_len > normalized_len) + return UVWASI_ENOBUFS; + + normalized_path[0] = '\0'; + ptr = normalized_path; + for (cur = path; cur != NULL; cur = next + 1) { + next = uvwasi__strchr_slash(cur); + cur_len = (next == NULL) ? strlen(cur) : (size_t) (next - cur); + + if (cur_len == 0 || (cur_len == 1 && cur[0] == '.')) + continue; + + if (cur_len == 2 && cur[0] == '.' && cur[1] == '.') { + while (!IS_SLASH(*ptr) && ptr != normalized_path) + ptr--; + *ptr = '\0'; + continue; + } + + *ptr = '/'; + ptr++; + memcpy(ptr, cur, cur_len); + ptr += cur_len; + *ptr = '\0'; + + if (next == NULL) + break; + } + + return UVWASI_ESUCCESS; +} + + +static uvwasi_errno_t uvwasi__resolve_path_to_host( + const uvwasi_t* uvwasi, + const struct uvwasi_fd_wrap_t* fd, + const char* path, + size_t path_len, + char** resolved_path, + size_t* resolved_len + ) { + /* Return the normalized path, but resolved to the host's real path. */ + int real_path_len; + int fake_path_len; +#ifdef _WIN32 + size_t i; +#endif /* _WIN32 */ + + real_path_len = strlen(fd->real_path); + fake_path_len = strlen(fd->path); + *resolved_len = path_len - fake_path_len + real_path_len; + *resolved_path = uvwasi__malloc(uvwasi, *resolved_len + 1); + + if (*resolved_path == NULL) + return UVWASI_ENOMEM; + + memcpy(*resolved_path, fd->real_path, real_path_len); + memcpy(*resolved_path + real_path_len, + path + fake_path_len, + path_len - fake_path_len + 1); + +#ifdef _WIN32 + /* Replace / with \ on Windows. */ + for (i = real_path_len; i < *resolved_len; i++) { + if ((*resolved_path)[i] == '/') + (*resolved_path)[i] = '\\'; + } +#endif /* _WIN32 */ + + return UVWASI_ESUCCESS; +} + + +static uvwasi_errno_t uvwasi__normalize_absolute_path( + const uvwasi_t* uvwasi, + const struct uvwasi_fd_wrap_t* fd, + const char* path, + size_t path_len, + char** normalized_path, + size_t* normalized_len + ) { + uvwasi_errno_t err; + char* abs_path; + int abs_size; + + *normalized_path = NULL; + *normalized_len = 0; + abs_size = path_len + 1; + abs_path = uvwasi__malloc(uvwasi, abs_size); + if (abs_path == NULL) { + err = UVWASI_ENOMEM; + goto exit; + } + + /* Normalize the input path first. */ + err = uvwasi__normalize_path(path, + path_len, + abs_path, + path_len); + if (err != UVWASI_ESUCCESS) + goto exit; + + /* Once the input is normalized, ensure that it is still sandboxed. */ + if (abs_path != strstr(abs_path, fd->path)) { + err = UVWASI_ENOTCAPABLE; + goto exit; + } + + *normalized_path = abs_path; + *normalized_len = abs_size - 1; + return UVWASI_ESUCCESS; + +exit: + uvwasi__free(uvwasi, abs_path); + return err; +} + + +static uvwasi_errno_t uvwasi__normalize_relative_path( + const uvwasi_t* uvwasi, + const struct uvwasi_fd_wrap_t* fd, + const char* path, + size_t path_len, + char** normalized_path, + size_t* normalized_len + ) { + uvwasi_errno_t err; + char* abs_path; + int abs_size; + int r; + + *normalized_path = NULL; + *normalized_len = 0; + abs_size = path_len + strlen(fd->path) + 2; + abs_path = uvwasi__malloc(uvwasi, abs_size); + if (abs_path == NULL) { + err = UVWASI_ENOMEM; + goto exit; + } + + /* Resolve the relative path to an absolute path based on fd's fake path. */ + r = snprintf(abs_path, abs_size, "%s/%s", fd->path, path); + if (r <= 0) { + err = uvwasi__translate_uv_error(uv_translate_sys_error(errno)); + goto exit; + } + + err = uvwasi__normalize_absolute_path(uvwasi, + fd, + abs_path, + abs_size - 1, + normalized_path, + normalized_len); +exit: + uvwasi__free(uvwasi, abs_path); + return err; +} + + static uvwasi_errno_t uvwasi__resolve_path(const uvwasi_t* uvwasi, const struct uvwasi_fd_wrap_t* fd, const char* path, size_t path_len, char* resolved_path, uvwasi_lookupflags_t flags) { - uv_fs_t realpath_req; + uv_fs_t req; uvwasi_errno_t err; - char* abs_path; - char* tok; - char* ptr; - int realpath_size; - int abs_size; - int input_is_absolute; + const char* input; + char* host_path; + char* normalized_path; + char* link_target; + size_t input_len; + size_t host_path_len; + size_t normalized_len; + int follow_count; int r; -#ifdef _WIN32 - int i; -#endif /* _WIN32 */ - err = UVWASI_ESUCCESS; - input_is_absolute = uvwasi__is_absolute_path(path, path_len); + input = path; + input_len = path_len; + link_target = NULL; + follow_count = 0; + host_path = NULL; - if (1 == input_is_absolute) { - /* TODO(cjihrig): Revisit this. Copying is probably not necessary here. */ - abs_size = path_len; - abs_path = uvwasi__malloc(uvwasi, abs_size); - if (abs_path == NULL) { - err = UVWASI_ENOMEM; - goto exit; - } +start: + normalized_path = NULL; + err = UVWASI_ESUCCESS; - memcpy(abs_path, path, abs_size); + if (1 == uvwasi__is_absolute_path(input, input_len)) { + err = uvwasi__normalize_absolute_path(uvwasi, + fd, + input, + input_len, + &normalized_path, + &normalized_len); } else { - /* Resolve the relative path to fd's real path. */ - abs_size = path_len + strlen(fd->real_path) + 2; - abs_path = uvwasi__malloc(uvwasi, abs_size); - if (abs_path == NULL) { - err = UVWASI_ENOMEM; - goto exit; - } - - r = snprintf(abs_path, abs_size, "%s/%s", fd->real_path, path); - if (r <= 0) { - err = uvwasi__translate_uv_error(uv_translate_sys_error(errno)); - goto exit; - } + err = uvwasi__normalize_relative_path(uvwasi, + fd, + input, + input_len, + &normalized_path, + &normalized_len); } -#ifdef _WIN32 - /* On Windows, convert slashes to backslashes. */ - for (i = 0; i < abs_size; ++i) { - if (abs_path[i] == '/') - abs_path[i] = SLASH; - } -#endif /* _WIN32 */ + if (err != UVWASI_ESUCCESS) + goto exit; - ptr = resolved_path; - tok = strtok(abs_path, SLASH_STR); - for (; tok != NULL; tok = strtok(NULL, SLASH_STR)) { - if (0 == strcmp(tok, ".")) - continue; + uvwasi__free(uvwasi, host_path); + err = uvwasi__resolve_path_to_host(uvwasi, + fd, + normalized_path, + normalized_len, + &host_path, + &host_path_len); + if (err != UVWASI_ESUCCESS) + goto exit; - if (0 == strcmp(tok, "..")) { - while (*ptr != SLASH && ptr != resolved_path) - ptr--; - *ptr = '\0'; - continue; - } + /* TODO(cjihrig): Currently performing a bounds check here. The TODO is to + stop allocating resolved_path in every caller and instead return the + path allocated in this function. */ + if (host_path_len > PATH_MAX_BYTES) { + err = UVWASI_ENOBUFS; + goto exit; + } + if ((flags & UVWASI_LOOKUP_SYMLINK_FOLLOW) == UVWASI_LOOKUP_SYMLINK_FOLLOW) { + r = uv_fs_readlink(NULL, &req, host_path, NULL); + + if (r != 0) { #ifdef _WIN32 - /* On Windows, prevent a leading slash in the path. */ - if (ptr == resolved_path) - r = sprintf(ptr, "%s", tok); - else + /* uv_fs_readlink() returns UV__UNKNOWN on Windows. Try to get a better + error using uv_fs_stat(). */ + if (r == UV__UNKNOWN) { + uv_fs_req_cleanup(&req); + r = uv_fs_stat(NULL, &req, host_path, NULL); + + if (r == 0) { + if (uvwasi__stat_to_filetype(&req.statbuf) != + UVWASI_FILETYPE_SYMBOLIC_LINK) { + r = UV_EINVAL; + } + } + + // Fall through. + } #endif /* _WIN32 */ - r = sprintf(ptr, "%c%s", SLASH, tok); - if (r < 1) { /* At least one character should have been written. */ - err = uvwasi__translate_uv_error(uv_translate_sys_error(errno)); + /* Don't report UV_EINVAL or UV_ENOENT. They mean that either the file + does not exist, or it is not a symlink. Both are OK. */ + if (r != UV_EINVAL && r != UV_ENOENT) + err = uvwasi__translate_uv_error(r); + + uv_fs_req_cleanup(&req); goto exit; } - ptr += r; - } - - if ((flags & UVWASI_LOOKUP_SYMLINK_FOLLOW) == UVWASI_LOOKUP_SYMLINK_FOLLOW) { - r = uv_fs_realpath(NULL, &realpath_req, resolved_path, NULL); - if (r == 0) { - realpath_size = strlen(realpath_req.ptr) + 1; - if (realpath_size > PATH_MAX_BYTES) { - err = UVWASI_ENOBUFS; - uv_fs_req_cleanup(&realpath_req); - goto exit; - } - - memcpy(resolved_path, realpath_req.ptr, realpath_size); - } else if (r != UV_ENOENT) { - /* Report errors except ENOENT. */ - err = uvwasi__translate_uv_error(r); - uv_fs_req_cleanup(&realpath_req); + /* Clean up memory and follow the link, unless it's time to return ELOOP. */ + follow_count++; + if (follow_count >= UVWASI__MAX_SYMLINK_FOLLOWS) { + uv_fs_req_cleanup(&req); + err = UVWASI_ELOOP; goto exit; } - uv_fs_req_cleanup(&realpath_req); - } + input_len = strlen(req.ptr); + uvwasi__free(uvwasi, link_target); + link_target = uvwasi__malloc(uvwasi, input_len + 1); + if (link_target == NULL) { + uv_fs_req_cleanup(&req); + err = UVWASI_ENOMEM; + goto exit; + } - /* Verify that the resolved path is still in the sandbox. */ - if (resolved_path != strstr(resolved_path, fd->real_path)) { - err = UVWASI_ENOTCAPABLE; - goto exit; + memcpy(link_target, req.ptr, input_len + 1); + input = link_target; + uvwasi__free(uvwasi, normalized_path); + uv_fs_req_cleanup(&req); + goto start; } exit: - uvwasi__free(uvwasi, abs_path); + if (err == UVWASI_ESUCCESS) + memcpy(resolved_path, host_path, host_path_len + 1); + + uvwasi__free(uvwasi, link_target); + uvwasi__free(uvwasi, normalized_path); + uvwasi__free(uvwasi, host_path); return err; } @@ -687,18 +878,26 @@ uvwasi_errno_t uvwasi_fd_close(uvwasi_t* uvwasi, uvwasi_fd_t fd) { if (uvwasi == NULL) return UVWASI_EINVAL; - err = uvwasi_fd_table_get(&uvwasi->fds, fd, &wrap, 0, 0); + uvwasi_fd_table_lock(&uvwasi->fds); + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, fd, &wrap, 0, 0); if (err != UVWASI_ESUCCESS) - return err; + goto exit; r = uv_fs_close(NULL, &req, wrap->fd, NULL); uv_mutex_unlock(&wrap->mutex); uv_fs_req_cleanup(&req); - if (r != 0) - return uvwasi__translate_uv_error(r); + if (r != 0) { + err = uvwasi__translate_uv_error(r); + goto exit; + } + + err = uvwasi_fd_table_remove_nolock(uvwasi, &uvwasi->fds, fd); - return uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, fd); +exit: + uvwasi_fd_table_unlock(&uvwasi->fds); + return err; } @@ -1295,41 +1494,10 @@ uvwasi_errno_t uvwasi_fd_readdir(uvwasi_t* uvwasi, uvwasi_errno_t uvwasi_fd_renumber(uvwasi_t* uvwasi, uvwasi_fd_t from, uvwasi_fd_t to) { - struct uvwasi_fd_wrap_t* to_wrap; - struct uvwasi_fd_wrap_t* from_wrap; - uv_fs_t req; - uvwasi_errno_t err; - int r; - if (uvwasi == NULL) return UVWASI_EINVAL; - if (from == to) - return UVWASI_ESUCCESS; - - err = uvwasi_fd_table_get(&uvwasi->fds, from, &from_wrap, 0, 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, to, &to_wrap, 0, 0); - if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&from_wrap->mutex); - return err; - } - - r = uv_fs_close(NULL, &req, to_wrap->fd, NULL); - uv_fs_req_cleanup(&req); - if (r != 0) { - uv_mutex_unlock(&from_wrap->mutex); - uv_mutex_unlock(&to_wrap->mutex); - return uvwasi__translate_uv_error(r); - } - - memcpy(to_wrap, from_wrap, sizeof(*to_wrap)); - to_wrap->id = to; - uv_mutex_unlock(&from_wrap->mutex); - uv_mutex_unlock(&to_wrap->mutex); - return uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, from); + return uvwasi_fd_table_renumber(uvwasi, &uvwasi->fds, to, from); } @@ -1603,37 +1771,41 @@ uvwasi_errno_t uvwasi_path_link(uvwasi_t* uvwasi, if (uvwasi == NULL || old_path == NULL || new_path == NULL) return UVWASI_EINVAL; - if (old_fd == new_fd) { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_LINK_SOURCE | - UVWASI_RIGHT_PATH_LINK_TARGET, - 0); - if (err != UVWASI_ESUCCESS) - return err; + uvwasi_fd_table_lock(&uvwasi->fds); + if (old_fd == new_fd) { + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_LINK_SOURCE | + UVWASI_RIGHT_PATH_LINK_TARGET, + 0); new_wrap = old_wrap; } else { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_LINK_SOURCE, - 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, - new_fd, - &new_wrap, - UVWASI_RIGHT_PATH_LINK_TARGET, - 0); + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_LINK_SOURCE, + 0); if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&old_wrap->mutex); + uvwasi_fd_table_unlock(&uvwasi->fds); return err; } + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + new_fd, + &new_wrap, + UVWASI_RIGHT_PATH_LINK_TARGET, + 0); + if (err != UVWASI_ESUCCESS) + uv_mutex_unlock(&old_wrap->mutex); } + uvwasi_fd_table_unlock(&uvwasi->fds); + + if (err != UVWASI_ESUCCESS) + return err; + err = uvwasi__resolve_path(uvwasi, old_wrap, old_path, @@ -1661,9 +1833,9 @@ uvwasi_errno_t uvwasi_path_link(uvwasi_t* uvwasi, err = UVWASI_ESUCCESS; exit: - uv_mutex_unlock(&old_wrap->mutex); + uv_mutex_unlock(&new_wrap->mutex); if (old_fd != new_fd) - uv_mutex_unlock(&new_wrap->mutex); + uv_mutex_unlock(&old_wrap->mutex); return err; } @@ -1681,8 +1853,11 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, char resolved_path[PATH_MAX_BYTES]; uvwasi_rights_t needed_inheriting; uvwasi_rights_t needed_base; + uvwasi_rights_t max_base; + uvwasi_rights_t max_inheriting; struct uvwasi_fd_wrap_t* dirfd_wrap; - struct uvwasi_fd_wrap_t wrap; + struct uvwasi_fd_wrap_t *wrap; + uvwasi_filetype_t filetype; uvwasi_errno_t err; uv_fs_t req; int flags; @@ -1759,37 +1934,43 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, } r = uv_fs_open(NULL, &req, resolved_path, flags, 0666, NULL); + uv_mutex_unlock(&dirfd_wrap->mutex); uv_fs_req_cleanup(&req); - if (r < 0) { - uv_mutex_unlock(&dirfd_wrap->mutex); + if (r < 0) return uvwasi__translate_uv_error(r); - } - err = uvwasi_fd_table_insert_fd(uvwasi, - &uvwasi->fds, - r, - flags, - resolved_path, - fs_rights_base, - fs_rights_inheriting, - &wrap); - if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&dirfd_wrap->mutex); + /* Not all platforms support UV_FS_O_DIRECTORY, so get the file type and check + it here. */ + err = uvwasi__get_filetype_by_fd(r, &filetype); + if (err != UVWASI_ESUCCESS) goto close_file_and_error_exit; - } - /* Not all platforms support UV_FS_O_DIRECTORY, so enforce it here as well. */ if ((o_flags & UVWASI_O_DIRECTORY) != 0 && - wrap.type != UVWASI_FILETYPE_DIRECTORY) { - uv_mutex_unlock(&dirfd_wrap->mutex); - uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, wrap.id); + filetype != UVWASI_FILETYPE_DIRECTORY) { err = UVWASI_ENOTDIR; goto close_file_and_error_exit; } - *fd = wrap.id; - uv_mutex_unlock(&dirfd_wrap->mutex); + err = uvwasi__get_rights(r, flags, filetype, &max_base, &max_inheriting); + if (err != UVWASI_ESUCCESS) + goto close_file_and_error_exit; + + err = uvwasi_fd_table_insert(uvwasi, + &uvwasi->fds, + r, + resolved_path, + resolved_path, + filetype, + fs_rights_base & max_base, + fs_rights_inheriting & max_inheriting, + 0, + &wrap); + if (err != UVWASI_ESUCCESS) + goto close_file_and_error_exit; + + *fd = wrap->id; + uv_mutex_unlock(&wrap->mutex); return UVWASI_ESUCCESS; close_file_and_error_exit: @@ -1907,36 +2088,41 @@ uvwasi_errno_t uvwasi_path_rename(uvwasi_t* uvwasi, if (uvwasi == NULL || old_path == NULL || new_path == NULL) return UVWASI_EINVAL; + uvwasi_fd_table_lock(&uvwasi->fds); + if (old_fd == new_fd) { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_RENAME_SOURCE | - UVWASI_RIGHT_PATH_RENAME_TARGET, - 0); - if (err != UVWASI_ESUCCESS) - return err; + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_RENAME_SOURCE | + UVWASI_RIGHT_PATH_RENAME_TARGET, + 0); new_wrap = old_wrap; } else { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_RENAME_SOURCE, - 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, - new_fd, - &new_wrap, - UVWASI_RIGHT_PATH_RENAME_TARGET, - 0); + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_RENAME_SOURCE, + 0); if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&old_wrap->mutex); + uvwasi_fd_table_unlock(&uvwasi->fds); return err; } + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + new_fd, + &new_wrap, + UVWASI_RIGHT_PATH_RENAME_TARGET, + 0); + if (err != UVWASI_ESUCCESS) + uv_mutex_unlock(&old_wrap->mutex); } + uvwasi_fd_table_unlock(&uvwasi->fds); + + if (err != UVWASI_ESUCCESS) + return err; + err = uvwasi__resolve_path(uvwasi, old_wrap, old_path, @@ -1964,9 +2150,9 @@ uvwasi_errno_t uvwasi_path_rename(uvwasi_t* uvwasi, err = UVWASI_ESUCCESS; exit: - uv_mutex_unlock(&old_wrap->mutex); + uv_mutex_unlock(&new_wrap->mutex); if (old_fd != new_fd) - uv_mutex_unlock(&new_wrap->mutex); + uv_mutex_unlock(&old_wrap->mutex); return err; } diff --git a/deps/uvwasi/src/wasi_rights.c b/deps/uvwasi/src/wasi_rights.c new file mode 100644 index 00000000000000..79d0338086a244 --- /dev/null +++ b/deps/uvwasi/src/wasi_rights.c @@ -0,0 +1,62 @@ +#include "uv.h" +#include "wasi_rights.h" +#include "wasi_types.h" + + +uvwasi_errno_t uvwasi__get_rights(uv_file fd, + int flags, + uvwasi_filetype_t type, + uvwasi_rights_t* rights_base, + uvwasi_rights_t* rights_inheriting) { + int read_or_write_only; + + if (type == UVWASI_FILETYPE_UNKNOWN) + return UVWASI_EINVAL; + + switch (type) { + case UVWASI_FILETYPE_REGULAR_FILE: + *rights_base = UVWASI__RIGHTS_REGULAR_FILE_BASE; + *rights_inheriting = UVWASI__RIGHTS_REGULAR_FILE_INHERITING; + break; + + case UVWASI_FILETYPE_DIRECTORY: + *rights_base = UVWASI__RIGHTS_DIRECTORY_BASE; + *rights_inheriting = UVWASI__RIGHTS_DIRECTORY_INHERITING; + break; + + case UVWASI_FILETYPE_SOCKET_STREAM: + case UVWASI_FILETYPE_SOCKET_DGRAM: + *rights_base = UVWASI__RIGHTS_SOCKET_BASE; + *rights_inheriting = UVWASI__RIGHTS_SOCKET_INHERITING; + break; + + case UVWASI_FILETYPE_CHARACTER_DEVICE: + if (uv_guess_handle(fd) == UV_TTY) { + *rights_base = UVWASI__RIGHTS_TTY_BASE; + *rights_inheriting = UVWASI__RIGHTS_TTY_INHERITING; + } else { + *rights_base = UVWASI__RIGHTS_CHARACTER_DEVICE_BASE; + *rights_inheriting = UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING; + } + break; + + case UVWASI_FILETYPE_BLOCK_DEVICE: + *rights_base = UVWASI__RIGHTS_BLOCK_DEVICE_BASE; + *rights_inheriting = UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING; + break; + + default: + *rights_base = 0; + *rights_inheriting = 0; + } + + /* Disable read/write bits depending on access mode. */ + read_or_write_only = flags & (UV_FS_O_RDONLY | UV_FS_O_WRONLY | UV_FS_O_RDWR); + + if (read_or_write_only == UV_FS_O_RDONLY) + *rights_base &= ~UVWASI_RIGHT_FD_WRITE; + else if (read_or_write_only == UV_FS_O_WRONLY) + *rights_base &= ~UVWASI_RIGHT_FD_READ; + + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/src/wasi_rights.h b/deps/uvwasi/src/wasi_rights.h new file mode 100644 index 00000000000000..fb19bd0a00e74e --- /dev/null +++ b/deps/uvwasi/src/wasi_rights.h @@ -0,0 +1,104 @@ +#ifndef __UVWASI_WASI_RIGHTS_H__ +#define __UVWASI_WASI_RIGHTS_H__ + +#include "wasi_types.h" + +#define UVWASI__RIGHTS_ALL (UVWASI_RIGHT_FD_DATASYNC | \ + UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_SEEK | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_TELL | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_FD_ALLOCATE | \ + UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ + UVWASI_RIGHT_PATH_CREATE_FILE | \ + UVWASI_RIGHT_PATH_LINK_SOURCE | \ + UVWASI_RIGHT_PATH_LINK_TARGET | \ + UVWASI_RIGHT_PATH_OPEN | \ + UVWASI_RIGHT_FD_READDIR | \ + UVWASI_RIGHT_PATH_READLINK | \ + UVWASI_RIGHT_PATH_RENAME_SOURCE | \ + UVWASI_RIGHT_PATH_RENAME_TARGET | \ + UVWASI_RIGHT_PATH_FILESTAT_GET | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_SYMLINK | \ + UVWASI_RIGHT_PATH_UNLINK_FILE | \ + UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ + UVWASI_RIGHT_POLL_FD_READWRITE | \ + UVWASI_RIGHT_SOCK_SHUTDOWN) + +#define UVWASI__RIGHTS_BLOCK_DEVICE_BASE UVWASI__RIGHTS_ALL +#define UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING UVWASI__RIGHTS_ALL + +#define UVWASI__RIGHTS_CHARACTER_DEVICE_BASE UVWASI__RIGHTS_ALL +#define UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING UVWASI__RIGHTS_ALL + +#define UVWASI__RIGHTS_REGULAR_FILE_BASE (UVWASI_RIGHT_FD_DATASYNC | \ + UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_SEEK | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_TELL | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_FD_ALLOCATE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES |\ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_REGULAR_FILE_INHERITING 0 + +#define UVWASI__RIGHTS_DIRECTORY_BASE (UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ + UVWASI_RIGHT_PATH_CREATE_FILE | \ + UVWASI_RIGHT_PATH_LINK_SOURCE | \ + UVWASI_RIGHT_PATH_LINK_TARGET | \ + UVWASI_RIGHT_PATH_OPEN | \ + UVWASI_RIGHT_FD_READDIR | \ + UVWASI_RIGHT_PATH_READLINK | \ + UVWASI_RIGHT_PATH_RENAME_SOURCE | \ + UVWASI_RIGHT_PATH_RENAME_TARGET | \ + UVWASI_RIGHT_PATH_FILESTAT_GET | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_PATH_SYMLINK | \ + UVWASI_RIGHT_PATH_UNLINK_FILE | \ + UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_DIRECTORY_INHERITING (UVWASI__RIGHTS_DIRECTORY_BASE | \ + UVWASI__RIGHTS_REGULAR_FILE_BASE) + +#define UVWASI__RIGHTS_SOCKET_BASE (UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_POLL_FD_READWRITE | \ + UVWASI_RIGHT_SOCK_SHUTDOWN) +#define UVWASI__RIGHTS_SOCKET_INHERITING UVWASI__RIGHTS_ALL; + +#define UVWASI__RIGHTS_TTY_BASE (UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_TTY_INHERITING 0 + + +uvwasi_errno_t uvwasi__get_rights(uv_file fd, + int flags, + uvwasi_filetype_t type, + uvwasi_rights_t* rights_base, + uvwasi_rights_t* rights_inheriting); + + +#endif /* __UVWASI_WASI_RIGHTS_H__ */ diff --git a/deps/uvwasi/uvwasi.gyp b/deps/uvwasi/uvwasi.gyp index c07b07b608b724..6963cbf20a7923 100644 --- a/deps/uvwasi/uvwasi.gyp +++ b/deps/uvwasi/uvwasi.gyp @@ -13,6 +13,7 @@ 'src/fd_table.c', 'src/uv_mapping.c', 'src/uvwasi.c', + 'src/wasi_rights.c', ], 'dependencies': [ '../uv/uv.gyp:libuv', @@ -20,6 +21,14 @@ 'direct_dependent_settings': { 'include_dirs': ['include'] }, + 'conditions': [ + [ 'OS=="linux"', { + 'defines': [ + '_GNU_SOURCE', + '_POSIX_C_SOURCE=200112', + ], + }], + ], } ] } diff --git a/deps/zlib/BUILD.gn b/deps/zlib/BUILD.gn new file mode 100644 index 00000000000000..5f8873357d35d1 --- /dev/null +++ b/deps/zlib/BUILD.gn @@ -0,0 +1,379 @@ +# Copyright (c) 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/compiler/compiler.gni") + +if (current_cpu == "arm" || current_cpu == "arm64") { + import("//build/config/arm.gni") +} + +config("zlib_config") { + include_dirs = [ "." ] +} + +config("zlib_internal_config") { + defines = [ "ZLIB_IMPLEMENTATION" ] +} + +use_arm_neon_optimizations = false +if (current_cpu == "arm" || current_cpu == "arm64") { + if (arm_use_neon) { + use_arm_neon_optimizations = true + } +} + +use_x86_x64_optimizations = + (current_cpu == "x86" || current_cpu == "x64") && !is_ios + +config("zlib_adler32_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "ADLER32_SIMD_SSSE3" ] + } + + if (use_arm_neon_optimizations) { + defines = [ "ADLER32_SIMD_NEON" ] + } +} + +source_set("zlib_adler32_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "adler32_simd.c", + "adler32_simd.h", + ] + + if (!is_win || is_clang) { + cflags = [ "-mssse3" ] + } + } + + if (use_arm_neon_optimizations) { + sources = [ + "adler32_simd.c", + "adler32_simd.h", + ] + if (!is_debug) { + # Use optimize_speed (-O3) to output the _smallest_ code. + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_adler32_simd_config" ] +} + +if (use_arm_neon_optimizations) { + config("zlib_arm_crc32_config") { + # Disabled for iPhone, as described in DDI0487C_a_armv8_arm: + # "All implementations of the ARMv8.1 architecture are required to + # implement the CRC32* instructions. These are optional in ARMv8.0." + if (!is_ios) { + defines = [ "CRC32_ARMV8_CRC32" ] + if (is_android) { + defines += [ "ARMV8_OS_ANDROID" ] + } else if (is_linux || is_chromeos) { + defines += [ "ARMV8_OS_LINUX" ] + } else if (is_fuchsia) { + defines += [ "ARMV8_OS_FUCHSIA" ] + } else if (is_win) { + defines += [ "ARMV8_OS_WINDOWS" ] + } else { + assert(false, "Unsupported ARM OS") + } + } + } + + source_set("zlib_arm_crc32") { + visibility = [ ":*" ] + + if (!is_ios) { + include_dirs = [ "." ] + + if (is_android) { + import("//build/config/android/config.gni") + if (defined(android_ndk_root) && android_ndk_root != "") { + deps = [ + "//third_party/android_ndk:cpu_features", + ] + } else { + assert(false, "CPU detection requires the Android NDK") + } + } else if (!is_win && !is_clang) { + assert(!use_thin_lto, + "ThinLTO fails mixing different module-level targets") + cflags_c = [ "-march=armv8-a+crc" ] + } + + sources = [ + "arm_features.c", + "arm_features.h", + "crc32_simd.c", + "crc32_simd.h", + ] + + if (!is_debug) { + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_arm_crc32_config" ] + } +} + +config("zlib_inflate_chunk_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "INFLATE_CHUNK_SIMD_SSE2" ] + + if (current_cpu == "x64") { + defines += [ "INFLATE_CHUNK_READ_64LE" ] + } + } + + if (use_arm_neon_optimizations) { + defines = [ "INFLATE_CHUNK_SIMD_NEON" ] + if (current_cpu == "arm64") { + defines += [ "INFLATE_CHUNK_READ_64LE" ] + } + } +} + +source_set("zlib_inflate_chunk_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations || use_arm_neon_optimizations) { + include_dirs = [ "." ] + + sources = [ + "contrib/optimizations/chunkcopy.h", + "contrib/optimizations/inffast_chunk.c", + "contrib/optimizations/inffast_chunk.h", + "contrib/optimizations/inflate.c", + ] + + if (use_arm_neon_optimizations && !is_debug) { + # Here we trade better performance on newer/bigger ARMv8 cores + # for less perf on ARMv7, per crbug.com/772870#c40 + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + ] + + public_configs = [ ":zlib_inflate_chunk_simd_config" ] +} + +config("zlib_crc32_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "CRC32_SIMD_SSE42_PCLMUL" ] + } +} + +source_set("zlib_crc32_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "crc32_simd.c", + "crc32_simd.h", + ] + + if (!is_win || is_clang) { + cflags = [ + "-msse4.2", + "-mpclmul", + ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_crc32_simd_config" ] +} + +source_set("zlib_x86_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "crc_folding.c", + "fill_window_sse.c", + ] + + if (!is_win || is_clang) { + cflags = [ + "-msse4.2", + "-mpclmul", + ] + } + } else { + sources = [ + "simd_stub.c", + ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + ] +} + +config("zlib_warnings") { + if (is_clang && use_x86_x64_optimizations) { + cflags = [ "-Wno-incompatible-pointer-types" ] + } +} + +component("zlib") { + if (!is_win) { + # Don't stomp on "libzlib" on other platforms. + output_name = "chrome_zlib" + } + + sources = [ + "adler32.c", + "chromeconf.h", + "compress.c", + "contrib/optimizations/insert_string.h", + "crc32.c", + "crc32.h", + "deflate.c", + "deflate.h", + "gzclose.c", + "gzguts.h", + "gzlib.c", + "gzread.c", + "gzwrite.c", + "infback.c", + "inffast.c", + "inffast.h", + "inffixed.h", + "inflate.h", + "inftrees.c", + "inftrees.h", + "trees.c", + "trees.h", + "uncompr.c", + "x86.h", + "zconf.h", + "zlib.h", + "zutil.c", + "zutil.h", + ] + + defines = [] + deps = [] + + if (use_x86_x64_optimizations || use_arm_neon_optimizations) { + deps += [ + ":zlib_adler32_simd", + ":zlib_inflate_chunk_simd", + ] + + if (use_x86_x64_optimizations) { + sources += [ "x86.c" ] + deps += [ ":zlib_crc32_simd" ] + } else if (use_arm_neon_optimizations) { + sources += [ "contrib/optimizations/slide_hash_neon.h" ] + deps += [ ":zlib_arm_crc32" ] + } + } else { + sources += [ "inflate.c" ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + + # Must be after no_chromium_code for warning flags to be ordered correctly. + ":zlib_warnings", + ] + + public_configs = [ ":zlib_config" ] + + deps += [ ":zlib_x86_simd" ] + allow_circular_includes_from = deps +} + +config("minizip_warnings") { + visibility = [ ":*" ] + + if (is_clang) { + # zlib uses `if ((a == b))` for some reason. + cflags = [ "-Wno-parentheses-equality" ] + } +} + +static_library("minizip") { + sources = [ + "contrib/minizip/ioapi.c", + "contrib/minizip/ioapi.h", + "contrib/minizip/iowin32.c", + "contrib/minizip/iowin32.h", + "contrib/minizip/unzip.c", + "contrib/minizip/unzip.h", + "contrib/minizip/zip.c", + "contrib/minizip/zip.h", + ] + + if (!is_win) { + sources -= [ + "contrib/minizip/iowin32.c", + "contrib/minizip/iowin32.h", + ] + } + + if (is_mac || is_ios || is_android || is_nacl) { + # Mac, Android and the BSDs don't have fopen64, ftello64, or fseeko64. We + # use fopen, ftell, and fseek instead on these systems. + defines = [ "USE_FILE32API" ] + } + + deps = [ + ":zlib", + ] + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + "//build/config/compiler:no_chromium_code", + + # Must be after no_chromium_code for warning flags to be ordered correctly. + ":minizip_warnings", + ] + + public_configs = [ ":zlib_config" ] +} + +executable("zlib_bench") { + include_dirs = [ "." ] + + sources = [ + "contrib/bench/zlib_bench.cc", + ] + + if (!is_debug) { + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] + + deps = [ + ":zlib", + ] +} diff --git a/deps/zlib/CMakeLists.txt b/deps/zlib/CMakeLists.txt deleted file mode 100644 index 0fe939df689306..00000000000000 --- a/deps/zlib/CMakeLists.txt +++ /dev/null @@ -1,249 +0,0 @@ -cmake_minimum_required(VERSION 2.4.4) -set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON) - -project(zlib C) - -set(VERSION "1.2.11") - -option(ASM686 "Enable building i686 assembly implementation") -option(AMD64 "Enable building amd64 assembly implementation") - -set(INSTALL_BIN_DIR "${CMAKE_INSTALL_PREFIX}/bin" CACHE PATH "Installation directory for executables") -set(INSTALL_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib" CACHE PATH "Installation directory for libraries") -set(INSTALL_INC_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "Installation directory for headers") -set(INSTALL_MAN_DIR "${CMAKE_INSTALL_PREFIX}/share/man" CACHE PATH "Installation directory for manual pages") -set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files") - -include(CheckTypeSize) -include(CheckFunctionExists) -include(CheckIncludeFile) -include(CheckCSourceCompiles) -enable_testing() - -check_include_file(sys/types.h HAVE_SYS_TYPES_H) -check_include_file(stdint.h HAVE_STDINT_H) -check_include_file(stddef.h HAVE_STDDEF_H) - -# -# Check to see if we have large file support -# -set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) -# We add these other definitions here because CheckTypeSize.cmake -# in CMake 2.4.x does not automatically do so and we want -# compatibility with CMake 2.4.x. -if(HAVE_SYS_TYPES_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H) -endif() -if(HAVE_STDINT_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H) -endif() -if(HAVE_STDDEF_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H) -endif() -check_type_size(off64_t OFF64_T) -if(HAVE_OFF64_T) - add_definitions(-D_LARGEFILE64_SOURCE=1) -endif() -set(CMAKE_REQUIRED_DEFINITIONS) # clear variable - -# -# Check for fseeko -# -check_function_exists(fseeko HAVE_FSEEKO) -if(NOT HAVE_FSEEKO) - add_definitions(-DNO_FSEEKO) -endif() - -# -# Check for unistd.h -# -check_include_file(unistd.h Z_HAVE_UNISTD_H) - -if(MSVC) - set(CMAKE_DEBUG_POSTFIX "d") - add_definitions(-D_CRT_SECURE_NO_DEPRECATE) - add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -endif() - -if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) - # If we're doing an out of source build and the user has a zconf.h - # in their source tree... - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h) - message(STATUS "Renaming") - message(STATUS " ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h") - message(STATUS "to 'zconf.h.included' because this file is included with zlib") - message(STATUS "but CMake generates it automatically in the build directory.") - file(RENAME ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.included) - endif() -endif() - -set(ZLIB_PC ${CMAKE_CURRENT_BINARY_DIR}/zlib.pc) -configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zlib.pc.cmakein - ${ZLIB_PC} @ONLY) -configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.cmakein - ${CMAKE_CURRENT_BINARY_DIR}/zconf.h @ONLY) -include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}) - - -#============================================================================ -# zlib -#============================================================================ - -set(ZLIB_PUBLIC_HDRS - ${CMAKE_CURRENT_BINARY_DIR}/zconf.h - zlib.h -) -set(ZLIB_PRIVATE_HDRS - crc32.h - deflate.h - gzguts.h - inffast.h - inffixed.h - inflate.h - inftrees.h - trees.h - zutil.h -) -set(ZLIB_SRCS - adler32.c - compress.c - crc32.c - deflate.c - gzclose.c - gzlib.c - gzread.c - gzwrite.c - inflate.c - infback.c - inftrees.c - inffast.c - trees.c - uncompr.c - zutil.c -) - -if(NOT MINGW) - set(ZLIB_DLL_SRCS - win32/zlib1.rc # If present will override custom build rule below. - ) -endif() - -if(CMAKE_COMPILER_IS_GNUCC) - if(ASM686) - set(ZLIB_ASMS contrib/asm686/match.S) - elseif (AMD64) - set(ZLIB_ASMS contrib/amd64/amd64-match.S) - endif () - - if(ZLIB_ASMS) - add_definitions(-DASMV) - set_source_files_properties(${ZLIB_ASMS} PROPERTIES LANGUAGE C COMPILE_FLAGS -DNO_UNDERLINE) - endif() -endif() - -if(MSVC) - if(ASM686) - ENABLE_LANGUAGE(ASM_MASM) - set(ZLIB_ASMS - contrib/masmx86/inffas32.asm - contrib/masmx86/match686.asm - ) - elseif (AMD64) - ENABLE_LANGUAGE(ASM_MASM) - set(ZLIB_ASMS - contrib/masmx64/gvmat64.asm - contrib/masmx64/inffasx64.asm - ) - endif() - - if(ZLIB_ASMS) - add_definitions(-DASMV -DASMINF) - endif() -endif() - -# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION -file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents) -string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([-0-9A-Za-z.]+)\".*" - "\\1" ZLIB_FULL_VERSION ${_zlib_h_contents}) - -if(MINGW) - # This gets us DLL resource information when compiling on MinGW. - if(NOT CMAKE_RC_COMPILER) - set(CMAKE_RC_COMPILER windres.exe) - endif() - - add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj - COMMAND ${CMAKE_RC_COMPILER} - -D GCC_WINDRES - -I ${CMAKE_CURRENT_SOURCE_DIR} - -I ${CMAKE_CURRENT_BINARY_DIR} - -o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj - -i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc) - set(ZLIB_DLL_SRCS ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj) -endif(MINGW) - -add_library(zlib SHARED ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_DLL_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) -add_library(zlibstatic STATIC ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) -set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL) -set_target_properties(zlib PROPERTIES SOVERSION 1) - -if(NOT CYGWIN) - # This property causes shared libraries on Linux to have the full version - # encoded into their final filename. We disable this on Cygwin because - # it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll - # seems to be the default. - # - # This has no effect with MSVC, on that platform the version info for - # the DLL comes from the resource file win32/zlib1.rc - set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION}) -endif() - -if(UNIX) - # On unix-like platforms the library is almost always called libz - set_target_properties(zlib zlibstatic PROPERTIES OUTPUT_NAME z) - if(NOT APPLE) - set_target_properties(zlib PROPERTIES LINK_FLAGS "-Wl,--version-script,\"${CMAKE_CURRENT_SOURCE_DIR}/zlib.map\"") - endif() -elseif(BUILD_SHARED_LIBS AND WIN32) - # Creates zlib1.dll when building shared library version - set_target_properties(zlib PROPERTIES SUFFIX "1.dll") -endif() - -if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL ) - install(TARGETS zlib zlibstatic - RUNTIME DESTINATION "${INSTALL_BIN_DIR}" - ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" - LIBRARY DESTINATION "${INSTALL_LIB_DIR}" ) -endif() -if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL ) - install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION "${INSTALL_INC_DIR}") -endif() -if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) - install(FILES zlib.3 DESTINATION "${INSTALL_MAN_DIR}/man3") -endif() -if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) - install(FILES ${ZLIB_PC} DESTINATION "${INSTALL_PKGCONFIG_DIR}") -endif() - -#============================================================================ -# Example binaries -#============================================================================ - -add_executable(example test/example.c) -target_link_libraries(example zlib) -add_test(example example) - -add_executable(minigzip test/minigzip.c) -target_link_libraries(minigzip zlib) - -if(HAVE_OFF64_T) - add_executable(example64 test/example.c) - target_link_libraries(example64 zlib) - set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") - add_test(example64 example64) - - add_executable(minigzip64 test/minigzip.c) - target_link_libraries(minigzip64 zlib) - set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") -endif() diff --git a/deps/zlib/ChangeLog b/deps/zlib/ChangeLog deleted file mode 100644 index 30199a65a03daa..00000000000000 --- a/deps/zlib/ChangeLog +++ /dev/null @@ -1,1515 +0,0 @@ - - ChangeLog file for zlib - -Changes in 1.2.11 (15 Jan 2017) -- Fix deflate stored bug when pulling last block from window -- Permit immediate deflateParams changes before any deflate input - -Changes in 1.2.10 (2 Jan 2017) -- Avoid warnings on snprintf() return value -- Fix bug in deflate_stored() for zero-length input -- Fix bug in gzwrite.c that produced corrupt gzip files -- Remove files to be installed before copying them in Makefile.in -- Add warnings when compiling with assembler code - -Changes in 1.2.9 (31 Dec 2016) -- Fix contrib/minizip to permit unzipping with desktop API [Zouzou] -- Improve contrib/blast to return unused bytes -- Assure that gzoffset() is correct when appending -- Improve compress() and uncompress() to support large lengths -- Fix bug in test/example.c where error code not saved -- Remedy Coverity warning [Randers-Pehrson] -- Improve speed of gzprintf() in transparent mode -- Fix inflateInit2() bug when windowBits is 16 or 32 -- Change DEBUG macro to ZLIB_DEBUG -- Avoid uninitialized access by gzclose_w() -- Allow building zlib outside of the source directory -- Fix bug that accepted invalid zlib header when windowBits is zero -- Fix gzseek() problem on MinGW due to buggy _lseeki64 there -- Loop on write() calls in gzwrite.c in case of non-blocking I/O -- Add --warn (-w) option to ./configure for more compiler warnings -- Reject a window size of 256 bytes if not using the zlib wrapper -- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE -- Add --debug (-d) option to ./configure to define ZLIB_DEBUG -- Fix bugs in creating a very large gzip header -- Add uncompress2() function, which returns the input size used -- Assure that deflateParams() will not switch functions mid-block -- Dramatically speed up deflation for level 0 (storing) -- Add gzfread(), duplicating the interface of fread() -- Add gzfwrite(), duplicating the interface of fwrite() -- Add deflateGetDictionary() function -- Use snprintf() for later versions of Microsoft C -- Fix *Init macros to use z_ prefix when requested -- Replace as400 with os400 for OS/400 support [Monnerat] -- Add crc32_z() and adler32_z() functions with size_t lengths -- Update Visual Studio project files [AraHaan] - -Changes in 1.2.8 (28 Apr 2013) -- Update contrib/minizip/iowin32.c for Windows RT [Vollant] -- Do not force Z_CONST for C++ -- Clean up contrib/vstudio [Roß] -- Correct spelling error in zlib.h -- Fix mixed line endings in contrib/vstudio - -Changes in 1.2.7.3 (13 Apr 2013) -- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc - -Changes in 1.2.7.2 (13 Apr 2013) -- Change check for a four-byte type back to hexadecimal -- Fix typo in win32/Makefile.msc -- Add casts in gzwrite.c for pointer differences - -Changes in 1.2.7.1 (24 Mar 2013) -- Replace use of unsafe string functions with snprintf if available -- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink] -- Fix gzgetc undefine when Z_PREFIX set [Turk] -- Eliminate use of mktemp in Makefile (not always available) -- Fix bug in 'F' mode for gzopen() -- Add inflateGetDictionary() function -- Correct comment in deflate.h -- Use _snprintf for snprintf in Microsoft C -- On Darwin, only use /usr/bin/libtool if libtool is not Apple -- Delete "--version" file if created by "ar --version" [Richard G.] -- Fix configure check for veracity of compiler error return codes -- Fix CMake compilation of static lib for MSVC2010 x64 -- Remove unused variable in infback9.c -- Fix argument checks in gzlog_compress() and gzlog_write() -- Clean up the usage of z_const and respect const usage within zlib -- Clean up examples/gzlog.[ch] comparisons of different types -- Avoid shift equal to bits in type (caused endless loop) -- Fix uninitialized value bug in gzputc() introduced by const patches -- Fix memory allocation error in examples/zran.c [Nor] -- Fix bug where gzopen(), gzclose() would write an empty file -- Fix bug in gzclose() when gzwrite() runs out of memory -- Check for input buffer malloc failure in examples/gzappend.c -- Add note to contrib/blast to use binary mode in stdio -- Fix comparisons of differently signed integers in contrib/blast -- Check for invalid code length codes in contrib/puff -- Fix serious but very rare decompression bug in inftrees.c -- Update inflateBack() comments, since inflate() can be faster -- Use underscored I/O function names for WINAPI_FAMILY -- Add _tr_flush_bits to the external symbols prefixed by --zprefix -- Add contrib/vstudio/vc10 pre-build step for static only -- Quote --version-script argument in CMakeLists.txt -- Don't specify --version-script on Apple platforms in CMakeLists.txt -- Fix casting error in contrib/testzlib/testzlib.c -- Fix types in contrib/minizip to match result of get_crc_table() -- Simplify contrib/vstudio/vc10 with 'd' suffix -- Add TOP support to win32/Makefile.msc -- Suport i686 and amd64 assembler builds in CMakeLists.txt -- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h -- Add vc11 and vc12 build files to contrib/vstudio -- Add gzvprintf() as an undocumented function in zlib -- Fix configure for Sun shell -- Remove runtime check in configure for four-byte integer type -- Add casts and consts to ease user conversion to C++ -- Add man pages for minizip and miniunzip -- In Makefile uninstall, don't rm if preceding cd fails -- Do not return Z_BUF_ERROR if deflateParam() has nothing to write - -Changes in 1.2.7 (2 May 2012) -- Replace use of memmove() with a simple copy for portability -- Test for existence of strerror -- Restore gzgetc_ for backward compatibility with 1.2.6 -- Fix build with non-GNU make on Solaris -- Require gcc 4.0 or later on Mac OS X to use the hidden attribute -- Include unistd.h for Watcom C -- Use __WATCOMC__ instead of __WATCOM__ -- Do not use the visibility attribute if NO_VIZ defined -- Improve the detection of no hidden visibility attribute -- Avoid using __int64 for gcc or solo compilation -- Cast to char * in gzprintf to avoid warnings [Zinser] -- Fix make_vms.com for VAX [Zinser] -- Don't use library or built-in byte swaps -- Simplify test and use of gcc hidden attribute -- Fix bug in gzclose_w() when gzwrite() fails to allocate memory -- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen() -- Fix bug in test/minigzip.c for configure --solo -- Fix contrib/vstudio project link errors [Mohanathas] -- Add ability to choose the builder in make_vms.com [Schweda] -- Add DESTDIR support to mingw32 win32/Makefile.gcc -- Fix comments in win32/Makefile.gcc for proper usage -- Allow overriding the default install locations for cmake -- Generate and install the pkg-config file with cmake -- Build both a static and a shared version of zlib with cmake -- Include version symbols for cmake builds -- If using cmake with MSVC, add the source directory to the includes -- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta] -- Move obsolete emx makefile to old [Truta] -- Allow the use of -Wundef when compiling or using zlib -- Avoid the use of the -u option with mktemp -- Improve inflate() documentation on the use of Z_FINISH -- Recognize clang as gcc -- Add gzopen_w() in Windows for wide character path names -- Rename zconf.h in CMakeLists.txt to move it out of the way -- Add source directory in CMakeLists.txt for building examples -- Look in build directory for zlib.pc in CMakeLists.txt -- Remove gzflags from zlibvc.def in vc9 and vc10 -- Fix contrib/minizip compilation in the MinGW environment -- Update ./configure for Solaris, support --64 [Mooney] -- Remove -R. from Solaris shared build (possible security issue) -- Avoid race condition for parallel make (-j) running example -- Fix type mismatch between get_crc_table() and crc_table -- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler] -- Fix the path to zlib.map in CMakeLists.txt -- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe] -- Add instructions to win32/Makefile.gcc for shared install [Torri] - -Changes in 1.2.6.1 (12 Feb 2012) -- Avoid the use of the Objective-C reserved name "id" -- Include io.h in gzguts.h for Microsoft compilers -- Fix problem with ./configure --prefix and gzgetc macro -- Include gz_header definition when compiling zlib solo -- Put gzflags() functionality back in zutil.c -- Avoid library header include in crc32.c for Z_SOLO -- Use name in GCC_CLASSIC as C compiler for coverage testing, if set -- Minor cleanup in contrib/minizip/zip.c [Vollant] -- Update make_vms.com [Zinser] -- Remove unnecessary gzgetc_ function -- Use optimized byte swap operations for Microsoft and GNU [Snyder] -- Fix minor typo in zlib.h comments [Rzesniowiecki] - -Changes in 1.2.6 (29 Jan 2012) -- Update the Pascal interface in contrib/pascal -- Fix function numbers for gzgetc_ in zlibvc.def files -- Fix configure.ac for contrib/minizip [Schiffer] -- Fix large-entry detection in minizip on 64-bit systems [Schiffer] -- Have ./configure use the compiler return code for error indication -- Fix CMakeLists.txt for cross compilation [McClure] -- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes] -- Fix compilation of contrib/minizip on FreeBSD [Marquez] -- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath] -- Include io.h for Turbo C / Borland C on all platforms [Truta] -- Make version explicit in contrib/minizip/configure.ac [Bosmans] -- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant] -- Minor cleanup up contrib/minizip/unzip.c [Vollant] -- Fix bug when compiling minizip with C++ [Vollant] -- Protect for long name and extra fields in contrib/minizip [Vollant] -- Avoid some warnings in contrib/minizip [Vollant] -- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip -- Add missing libs to minizip linker command -- Add support for VPATH builds in contrib/minizip -- Add an --enable-demos option to contrib/minizip/configure -- Add the generation of configure.log by ./configure -- Exit when required parameters not provided to win32/Makefile.gcc -- Have gzputc return the character written instead of the argument -- Use the -m option on ldconfig for BSD systems [Tobias] -- Correct in zlib.map when deflateResetKeep was added - -Changes in 1.2.5.3 (15 Jan 2012) -- Restore gzgetc function for binary compatibility -- Do not use _lseeki64 under Borland C++ [Truta] -- Update win32/Makefile.msc to build test/*.c [Truta] -- Remove old/visualc6 given CMakefile and other alternatives -- Update AS400 build files and documentation [Monnerat] -- Update win32/Makefile.gcc to build test/*.c [Truta] -- Permit stronger flushes after Z_BLOCK flushes -- Avoid extraneous empty blocks when doing empty flushes -- Permit Z_NULL arguments to deflatePending -- Allow deflatePrime() to insert bits in the middle of a stream -- Remove second empty static block for Z_PARTIAL_FLUSH -- Write out all of the available bits when using Z_BLOCK -- Insert the first two strings in the hash table after a flush - -Changes in 1.2.5.2 (17 Dec 2011) -- fix ld error: unable to find version dependency 'ZLIB_1.2.5' -- use relative symlinks for shared libs -- Avoid searching past window for Z_RLE strategy -- Assure that high-water mark initialization is always applied in deflate -- Add assertions to fill_window() in deflate.c to match comments -- Update python link in README -- Correct spelling error in gzread.c -- Fix bug in gzgets() for a concatenated empty gzip stream -- Correct error in comment for gz_make() -- Change gzread() and related to ignore junk after gzip streams -- Allow gzread() and related to continue after gzclearerr() -- Allow gzrewind() and gzseek() after a premature end-of-file -- Simplify gzseek() now that raw after gzip is ignored -- Change gzgetc() to a macro for speed (~40% speedup in testing) -- Fix gzclose() to return the actual error last encountered -- Always add large file support for windows -- Include zconf.h for windows large file support -- Include zconf.h.cmakein for windows large file support -- Update zconf.h.cmakein on make distclean -- Merge vestigial vsnprintf determination from zutil.h to gzguts.h -- Clarify how gzopen() appends in zlib.h comments -- Correct documentation of gzdirect() since junk at end now ignored -- Add a transparent write mode to gzopen() when 'T' is in the mode -- Update python link in zlib man page -- Get inffixed.h and MAKEFIXED result to match -- Add a ./config --solo option to make zlib subset with no library use -- Add undocumented inflateResetKeep() function for CAB file decoding -- Add --cover option to ./configure for gcc coverage testing -- Add #define ZLIB_CONST option to use const in the z_stream interface -- Add comment to gzdopen() in zlib.h to use dup() when using fileno() -- Note behavior of uncompress() to provide as much data as it can -- Add files in contrib/minizip to aid in building libminizip -- Split off AR options in Makefile.in and configure -- Change ON macro to Z_ARG to avoid application conflicts -- Facilitate compilation with Borland C++ for pragmas and vsnprintf -- Include io.h for Turbo C / Borland C++ -- Move example.c and minigzip.c to test/ -- Simplify incomplete code table filling in inflate_table() -- Remove code from inflate.c and infback.c that is impossible to execute -- Test the inflate code with full coverage -- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw) -- Add deflateResetKeep and fix inflateResetKeep to retain dictionary -- Fix gzwrite.c to accommodate reduced memory zlib compilation -- Have inflate() with Z_FINISH avoid the allocation of a window -- Do not set strm->adler when doing raw inflate -- Fix gzeof() to behave just like feof() when read is not past end of file -- Fix bug in gzread.c when end-of-file is reached -- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF -- Document gzread() capability to read concurrently written files -- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo] - -Changes in 1.2.5.1 (10 Sep 2011) -- Update FAQ entry on shared builds (#13) -- Avoid symbolic argument to chmod in Makefile.in -- Fix bug and add consts in contrib/puff [Oberhumer] -- Update contrib/puff/zeros.raw test file to have all block types -- Add full coverage test for puff in contrib/puff/Makefile -- Fix static-only-build install in Makefile.in -- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno] -- Add libz.a dependency to shared in Makefile.in for parallel builds -- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out -- Replace $(...) with `...` in configure for non-bash sh [Bowler] -- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen] -- Add solaris* to Linux* in configure to allow gcc use [Groffen] -- Add *bsd* to Linux* case in configure [Bar-Lev] -- Add inffast.obj to dependencies in win32/Makefile.msc -- Correct spelling error in deflate.h [Kohler] -- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc -- Add test to configure for GNU C looking for gcc in output of $cc -v -- Add zlib.pc generation to win32/Makefile.gcc [Weigelt] -- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not -- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense -- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser) -- Make stronger test in zconf.h to include unistd.h for LFS -- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack] -- Fix zlib.h LFS support when Z_PREFIX used -- Add updated as400 support (removed from old) [Monnerat] -- Avoid deflate sensitivity to volatile input data -- Avoid division in adler32_combine for NO_DIVIDE -- Clarify the use of Z_FINISH with deflateBound() amount of space -- Set binary for output file in puff.c -- Use u4 type for crc_table to avoid conversion warnings -- Apply casts in zlib.h to avoid conversion warnings -- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller] -- Improve inflateSync() documentation to note indeterminancy -- Add deflatePending() function to return the amount of pending output -- Correct the spelling of "specification" in FAQ [Randers-Pehrson] -- Add a check in configure for stdarg.h, use for gzprintf() -- Check that pointers fit in ints when gzprint() compiled old style -- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler] -- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt] -- Add debug records in assmebler code [Londer] -- Update RFC references to use http://tools.ietf.org/html/... [Li] -- Add --archs option, use of libtool to configure for Mac OS X [Borstel] - -Changes in 1.2.5 (19 Apr 2010) -- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] -- Default to libdir as sharedlibdir in configure [Nieder] -- Update copyright dates on modified source files -- Update trees.c to be able to generate modified trees.h -- Exit configure for MinGW, suggesting win32/Makefile.gcc -- Check for NULL path in gz_open [Homurlu] - -Changes in 1.2.4.5 (18 Apr 2010) -- Set sharedlibdir in configure [Torok] -- Set LDFLAGS in Makefile.in [Bar-Lev] -- Avoid mkdir objs race condition in Makefile.in [Bowler] -- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays -- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C -- Don't use hidden attribute when it is a warning generator (e.g. Solaris) - -Changes in 1.2.4.4 (18 Apr 2010) -- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] -- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty -- Try to use bash or ksh regardless of functionality of /bin/sh -- Fix configure incompatibility with NetBSD sh -- Remove attempt to run under bash or ksh since have better NetBSD fix -- Fix win32/Makefile.gcc for MinGW [Bar-Lev] -- Add diagnostic messages when using CROSS_PREFIX in configure -- Added --sharedlibdir option to configure [Weigelt] -- Use hidden visibility attribute when available [Frysinger] - -Changes in 1.2.4.3 (10 Apr 2010) -- Only use CROSS_PREFIX in configure for ar and ranlib if they exist -- Use CROSS_PREFIX for nm [Bar-Lev] -- Assume _LARGEFILE64_SOURCE defined is equivalent to true -- Avoid use of undefined symbols in #if with && and || -- Make *64 prototypes in gzguts.h consistent with functions -- Add -shared load option for MinGW in configure [Bowler] -- Move z_off64_t to public interface, use instead of off64_t -- Remove ! from shell test in configure (not portable to Solaris) -- Change +0 macro tests to -0 for possibly increased portability - -Changes in 1.2.4.2 (9 Apr 2010) -- Add consistent carriage returns to readme.txt's in masmx86 and masmx64 -- Really provide prototypes for *64 functions when building without LFS -- Only define unlink() in minigzip.c if unistd.h not included -- Update README to point to contrib/vstudio project files -- Move projects/vc6 to old/ and remove projects/ -- Include stdlib.h in minigzip.c for setmode() definition under WinCE -- Clean up assembler builds in win32/Makefile.msc [Rowe] -- Include sys/types.h for Microsoft for off_t definition -- Fix memory leak on error in gz_open() -- Symbolize nm as $NM in configure [Weigelt] -- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] -- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined -- Fix bug in gzeof() to take into account unused input data -- Avoid initialization of structures with variables in puff.c -- Updated win32/README-WIN32.txt [Rowe] - -Changes in 1.2.4.1 (28 Mar 2010) -- Remove the use of [a-z] constructs for sed in configure [gentoo 310225] -- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] -- Restore "for debugging" comment on sprintf() in gzlib.c -- Remove fdopen for MVS from gzguts.h -- Put new README-WIN32.txt in win32 [Rowe] -- Add check for shell to configure and invoke another shell if needed -- Fix big fat stinking bug in gzseek() on uncompressed files -- Remove vestigial F_OPEN64 define in zutil.h -- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE -- Avoid errors on non-LFS systems when applications define LFS macros -- Set EXE to ".exe" in configure for MINGW [Kahle] -- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] -- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] -- Add DLL install in win32/makefile.gcc [Bar-Lev] -- Allow Linux* or linux* from uname in configure [Bar-Lev] -- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] -- Add cross-compilation prefixes to configure [Bar-Lev] -- Match type exactly in gz_load() invocation in gzread.c -- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func -- Provide prototypes for *64 functions when building zlib without LFS -- Don't use -lc when linking shared library on MinGW -- Remove errno.h check in configure and vestigial errno code in zutil.h - -Changes in 1.2.4 (14 Mar 2010) -- Fix VER3 extraction in configure for no fourth subversion -- Update zlib.3, add docs to Makefile.in to make .pdf out of it -- Add zlib.3.pdf to distribution -- Don't set error code in gzerror() if passed pointer is NULL -- Apply destination directory fixes to CMakeLists.txt [Lowman] -- Move #cmakedefine's to a new zconf.in.cmakein -- Restore zconf.h for builds that don't use configure or cmake -- Add distclean to dummy Makefile for convenience -- Update and improve INDEX, README, and FAQ -- Update CMakeLists.txt for the return of zconf.h [Lowman] -- Update contrib/vstudio/vc9 and vc10 [Vollant] -- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc -- Apply license and readme changes to contrib/asm686 [Raiter] -- Check file name lengths and add -c option in minigzip.c [Li] -- Update contrib/amd64 and contrib/masmx86/ [Vollant] -- Avoid use of "eof" parameter in trees.c to not shadow library variable -- Update make_vms.com for removal of zlibdefs.h [Zinser] -- Update assembler code and vstudio projects in contrib [Vollant] -- Remove outdated assembler code contrib/masm686 and contrib/asm586 -- Remove old vc7 and vc8 from contrib/vstudio -- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] -- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() -- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] -- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) -- Fix bug in void-returning vsprintf() case in gzwrite.c -- Fix name change from inflate.h in contrib/inflate86/inffas86.c -- Check if temporary file exists before removing in make_vms.com [Zinser] -- Fix make install and uninstall for --static option -- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] -- Update readme.txt in contrib/masmx64 and masmx86 to assemble - -Changes in 1.2.3.9 (21 Feb 2010) -- Expunge gzio.c -- Move as400 build information to old -- Fix updates in contrib/minizip and contrib/vstudio -- Add const to vsnprintf test in configure to avoid warnings [Weigelt] -- Delete zconf.h (made by configure) [Weigelt] -- Change zconf.in.h to zconf.h.in per convention [Weigelt] -- Check for NULL buf in gzgets() -- Return empty string for gzgets() with len == 1 (like fgets()) -- Fix description of gzgets() in zlib.h for end-of-file, NULL return -- Update minizip to 1.1 [Vollant] -- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c -- Note in zlib.h that gzerror() should be used to distinguish from EOF -- Remove use of snprintf() from gzlib.c -- Fix bug in gzseek() -- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] -- Fix zconf.h generation in CMakeLists.txt [Lowman] -- Improve comments in zconf.h where modified by configure - -Changes in 1.2.3.8 (13 Feb 2010) -- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] -- Use z_off64_t in gz_zero() and gz_skip() to match state->skip -- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) -- Revert to Makefile.in from 1.2.3.6 (live with the clutter) -- Fix missing error return in gzflush(), add zlib.h note -- Add *64 functions to zlib.map [Levin] -- Fix signed/unsigned comparison in gz_comp() -- Use SFLAGS when testing shared linking in configure -- Add --64 option to ./configure to use -m64 with gcc -- Fix ./configure --help to correctly name options -- Have make fail if a test fails [Levin] -- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] -- Remove assembler object files from contrib - -Changes in 1.2.3.7 (24 Jan 2010) -- Always gzopen() with O_LARGEFILE if available -- Fix gzdirect() to work immediately after gzopen() or gzdopen() -- Make gzdirect() more precise when the state changes while reading -- Improve zlib.h documentation in many places -- Catch memory allocation failure in gz_open() -- Complete close operation if seek forward in gzclose_w() fails -- Return Z_ERRNO from gzclose_r() if close() fails -- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL -- Return zero for gzwrite() errors to match zlib.h description -- Return -1 on gzputs() error to match zlib.h description -- Add zconf.in.h to allow recovery from configure modification [Weigelt] -- Fix static library permissions in Makefile.in [Weigelt] -- Avoid warnings in configure tests that hide functionality [Weigelt] -- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] -- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] -- Avoid access of uninitialized data for first inflateReset2 call [Gomes] -- Keep object files in subdirectories to reduce the clutter somewhat -- Remove default Makefile and zlibdefs.h, add dummy Makefile -- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ -- Remove zlibdefs.h completely -- modify zconf.h instead - -Changes in 1.2.3.6 (17 Jan 2010) -- Avoid void * arithmetic in gzread.c and gzwrite.c -- Make compilers happier with const char * for gz_error message -- Avoid unused parameter warning in inflate.c -- Avoid signed-unsigned comparison warning in inflate.c -- Indent #pragma's for traditional C -- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() -- Correct email address in configure for system options -- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] -- Update zlib.map [Brown] -- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] -- Apply various fixes to CMakeLists.txt [Lowman] -- Add checks on len in gzread() and gzwrite() -- Add error message for no more room for gzungetc() -- Remove zlib version check in gzwrite() -- Defer compression of gzprintf() result until need to -- Use snprintf() in gzdopen() if available -- Remove USE_MMAP configuration determination (only used by minigzip) -- Remove examples/pigz.c (available separately) -- Update examples/gun.c to 1.6 - -Changes in 1.2.3.5 (8 Jan 2010) -- Add space after #if in zutil.h for some compilers -- Fix relatively harmless bug in deflate_fast() [Exarevsky] -- Fix same problem in deflate_slow() -- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] -- Add deflate_rle() for faster Z_RLE strategy run-length encoding -- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding -- Change name of "write" variable in inffast.c to avoid library collisions -- Fix premature EOF from gzread() in gzio.c [Brown] -- Use zlib header window size if windowBits is 0 in inflateInit2() -- Remove compressBound() call in deflate.c to avoid linking compress.o -- Replace use of errno in gz* with functions, support WinCE [Alves] -- Provide alternative to perror() in minigzip.c for WinCE [Alves] -- Don't use _vsnprintf on later versions of MSVC [Lowman] -- Add CMake build script and input file [Lowman] -- Update contrib/minizip to 1.1 [Svensson, Vollant] -- Moved nintendods directory from contrib to . -- Replace gzio.c with a new set of routines with the same functionality -- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above -- Update contrib/minizip to 1.1b -- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h - -Changes in 1.2.3.4 (21 Dec 2009) -- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility -- Update comments in configure and Makefile.in for default --shared -- Fix test -z's in configure [Marquess] -- Build examplesh and minigzipsh when not testing -- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h -- Import LDFLAGS from the environment in configure -- Fix configure to populate SFLAGS with discovered CFLAGS options -- Adapt make_vms.com to the new Makefile.in [Zinser] -- Add zlib2ansi script for C++ compilation [Marquess] -- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) -- Add AMD64 assembler code for longest match to contrib [Teterin] -- Include options from $SFLAGS when doing $LDSHARED -- Simplify 64-bit file support by introducing z_off64_t type -- Make shared object files in objs directory to work around old Sun cc -- Use only three-part version number for Darwin shared compiles -- Add rc option to ar in Makefile.in for when ./configure not run -- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* -- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile -- Protect against _FILE_OFFSET_BITS being defined when compiling zlib -- Rename Makefile.in targets allstatic to static and allshared to shared -- Fix static and shared Makefile.in targets to be independent -- Correct error return bug in gz_open() by setting state [Brown] -- Put spaces before ;;'s in configure for better sh compatibility -- Add pigz.c (parallel implementation of gzip) to examples/ -- Correct constant in crc32.c to UL [Leventhal] -- Reject negative lengths in crc32_combine() -- Add inflateReset2() function to work like inflateEnd()/inflateInit2() -- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] -- Correct typo in doc/algorithm.txt [Janik] -- Fix bug in adler32_combine() [Zhu] -- Catch missing-end-of-block-code error in all inflates and in puff - Assures that random input to inflate eventually results in an error -- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ -- Update ENOUGH and its usage to reflect discovered bounds -- Fix gzerror() error report on empty input file [Brown] -- Add ush casts in trees.c to avoid pedantic runtime errors -- Fix typo in zlib.h uncompress() description [Reiss] -- Correct inflate() comments with regard to automatic header detection -- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) -- Put new version of gzlog (2.0) in examples with interruption recovery -- Add puff compile option to permit invalid distance-too-far streams -- Add puff TEST command options, ability to read piped input -- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but - _LARGEFILE64_SOURCE not defined -- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart -- Fix deflateSetDictionary() to use all 32K for output consistency -- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) -- Clear bytes after deflate lookahead to avoid use of uninitialized data -- Change a limit in inftrees.c to be more transparent to Coverity Prevent -- Update win32/zlib.def with exported symbols from zlib.h -- Correct spelling errors in zlib.h [Willem, Sobrado] -- Allow Z_BLOCK for deflate() to force a new block -- Allow negative bits in inflatePrime() to delete existing bit buffer -- Add Z_TREES flush option to inflate() to return at end of trees -- Add inflateMark() to return current state information for random access -- Add Makefile for NintendoDS to contrib [Costa] -- Add -w in configure compile tests to avoid spurious warnings [Beucler] -- Fix typos in zlib.h comments for deflateSetDictionary() -- Fix EOF detection in transparent gzread() [Maier] - -Changes in 1.2.3.3 (2 October 2006) -- Make --shared the default for configure, add a --static option -- Add compile option to permit invalid distance-too-far streams -- Add inflateUndermine() function which is required to enable above -- Remove use of "this" variable name for C++ compatibility [Marquess] -- Add testing of shared library in make test, if shared library built -- Use ftello() and fseeko() if available instead of ftell() and fseek() -- Provide two versions of all functions that use the z_off_t type for - binary compatibility -- a normal version and a 64-bit offset version, - per the Large File Support Extension when _LARGEFILE64_SOURCE is - defined; use the 64-bit versions by default when _FILE_OFFSET_BITS - is defined to be 64 -- Add a --uname= option to configure to perhaps help with cross-compiling - -Changes in 1.2.3.2 (3 September 2006) -- Turn off silly Borland warnings [Hay] -- Use off64_t and define _LARGEFILE64_SOURCE when present -- Fix missing dependency on inffixed.h in Makefile.in -- Rig configure --shared to build both shared and static [Teredesai, Truta] -- Remove zconf.in.h and instead create a new zlibdefs.h file -- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] -- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] - -Changes in 1.2.3.1 (16 August 2006) -- Add watcom directory with OpenWatcom make files [Daniel] -- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] -- Update make_vms.com [Zinser] -- Use -fPIC for shared build in configure [Teredesai, Nicholson] -- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] -- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck] -- Add some FAQ entries about the contrib directory -- Update the MVS question in the FAQ -- Avoid extraneous reads after EOF in gzio.c [Brown] -- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] -- Add comments to zlib.h about gzerror() usage [Brown] -- Set extra flags in gzip header in gzopen() like deflate() does -- Make configure options more compatible with double-dash conventions - [Weigelt] -- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] -- Fix uninstall target in Makefile.in [Truta] -- Add pkgconfig support [Weigelt] -- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] -- Replace set_data_type() with a more accurate detect_data_type() in - trees.c, according to the txtvsbin.txt document [Truta] -- Swap the order of #include and #include "zlib.h" in - gzio.c, example.c and minigzip.c [Truta] -- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, - Truta] (where?) -- Fix target "clean" from win32/Makefile.bor [Truta] -- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] -- Update zlib www home address in win32/DLL_FAQ.txt [Truta] -- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] -- Enable browse info in the "Debug" and "ASM Debug" configurations in - the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] -- Add pkgconfig support [Weigelt] -- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, - for use in win32/zlib1.rc [Polushin, Rowe, Truta] -- Add a document that explains the new text detection scheme to - doc/txtvsbin.txt [Truta] -- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] -- Move algorithm.txt into doc/ [Truta] -- Synchronize FAQ with website -- Fix compressBound(), was low for some pathological cases [Fearnley] -- Take into account wrapper variations in deflateBound() -- Set examples/zpipe.c input and output to binary mode for Windows -- Update examples/zlib_how.html with new zpipe.c (also web site) -- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems - that gcc became pickier in 4.0) -- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain - un-versioned, the patch adds versioning only for symbols introduced in - zlib-1.2.0 or later. It also declares as local those symbols which are - not designed to be exported." [Levin] -- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure -- Do not initialize global static by default in trees.c, add a response - NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] -- Don't use strerror() in gzio.c under WinCE [Yakimov] -- Don't use errno.h in zutil.h under WinCE [Yakimov] -- Move arguments for AR to its usage to allow replacing ar [Marot] -- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] -- Improve inflateInit() and inflateInit2() documentation -- Fix structure size comment in inflate.h -- Change configure help option from --h* to --help [Santos] - -Changes in 1.2.3 (18 July 2005) -- Apply security vulnerability fixes to contrib/infback9 as well -- Clean up some text files (carriage returns, trailing space) -- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] - -Changes in 1.2.2.4 (11 July 2005) -- Add inflatePrime() function for starting inflation at bit boundary -- Avoid some Visual C warnings in deflate.c -- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit - compile -- Fix some spelling errors in comments [Betts] -- Correct inflateInit2() error return documentation in zlib.h -- Add zran.c example of compressed data random access to examples - directory, shows use of inflatePrime() -- Fix cast for assignments to strm->state in inflate.c and infback.c -- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] -- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] -- Add cast in trees.c t avoid a warning [Oberhumer] -- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] -- Update make_vms.com [Zinser] -- Initialize state->write in inflateReset() since copied in inflate_fast() -- Be more strict on incomplete code sets in inflate_table() and increase - ENOUGH and MAXD -- this repairs a possible security vulnerability for - invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for - discovering the vulnerability and providing test cases. -- Add ia64 support to configure for HP-UX [Smith] -- Add error return to gzread() for format or i/o error [Levin] -- Use malloc.h for OS/2 [Necasek] - -Changes in 1.2.2.3 (27 May 2005) -- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile -- Typecast fread() return values in gzio.c [Vollant] -- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) -- Fix crc check bug in gzread() after gzungetc() [Heiner] -- Add the deflateTune() function to adjust internal compression parameters -- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) -- Remove an incorrect assertion in examples/zpipe.c -- Add C++ wrapper in infback9.h [Donais] -- Fix bug in inflateCopy() when decoding fixed codes -- Note in zlib.h how much deflateSetDictionary() actually uses -- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) -- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] -- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] -- Add gzdirect() function to indicate transparent reads -- Update contrib/minizip [Vollant] -- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] -- Add casts in crc32.c to avoid warnings [Oberhumer] -- Add contrib/masmx64 [Vollant] -- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] - -Changes in 1.2.2.2 (30 December 2004) -- Replace structure assignments in deflate.c and inflate.c with zmemcpy to - avoid implicit memcpy calls (portability for no-library compilation) -- Increase sprintf() buffer size in gzdopen() to allow for large numbers -- Add INFLATE_STRICT to check distances against zlib header -- Improve WinCE errno handling and comments [Chang] -- Remove comment about no gzip header processing in FAQ -- Add Z_FIXED strategy option to deflateInit2() to force fixed trees -- Add updated make_vms.com [Coghlan], update README -- Create a new "examples" directory, move gzappend.c there, add zpipe.c, - fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. -- Add FAQ entry and comments in deflate.c on uninitialized memory access -- Add Solaris 9 make options in configure [Gilbert] -- Allow strerror() usage in gzio.c for STDC -- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] -- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] -- Use z_off_t for adler32_combine() and crc32_combine() lengths -- Make adler32() much faster for small len -- Use OS_CODE in deflate() default gzip header - -Changes in 1.2.2.1 (31 October 2004) -- Allow inflateSetDictionary() call for raw inflate -- Fix inflate header crc check bug for file names and comments -- Add deflateSetHeader() and gz_header structure for custom gzip headers -- Add inflateGetheader() to retrieve gzip headers -- Add crc32_combine() and adler32_combine() functions -- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list -- Use zstreamp consistently in zlib.h (inflate_back functions) -- Remove GUNZIP condition from definition of inflate_mode in inflate.h - and in contrib/inflate86/inffast.S [Truta, Anderson] -- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] -- Update projects/README.projects and projects/visualc6 [Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] -- Deprecate Z_ASCII; use Z_TEXT instead [Truta] -- Use a new algorithm for setting strm->data_type in trees.c [Truta] -- Do not define an exit() prototype in zutil.c unless DEBUG defined -- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] -- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() -- Fix Darwin build version identification [Peterson] - -Changes in 1.2.2 (3 October 2004) -- Update zlib.h comments on gzip in-memory processing -- Set adler to 1 in inflateReset() to support Java test suite [Walles] -- Add contrib/dotzlib [Ravn] -- Update win32/DLL_FAQ.txt [Truta] -- Update contrib/minizip [Vollant] -- Move contrib/visual-basic.txt to old/ [Truta] -- Fix assembler builds in projects/visualc6/ [Truta] - -Changes in 1.2.1.2 (9 September 2004) -- Update INDEX file -- Fix trees.c to update strm->data_type (no one ever noticed!) -- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] -- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) -- Add limited multitasking protection to DYNAMIC_CRC_TABLE -- Add NO_vsnprintf for VMS in zutil.h [Mozilla] -- Don't declare strerror() under VMS [Mozilla] -- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize -- Update contrib/ada [Anisimkov] -- Update contrib/minizip [Vollant] -- Fix configure to not hardcode directories for Darwin [Peterson] -- Fix gzio.c to not return error on empty files [Brown] -- Fix indentation; update version in contrib/delphi/ZLib.pas and - contrib/pascal/zlibpas.pas [Truta] -- Update mkasm.bat in contrib/masmx86 [Truta] -- Update contrib/untgz [Truta] -- Add projects/README.projects [Truta] -- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] -- Remove an unnecessary assignment to curr in inftrees.c [Truta] -- Add OS/2 to exe builds in configure [Poltorak] -- Remove err dummy parameter in zlib.h [Kientzle] - -Changes in 1.2.1.1 (9 January 2004) -- Update email address in README -- Several FAQ updates -- Fix a big fat bug in inftrees.c that prevented decoding valid - dynamic blocks with only literals and no distance codes -- - Thanks to "Hot Emu" for the bug report and sample file -- Add a note to puff.c on no distance codes case. - -Changes in 1.2.1 (17 November 2003) -- Remove a tab in contrib/gzappend/gzappend.c -- Update some interfaces in contrib for new zlib functions -- Update zlib version number in some contrib entries -- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] -- Support shared libraries on Hurd and KFreeBSD [Brown] -- Fix error in NO_DIVIDE option of adler32.c - -Changes in 1.2.0.8 (4 November 2003) -- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas -- Add experimental NO_DIVIDE #define in adler32.c - - Possibly faster on some processors (let me know if it is) -- Correct Z_BLOCK to not return on first inflate call if no wrap -- Fix strm->data_type on inflate() return to correctly indicate EOB -- Add deflatePrime() function for appending in the middle of a byte -- Add contrib/gzappend for an example of appending to a stream -- Update win32/DLL_FAQ.txt [Truta] -- Delete Turbo C comment in README [Truta] -- Improve some indentation in zconf.h [Truta] -- Fix infinite loop on bad input in configure script [Church] -- Fix gzeof() for concatenated gzip files [Johnson] -- Add example to contrib/visual-basic.txt [Michael B.] -- Add -p to mkdir's in Makefile.in [vda] -- Fix configure to properly detect presence or lack of printf functions -- Add AS400 support [Monnerat] -- Add a little Cygwin support [Wilson] - -Changes in 1.2.0.7 (21 September 2003) -- Correct some debug formats in contrib/infback9 -- Cast a type in a debug statement in trees.c -- Change search and replace delimiter in configure from % to # [Beebe] -- Update contrib/untgz to 0.2 with various fixes [Truta] -- Add build support for Amiga [Nikl] -- Remove some directories in old that have been updated to 1.2 -- Add dylib building for Mac OS X in configure and Makefile.in -- Remove old distribution stuff from Makefile -- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X -- Update links in README - -Changes in 1.2.0.6 (13 September 2003) -- Minor FAQ updates -- Update contrib/minizip to 1.00 [Vollant] -- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] -- Update POSTINC comment for 68060 [Nikl] -- Add contrib/infback9 with deflate64 decoding (unsupported) -- For MVS define NO_vsnprintf and undefine FAR [van Burik] -- Add pragma for fdopen on MVS [van Burik] - -Changes in 1.2.0.5 (8 September 2003) -- Add OF to inflateBackEnd() declaration in zlib.h -- Remember start when using gzdopen in the middle of a file -- Use internal off_t counters in gz* functions to properly handle seeks -- Perform more rigorous check for distance-too-far in inffast.c -- Add Z_BLOCK flush option to return from inflate at block boundary -- Set strm->data_type on return from inflate - - Indicate bits unused, if at block boundary, and if in last block -- Replace size_t with ptrdiff_t in crc32.c, and check for correct size -- Add condition so old NO_DEFLATE define still works for compatibility -- FAQ update regarding the Windows DLL [Truta] -- INDEX update: add qnx entry, remove aix entry [Truta] -- Install zlib.3 into mandir [Wilson] -- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] -- Adapt the zlib interface to the new DLL convention guidelines [Truta] -- Introduce ZLIB_WINAPI macro to allow the export of functions using - the WINAPI calling convention, for Visual Basic [Vollant, Truta] -- Update msdos and win32 scripts and makefiles [Truta] -- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] -- Add contrib/ada [Anisimkov] -- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] -- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] -- Add contrib/masm686 [Truta] -- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm - [Truta, Vollant] -- Update contrib/delphi; rename to contrib/pascal; add example [Truta] -- Remove contrib/delphi2; add a new contrib/delphi [Truta] -- Avoid inclusion of the nonstandard in contrib/iostream, - and fix some method prototypes [Truta] -- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip - [Truta] -- Avoid the use of backslash (\) in contrib/minizip [Vollant] -- Fix file time handling in contrib/untgz; update makefiles [Truta] -- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines - [Vollant] -- Remove contrib/vstudio/vc15_16 [Vollant] -- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] -- Update README.contrib [Truta] -- Invert the assignment order of match_head and s->prev[...] in - INSERT_STRING [Truta] -- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings - [Truta] -- Compare function pointers with 0, not with NULL or Z_NULL [Truta] -- Fix prototype of syncsearch in inflate.c [Truta] -- Introduce ASMINF macro to be enabled when using an ASM implementation - of inflate_fast [Truta] -- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] -- Modify test_gzio in example.c to take a single file name as a - parameter [Truta] -- Exit the example.c program if gzopen fails [Truta] -- Add type casts around strlen in example.c [Truta] -- Remove casting to sizeof in minigzip.c; give a proper type - to the variable compared with SUFFIX_LEN [Truta] -- Update definitions of STDC and STDC99 in zconf.h [Truta] -- Synchronize zconf.h with the new Windows DLL interface [Truta] -- Use SYS16BIT instead of __32BIT__ to distinguish between - 16- and 32-bit platforms [Truta] -- Use far memory allocators in small 16-bit memory models for - Turbo C [Truta] -- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in - zlibCompileFlags [Truta] -- Cygwin has vsnprintf [Wilson] -- In Windows16, OS_CODE is 0, as in MSDOS [Truta] -- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] - -Changes in 1.2.0.4 (10 August 2003) -- Minor FAQ updates -- Be more strict when checking inflateInit2's windowBits parameter -- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well -- Add gzip wrapper option to deflateInit2 using windowBits -- Add updated QNX rule in configure and qnx directory [Bonnefoy] -- Make inflate distance-too-far checks more rigorous -- Clean up FAR usage in inflate -- Add casting to sizeof() in gzio.c and minigzip.c - -Changes in 1.2.0.3 (19 July 2003) -- Fix silly error in gzungetc() implementation [Vollant] -- Update contrib/minizip and contrib/vstudio [Vollant] -- Fix printf format in example.c -- Correct cdecl support in zconf.in.h [Anisimkov] -- Minor FAQ updates - -Changes in 1.2.0.2 (13 July 2003) -- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons -- Attempt to avoid warnings in crc32.c for pointer-int conversion -- Add AIX to configure, remove aix directory [Bakker] -- Add some casts to minigzip.c -- Improve checking after insecure sprintf() or vsprintf() calls -- Remove #elif's from crc32.c -- Change leave label to inf_leave in inflate.c and infback.c to avoid - library conflicts -- Remove inflate gzip decoding by default--only enable gzip decoding by - special request for stricter backward compatibility -- Add zlibCompileFlags() function to return compilation information -- More typecasting in deflate.c to avoid warnings -- Remove leading underscore from _Capital #defines [Truta] -- Fix configure to link shared library when testing -- Add some Windows CE target adjustments [Mai] -- Remove #define ZLIB_DLL in zconf.h [Vollant] -- Add zlib.3 [Rodgers] -- Update RFC URL in deflate.c and algorithm.txt [Mai] -- Add zlib_dll_FAQ.txt to contrib [Truta] -- Add UL to some constants [Truta] -- Update minizip and vstudio [Vollant] -- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h -- Expand use of NO_DUMMY_DECL to avoid all dummy structures -- Added iostream3 to contrib [Schwardt] -- Replace rewind() with fseek() for WinCE [Truta] -- Improve setting of zlib format compression level flags - - Report 0 for huffman and rle strategies and for level == 0 or 1 - - Report 2 only for level == 6 -- Only deal with 64K limit when necessary at compile time [Truta] -- Allow TOO_FAR check to be turned off at compile time [Truta] -- Add gzclearerr() function [Souza] -- Add gzungetc() function - -Changes in 1.2.0.1 (17 March 2003) -- Add Z_RLE strategy for run-length encoding [Truta] - - When Z_RLE requested, restrict matches to distance one - - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE -- Correct FASTEST compilation to allow level == 0 -- Clean up what gets compiled for FASTEST -- Incorporate changes to zconf.in.h [Vollant] - - Refine detection of Turbo C need for dummy returns - - Refine ZLIB_DLL compilation - - Include additional header file on VMS for off_t typedef -- Try to use _vsnprintf where it supplants vsprintf [Vollant] -- Add some casts in inffast.c -- Enchance comments in zlib.h on what happens if gzprintf() tries to - write more than 4095 bytes before compression -- Remove unused state from inflateBackEnd() -- Remove exit(0) from minigzip.c, example.c -- Get rid of all those darn tabs -- Add "check" target to Makefile.in that does the same thing as "test" -- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in -- Update contrib/inflate86 [Anderson] -- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] -- Add msdos and win32 directories with makefiles [Truta] -- More additions and improvements to the FAQ - -Changes in 1.2.0 (9 March 2003) -- New and improved inflate code - - About 20% faster - - Does not allocate 32K window unless and until needed - - Automatically detects and decompresses gzip streams - - Raw inflate no longer needs an extra dummy byte at end - - Added inflateBack functions using a callback interface--even faster - than inflate, useful for file utilities (gzip, zip) - - Added inflateCopy() function to record state for random access on - externally generated deflate streams (e.g. in gzip files) - - More readable code (I hope) -- New and improved crc32() - - About 50% faster, thanks to suggestions from Rodney Brown -- Add deflateBound() and compressBound() functions -- Fix memory leak in deflateInit2() -- Permit setting dictionary for raw deflate (for parallel deflate) -- Fix const declaration for gzwrite() -- Check for some malloc() failures in gzio.c -- Fix bug in gzopen() on single-byte file 0x1f -- Fix bug in gzread() on concatenated file with 0x1f at end of buffer - and next buffer doesn't start with 0x8b -- Fix uncompress() to return Z_DATA_ERROR on truncated input -- Free memory at end of example.c -- Remove MAX #define in trees.c (conflicted with some libraries) -- Fix static const's in deflate.c, gzio.c, and zutil.[ch] -- Declare malloc() and free() in gzio.c if STDC not defined -- Use malloc() instead of calloc() in zutil.c if int big enough -- Define STDC for AIX -- Add aix/ with approach for compiling shared library on AIX -- Add HP-UX support for shared libraries in configure -- Add OpenUNIX support for shared libraries in configure -- Use $cc instead of gcc to build shared library -- Make prefix directory if needed when installing -- Correct Macintosh avoidance of typedef Byte in zconf.h -- Correct Turbo C memory allocation when under Linux -- Use libz.a instead of -lz in Makefile (assure use of compiled library) -- Update configure to check for snprintf or vsnprintf functions and their - return value, warn during make if using an insecure function -- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that - is lost when library is used--resolution is to build new zconf.h -- Documentation improvements (in zlib.h): - - Document raw deflate and inflate - - Update RFCs URL - - Point out that zlib and gzip formats are different - - Note that Z_BUF_ERROR is not fatal - - Document string limit for gzprintf() and possible buffer overflow - - Note requirement on avail_out when flushing - - Note permitted values of flush parameter of inflate() -- Add some FAQs (and even answers) to the FAQ -- Add contrib/inflate86/ for x86 faster inflate -- Add contrib/blast/ for PKWare Data Compression Library decompression -- Add contrib/puff/ simple inflate for deflate format description - -Changes in 1.1.4 (11 March 2002) -- ZFREE was repeated on same allocation on some error conditions. - This creates a security problem described in - http://www.zlib.org/advisory-2002-03-11.txt -- Returned incorrect error (Z_MEM_ERROR) on some invalid data -- Avoid accesses before window for invalid distances with inflate window - less than 32K. -- force windowBits > 8 to avoid a bug in the encoder for a window size - of 256 bytes. (A complete fix will be available in 1.1.5). - -Changes in 1.1.3 (9 July 1998) -- fix "an inflate input buffer bug that shows up on rare but persistent - occasions" (Mark) -- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) -- fix gzseek(..., SEEK_SET) in write mode -- fix crc check after a gzeek (Frank Faubert) -- fix miniunzip when the last entry in a zip file is itself a zip file - (J Lillge) -- add contrib/asm586 and contrib/asm686 (Brian Raiter) - See http://www.muppetlabs.com/~breadbox/software/assembly.html -- add support for Delphi 3 in contrib/delphi (Bob Dellaca) -- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) -- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) -- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) -- added a FAQ file - -- Support gzdopen on Mac with Metrowerks (Jason Linhart) -- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) -- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) -- avoid some warnings with Borland C (Tom Tanner) -- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) -- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) -- allow several arguments to configure (Tim Mooney, Frodo Looijaard) -- use libdir and includedir in Makefile.in (Tim Mooney) -- support shared libraries on OSF1 V4 (Tim Mooney) -- remove so_locations in "make clean" (Tim Mooney) -- fix maketree.c compilation error (Glenn, Mark) -- Python interface to zlib now in Python 1.5 (Jeremy Hylton) -- new Makefile.riscos (Rich Walker) -- initialize static descriptors in trees.c for embedded targets (Nick Smith) -- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) -- add the OS/2 files in Makefile.in too (Andrew Zabolotny) -- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) -- fix maketree.c to allow clean compilation of inffixed.h (Mark) -- fix parameter check in deflateCopy (Gunther Nikl) -- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) -- Many portability patches by Christian Spieler: - . zutil.c, zutil.h: added "const" for zmem* - . Make_vms.com: fixed some typos - . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists - . msdos/Makefile.msc: remove "default rtl link library" info from obj files - . msdos/Makefile.*: use model-dependent name for the built zlib library - . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: - new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) -- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) -- replace __far with _far for better portability (Christian Spieler, Tom Lane) -- fix test for errno.h in configure (Tim Newsham) - -Changes in 1.1.2 (19 March 98) -- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) - See http://www.winimage.com/zLibDll/unzip.html -- preinitialize the inflate tables for fixed codes, to make the code - completely thread safe (Mark) -- some simplifications and slight speed-up to the inflate code (Mark) -- fix gzeof on non-compressed files (Allan Schrum) -- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) -- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) -- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) -- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) -- do not wrap extern "C" around system includes (Tom Lane) -- mention zlib binding for TCL in README (Andreas Kupries) -- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) -- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) -- allow "configure --prefix $HOME" (Tim Mooney) -- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) -- move Makefile.sas to amiga/Makefile.sas - -Changes in 1.1.1 (27 Feb 98) -- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) -- remove block truncation heuristic which had very marginal effect for zlib - (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the - compression ratio on some files. This also allows inlining _tr_tally for - matches in deflate_slow. -- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) - -Changes in 1.1.0 (24 Feb 98) -- do not return STREAM_END prematurely in inflate (John Bowler) -- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) -- compile with -DFASTEST to get compression code optimized for speed only -- in minigzip, try mmap'ing the input file first (Miguel Albrecht) -- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain - on Sun but significant on HP) - -- add a pointer to experimental unzip library in README (Gilles Vollant) -- initialize variable gcc in configure (Chris Herborth) - -Changes in 1.0.9 (17 Feb 1998) -- added gzputs and gzgets functions -- do not clear eof flag in gzseek (Mark Diekhans) -- fix gzseek for files in transparent mode (Mark Diekhans) -- do not assume that vsprintf returns the number of bytes written (Jens Krinke) -- replace EXPORT with ZEXPORT to avoid conflict with other programs -- added compress2 in zconf.h, zlib.def, zlib.dnt -- new asm code from Gilles Vollant in contrib/asm386 -- simplify the inflate code (Mark): - . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() - . ZALLOC the length list in inflate_trees_fixed() instead of using stack - . ZALLOC the value area for huft_build() instead of using stack - . Simplify Z_FINISH check in inflate() - -- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 -- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) -- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with - the declaration of FAR (Gilles VOllant) -- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) -- read_buf buf parameter of type Bytef* instead of charf* -- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) -- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) -- fix check for presence of directories in "make install" (Ian Willis) - -Changes in 1.0.8 (27 Jan 1998) -- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) -- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) -- added compress2() to allow setting the compression level -- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) -- use constant arrays for the static trees in trees.c instead of computing - them at run time (thanks to Ken Raeburn for this suggestion). To create - trees.h, compile with GEN_TREES_H and run "make test". -- check return code of example in "make test" and display result -- pass minigzip command line options to file_compress -- simplifying code of inflateSync to avoid gcc 2.8 bug - -- support CC="gcc -Wall" in configure -s (QingLong) -- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) -- fix test for shared library support to avoid compiler warnings -- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) -- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) -- do not use fdopen for Metrowerks on Mac (Brad Pettit)) -- add checks for gzputc and gzputc in example.c -- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) -- use const for the CRC table (Ken Raeburn) -- fixed "make uninstall" for shared libraries -- use Tracev instead of Trace in infblock.c -- in example.c use correct compressed length for test_sync -- suppress +vnocompatwarnings in configure for HPUX (not always supported) - -Changes in 1.0.7 (20 Jan 1998) -- fix gzseek which was broken in write mode -- return error for gzseek to negative absolute position -- fix configure for Linux (Chun-Chung Chen) -- increase stack space for MSC (Tim Wegner) -- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) -- define EXPORTVA for gzprintf (Gilles Vollant) -- added man page zlib.3 (Rick Rodgers) -- for contrib/untgz, fix makedir() and improve Makefile - -- check gzseek in write mode in example.c -- allocate extra buffer for seeks only if gzseek is actually called -- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) -- add inflateSyncPoint in zconf.h -- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def - -Changes in 1.0.6 (19 Jan 1998) -- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and - gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) -- Fix a deflate bug occurring only with compression level 0 (thanks to - Andy Buckler for finding this one). -- In minigzip, pass transparently also the first byte for .Z files. -- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() -- check Z_FINISH in inflate (thanks to Marc Schluper) -- Implement deflateCopy (thanks to Adam Costello) -- make static libraries by default in configure, add --shared option. -- move MSDOS or Windows specific files to directory msdos -- suppress the notion of partial flush to simplify the interface - (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) -- suppress history buffer provided by application to simplify the interface - (this feature was not implemented anyway in 1.0.4) -- next_in and avail_in must be initialized before calling inflateInit or - inflateInit2 -- add EXPORT in all exported functions (for Windows DLL) -- added Makefile.nt (thanks to Stephen Williams) -- added the unsupported "contrib" directory: - contrib/asm386/ by Gilles Vollant - 386 asm code replacing longest_match(). - contrib/iostream/ by Kevin Ruland - A C++ I/O streams interface to the zlib gz* functions - contrib/iostream2/ by Tyge Løvset - Another C++ I/O streams interface - contrib/untgz/ by "Pedro A. Aranda Guti\irrez" - A very simple tar.gz file extractor using zlib - contrib/visual-basic.txt by Carlos Rios - How to use compress(), uncompress() and the gz* functions from VB. -- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression - level) in minigzip (thanks to Tom Lane) - -- use const for rommable constants in deflate -- added test for gzseek and gztell in example.c -- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) -- add undocumented function zError to convert error code to string - (for Tim Smithers) -- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. -- Use default memcpy for Symantec MSDOS compiler. -- Add EXPORT keyword for check_func (needed for Windows DLL) -- add current directory to LD_LIBRARY_PATH for "make test" -- create also a link for libz.so.1 -- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) -- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) -- added -soname for Linux in configure (Chun-Chung Chen, -- assign numbers to the exported functions in zlib.def (for Windows DLL) -- add advice in zlib.h for best usage of deflateSetDictionary -- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) -- allow compilation with ANSI keywords only enabled for TurboC in large model -- avoid "versionString"[0] (Borland bug) -- add NEED_DUMMY_RETURN for Borland -- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). -- allow compilation with CC -- defined STDC for OS/2 (David Charlap) -- limit external names to 8 chars for MVS (Thomas Lund) -- in minigzip.c, use static buffers only for 16-bit systems -- fix suffix check for "minigzip -d foo.gz" -- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) -- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) -- added makelcc.bat for lcc-win32 (Tom St Denis) -- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) -- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. -- check for unistd.h in configure (for off_t) -- remove useless check parameter in inflate_blocks_free -- avoid useless assignment of s->check to itself in inflate_blocks_new -- do not flush twice in gzclose (thanks to Ken Raeburn) -- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h -- use NO_ERRNO_H instead of enumeration of operating systems with errno.h -- work around buggy fclose on pipes for HP/UX -- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) -- fix configure if CC is already equal to gcc - -Changes in 1.0.5 (3 Jan 98) -- Fix inflate to terminate gracefully when fed corrupted or invalid data -- Use const for rommable constants in inflate -- Eliminate memory leaks on error conditions in inflate -- Removed some vestigial code in inflate -- Update web address in README - -Changes in 1.0.4 (24 Jul 96) -- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF - bit, so the decompressor could decompress all the correct data but went - on to attempt decompressing extra garbage data. This affected minigzip too. -- zlibVersion and gzerror return const char* (needed for DLL) -- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) -- use z_error only for DEBUG (avoid problem with DLLs) - -Changes in 1.0.3 (2 Jul 96) -- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS - small and medium models; this makes the library incompatible with previous - versions for these models. (No effect in large model or on other systems.) -- return OK instead of BUF_ERROR if previous deflate call returned with - avail_out as zero but there is nothing to do -- added memcmp for non STDC compilers -- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) -- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) -- better check for 16-bit mode MSC (avoids problem with Symantec) - -Changes in 1.0.2 (23 May 96) -- added Windows DLL support -- added a function zlibVersion (for the DLL support) -- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) -- Bytef is define's instead of typedef'd only for Borland C -- avoid reading uninitialized memory in example.c -- mention in README that the zlib format is now RFC1950 -- updated Makefile.dj2 -- added algorithm.doc - -Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] -- fix array overlay in deflate.c which sometimes caused bad compressed data -- fix inflate bug with empty stored block -- fix MSDOS medium model which was broken in 0.99 -- fix deflateParams() which could generate bad compressed data. -- Bytef is define'd instead of typedef'ed (work around Borland bug) -- added an INDEX file -- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), - Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) -- speed up adler32 for modern machines without auto-increment -- added -ansi for IRIX in configure -- static_init_done in trees.c is an int -- define unlink as delete for VMS -- fix configure for QNX -- add configure branch for SCO and HPUX -- avoid many warnings (unused variables, dead assignments, etc...) -- no fdopen for BeOS -- fix the Watcom fix for 32 bit mode (define FAR as empty) -- removed redefinition of Byte for MKWERKS -- work around an MWKERKS bug (incorrect merge of all .h files) - -Changes in 0.99 (27 Jan 96) -- allow preset dictionary shared between compressor and decompressor -- allow compression level 0 (no compression) -- add deflateParams in zlib.h: allow dynamic change of compression level - and compression strategy. -- test large buffers and deflateParams in example.c -- add optional "configure" to build zlib as a shared library -- suppress Makefile.qnx, use configure instead -- fixed deflate for 64-bit systems (detected on Cray) -- fixed inflate_blocks for 64-bit systems (detected on Alpha) -- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) -- always return Z_BUF_ERROR when deflate() has nothing to do -- deflateInit and inflateInit are now macros to allow version checking -- prefix all global functions and types with z_ with -DZ_PREFIX -- make falloc completely reentrant (inftrees.c) -- fixed very unlikely race condition in ct_static_init -- free in reverse order of allocation to help memory manager -- use zlib-1.0/* instead of zlib/* inside the tar.gz -- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith - -Wconversion -Wstrict-prototypes -Wmissing-prototypes" -- allow gzread on concatenated .gz files -- deflateEnd now returns Z_DATA_ERROR if it was premature -- deflate is finally (?) fully deterministic (no matches beyond end of input) -- Document Z_SYNC_FLUSH -- add uninstall in Makefile -- Check for __cpluplus in zlib.h -- Better test in ct_align for partial flush -- avoid harmless warnings for Borland C++ -- initialize hash_head in deflate.c -- avoid warning on fdopen (gzio.c) for HP cc -Aa -- include stdlib.h for STDC compilers -- include errno.h for Cray -- ignore error if ranlib doesn't exist -- call ranlib twice for NeXTSTEP -- use exec_prefix instead of prefix for libz.a -- renamed ct_* as _tr_* to avoid conflict with applications -- clear z->msg in inflateInit2 before any error return -- initialize opaque in example.c, gzio.c, deflate.c and inflate.c -- fixed typo in zconf.h (_GNUC__ => __GNUC__) -- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) -- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) -- in fcalloc, normalize pointer if size > 65520 bytes -- don't use special fcalloc for 32 bit Borland C++ -- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... -- use Z_BINARY instead of BINARY -- document that gzclose after gzdopen will close the file -- allow "a" as mode in gzopen. -- fix error checking in gzread -- allow skipping .gz extra-field on pipes -- added reference to Perl interface in README -- put the crc table in FAR data (I dislike more and more the medium model :) -- added get_crc_table -- added a dimension to all arrays (Borland C can't count). -- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast -- guard against multiple inclusion of *.h (for precompiled header on Mac) -- Watcom C pretends to be Microsoft C small model even in 32 bit mode. -- don't use unsized arrays to avoid silly warnings by Visual C++: - warning C4746: 'inflate_mask' : unsized array treated as '__far' - (what's wrong with far data in far model?). -- define enum out of inflate_blocks_state to allow compilation with C++ - -Changes in 0.95 (16 Aug 95) -- fix MSDOS small and medium model (now easier to adapt to any compiler) -- inlined send_bits -- fix the final (:-) bug for deflate with flush (output was correct but - not completely flushed in rare occasions). -- default window size is same for compression and decompression - (it's now sufficient to set MAX_WBITS in zconf.h). -- voidp -> voidpf and voidnp -> voidp (for consistency with other - typedefs and because voidnp was not near in large model). - -Changes in 0.94 (13 Aug 95) -- support MSDOS medium model -- fix deflate with flush (could sometimes generate bad output) -- fix deflateReset (zlib header was incorrectly suppressed) -- added support for VMS -- allow a compression level in gzopen() -- gzflush now calls fflush -- For deflate with flush, flush even if no more input is provided. -- rename libgz.a as libz.a -- avoid complex expression in infcodes.c triggering Turbo C bug -- work around a problem with gcc on Alpha (in INSERT_STRING) -- don't use inline functions (problem with some gcc versions) -- allow renaming of Byte, uInt, etc... with #define. -- avoid warning about (unused) pointer before start of array in deflate.c -- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c -- avoid reserved word 'new' in trees.c - -Changes in 0.93 (25 June 95) -- temporarily disable inline functions -- make deflate deterministic -- give enough lookahead for PARTIAL_FLUSH -- Set binary mode for stdin/stdout in minigzip.c for OS/2 -- don't even use signed char in inflate (not portable enough) -- fix inflate memory leak for segmented architectures - -Changes in 0.92 (3 May 95) -- don't assume that char is signed (problem on SGI) -- Clear bit buffer when starting a stored block -- no memcpy on Pyramid -- suppressed inftest.c -- optimized fill_window, put longest_match inline for gcc -- optimized inflate on stored blocks. -- untabify all sources to simplify patches - -Changes in 0.91 (2 May 95) -- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h -- Document the memory requirements in zconf.h -- added "make install" -- fix sync search logic in inflateSync -- deflate(Z_FULL_FLUSH) now works even if output buffer too short -- after inflateSync, don't scare people with just "lo world" -- added support for DJGPP - -Changes in 0.9 (1 May 95) -- don't assume that zalloc clears the allocated memory (the TurboC bug - was Mark's bug after all :) -- let again gzread copy uncompressed data unchanged (was working in 0.71) -- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented -- added a test of inflateSync in example.c -- moved MAX_WBITS to zconf.h because users might want to change that. -- document explicitly that zalloc(64K) on MSDOS must return a normalized - pointer (zero offset) -- added Makefiles for Microsoft C, Turbo C, Borland C++ -- faster crc32() - -Changes in 0.8 (29 April 95) -- added fast inflate (inffast.c) -- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this - is incompatible with previous versions of zlib which returned Z_OK. -- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) - (actually that was not a compiler bug, see 0.81 above) -- gzread no longer reads one extra byte in certain cases -- In gzio destroy(), don't reference a freed structure -- avoid many warnings for MSDOS -- avoid the ERROR symbol which is used by MS Windows - -Changes in 0.71 (14 April 95) -- Fixed more MSDOS compilation problems :( There is still a bug with - TurboC large model. - -Changes in 0.7 (14 April 95) -- Added full inflate support. -- Simplified the crc32() interface. The pre- and post-conditioning - (one's complement) is now done inside crc32(). WARNING: this is - incompatible with previous versions; see zlib.h for the new usage. - -Changes in 0.61 (12 April 95) -- workaround for a bug in TurboC. example and minigzip now work on MSDOS. - -Changes in 0.6 (11 April 95) -- added minigzip.c -- added gzdopen to reopen a file descriptor as gzFile -- added transparent reading of non-gziped files in gzread. -- fixed bug in gzread (don't read crc as data) -- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). -- don't allocate big arrays in the stack (for MSDOS) -- fix some MSDOS compilation problems - -Changes in 0.5: -- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but - not yet Z_FULL_FLUSH. -- support decompression but only in a single step (forced Z_FINISH) -- added opaque object for zalloc and zfree. -- added deflateReset and inflateReset -- added a variable zlib_version for consistency checking. -- renamed the 'filter' parameter of deflateInit2 as 'strategy'. - Added Z_FILTERED and Z_HUFFMAN_ONLY constants. - -Changes in 0.4: -- avoid "zip" everywhere, use zlib instead of ziplib. -- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush - if compression method == 8. -- added adler32 and crc32 -- renamed deflateOptions as deflateInit2, call one or the other but not both -- added the method parameter for deflateInit2. -- added inflateInit2 -- simplied considerably deflateInit and inflateInit by not supporting - user-provided history buffer. This is supported only in deflateInit2 - and inflateInit2. - -Changes in 0.3: -- prefix all macro names with Z_ -- use Z_FINISH instead of deflateEnd to finish compression. -- added Z_HUFFMAN_ONLY -- added gzerror() diff --git a/deps/zlib/FAQ b/deps/zlib/FAQ deleted file mode 100644 index 99b7cf92e45497..00000000000000 --- a/deps/zlib/FAQ +++ /dev/null @@ -1,368 +0,0 @@ - - Frequently Asked Questions about zlib - - -If your question is not there, please check the zlib home page -http://zlib.net/ which may have more recent information. -The lastest zlib FAQ is at http://zlib.net/zlib_faq.html - - - 1. Is zlib Y2K-compliant? - - Yes. zlib doesn't handle dates. - - 2. Where can I get a Windows DLL version? - - The zlib sources can be compiled without change to produce a DLL. See the - file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the - precompiled DLL are found in the zlib web site at http://zlib.net/ . - - 3. Where can I get a Visual Basic interface to zlib? - - See - * http://marknelson.us/1997/01/01/zlib-engine/ - * win32/DLL_FAQ.txt in the zlib distribution - - 4. compress() returns Z_BUF_ERROR. - - Make sure that before the call of compress(), the length of the compressed - buffer is equal to the available size of the compressed buffer and not - zero. For Visual Basic, check that this parameter is passed by reference - ("as any"), not by value ("as long"). - - 5. deflate() or inflate() returns Z_BUF_ERROR. - - Before making the call, make sure that avail_in and avail_out are not zero. - When setting the parameter flush equal to Z_FINISH, also make sure that - avail_out is big enough to allow processing all pending input. Note that a - Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be - made with more input or output space. A Z_BUF_ERROR may in fact be - unavoidable depending on how the functions are used, since it is not - possible to tell whether or not there is more output pending when - strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a - heavily annotated example. - - 6. Where's the zlib documentation (man pages, etc.)? - - It's in zlib.h . Examples of zlib usage are in the files test/example.c - and test/minigzip.c, with more in examples/ . - - 7. Why don't you use GNU autoconf or libtool or ...? - - Because we would like to keep zlib as a very small and simple package. - zlib is rather portable and doesn't need much configuration. - - 8. I found a bug in zlib. - - Most of the time, such problems are due to an incorrect usage of zlib. - Please try to reproduce the problem with a small program and send the - corresponding source to us at zlib@gzip.org . Do not send multi-megabyte - data files without prior agreement. - - 9. Why do I get "undefined reference to gzputc"? - - If "make test" produces something like - - example.o(.text+0x154): undefined reference to `gzputc' - - check that you don't have old files libz.* in /usr/lib, /usr/local/lib or - /usr/X11R6/lib. Remove any old versions, then do "make install". - -10. I need a Delphi interface to zlib. - - See the contrib/delphi directory in the zlib distribution. - -11. Can zlib handle .zip archives? - - Not by itself, no. See the directory contrib/minizip in the zlib - distribution. - -12. Can zlib handle .Z files? - - No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt - the code of uncompress on your own. - -13. How can I make a Unix shared library? - - By default a shared (and a static) library is built for Unix. So: - - make distclean - ./configure - make - -14. How do I install a shared zlib library on Unix? - - After the above, then: - - make install - - However, many flavors of Unix come with a shared zlib already installed. - Before going to the trouble of compiling a shared version of zlib and - trying to install it, you may want to check if it's already there! If you - can #include , it's there. The -lz option will probably link to - it. You can check the version at the top of zlib.h or with the - ZLIB_VERSION symbol defined in zlib.h . - -15. I have a question about OttoPDF. - - We are not the authors of OttoPDF. The real author is on the OttoPDF web - site: Joel Hainley, jhainley@myndkryme.com. - -16. Can zlib decode Flate data in an Adobe PDF file? - - Yes. See http://www.pdflib.com/ . To modify PDF forms, see - http://sourceforge.net/projects/acroformtool/ . - -17. Why am I getting this "register_frame_info not found" error on Solaris? - - After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib - generates an error such as: - - ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: - symbol __register_frame_info: referenced symbol not found - - The symbol __register_frame_info is not part of zlib, it is generated by - the C compiler (cc or gcc). You must recompile applications using zlib - which have this problem. This problem is specific to Solaris. See - http://www.sunfreeware.com for Solaris versions of zlib and applications - using zlib. - -18. Why does gzip give an error on a file I make with compress/deflate? - - The compress and deflate functions produce data in the zlib format, which - is different and incompatible with the gzip format. The gz* functions in - zlib on the other hand use the gzip format. Both the zlib and gzip formats - use the same compressed data format internally, but have different headers - and trailers around the compressed data. - -19. Ok, so why are there two different formats? - - The gzip format was designed to retain the directory information about a - single file, such as the name and last modification date. The zlib format - on the other hand was designed for in-memory and communication channel - applications, and has a much more compact header and trailer and uses a - faster integrity check than gzip. - -20. Well that's nice, but how do I make a gzip file in memory? - - You can request that deflate write the gzip format instead of the zlib - format using deflateInit2(). You can also request that inflate decode the - gzip format using inflateInit2(). Read zlib.h for more details. - -21. Is zlib thread-safe? - - Yes. However any library routines that zlib uses and any application- - provided memory allocation routines must also be thread-safe. zlib's gz* - functions use stdio library routines, and most of zlib's functions use the - library memory allocation routines by default. zlib's *Init* functions - allow for the application to provide custom memory allocation routines. - - Of course, you should only operate on any given zlib or gzip stream from a - single thread at a time. - -22. Can I use zlib in my commercial application? - - Yes. Please read the license in zlib.h. - -23. Is zlib under the GNU license? - - No. Please read the license in zlib.h. - -24. The license says that altered source versions must be "plainly marked". So - what exactly do I need to do to meet that requirement? - - You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In - particular, the final version number needs to be changed to "f", and an - identification string should be appended to ZLIB_VERSION. Version numbers - x.x.x.f are reserved for modifications to zlib by others than the zlib - maintainers. For example, if the version of the base zlib you are altering - is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and - ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also - update the version strings in deflate.c and inftrees.c. - - For altered source distributions, you should also note the origin and - nature of the changes in zlib.h, as well as in ChangeLog and README, along - with the dates of the alterations. The origin should include at least your - name (or your company's name), and an email address to contact for help or - issues with the library. - - Note that distributing a compiled zlib library along with zlib.h and - zconf.h is also a source distribution, and so you should change - ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes - in zlib.h as you would for a full source distribution. - -25. Will zlib work on a big-endian or little-endian architecture, and can I - exchange compressed data between them? - - Yes and yes. - -26. Will zlib work on a 64-bit machine? - - Yes. It has been tested on 64-bit machines, and has no dependence on any - data types being limited to 32-bits in length. If you have any - difficulties, please provide a complete problem report to zlib@gzip.org - -27. Will zlib decompress data from the PKWare Data Compression Library? - - No. The PKWare DCL uses a completely different compressed data format than - does PKZIP and zlib. However, you can look in zlib's contrib/blast - directory for a possible solution to your problem. - -28. Can I access data randomly in a compressed stream? - - No, not without some preparation. If when compressing you periodically use - Z_FULL_FLUSH, carefully write all the pending data at those points, and - keep an index of those locations, then you can start decompression at those - points. You have to be careful to not use Z_FULL_FLUSH too often, since it - can significantly degrade compression. Alternatively, you can scan a - deflate stream once to generate an index, and then use that index for - random access. See examples/zran.c . - -29. Does zlib work on MVS, OS/390, CICS, etc.? - - It has in the past, but we have not heard of any recent evidence. There - were working ports of zlib 1.1.4 to MVS, but those links no longer work. - If you know of recent, successful applications of zlib on these operating - systems, please let us know. Thanks. - -30. Is there some simpler, easier to read version of inflate I can look at to - understand the deflate format? - - First off, you should read RFC 1951. Second, yes. Look in zlib's - contrib/puff directory. - -31. Does zlib infringe on any patents? - - As far as we know, no. In fact, that was originally the whole point behind - zlib. Look here for some more information: - - http://www.gzip.org/#faq11 - -32. Can zlib work with greater than 4 GB of data? - - Yes. inflate() and deflate() will process any amount of data correctly. - Each call of inflate() or deflate() is limited to input and output chunks - of the maximum value that can be stored in the compiler's "unsigned int" - type, but there is no limit to the number of chunks. Note however that the - strm.total_in and strm_total_out counters may be limited to 4 GB. These - counters are provided as a convenience and are not used internally by - inflate() or deflate(). The application can easily set up its own counters - updated after each call of inflate() or deflate() to count beyond 4 GB. - compress() and uncompress() may be limited to 4 GB, since they operate in a - single call. gzseek() and gztell() may be limited to 4 GB depending on how - zlib is compiled. See the zlibCompileFlags() function in zlib.h. - - The word "may" appears several times above since there is a 4 GB limit only - if the compiler's "long" type is 32 bits. If the compiler's "long" type is - 64 bits, then the limit is 16 exabytes. - -33. Does zlib have any security vulnerabilities? - - The only one that we are aware of is potentially in gzprintf(). If zlib is - compiled to use sprintf() or vsprintf(), then there is no protection - against a buffer overflow of an 8K string space (or other value as set by - gzbuffer()), other than the caller of gzprintf() assuring that the output - will not exceed 8K. On the other hand, if zlib is compiled to use - snprintf() or vsnprintf(), which should normally be the case, then there is - no vulnerability. The ./configure script will display warnings if an - insecure variation of sprintf() will be used by gzprintf(). Also the - zlibCompileFlags() function will return information on what variant of - sprintf() is used by gzprintf(). - - If you don't have snprintf() or vsnprintf() and would like one, you can - find a portable implementation here: - - http://www.ijs.si/software/snprintf/ - - Note that you should be using the most recent version of zlib. Versions - 1.1.3 and before were subject to a double-free vulnerability, and versions - 1.2.1 and 1.2.2 were subject to an access exception when decompressing - invalid compressed data. - -34. Is there a Java version of zlib? - - Probably what you want is to use zlib in Java. zlib is already included - as part of the Java SDK in the java.util.zip package. If you really want - a version of zlib written in the Java language, look on the zlib home - page for links: http://zlib.net/ . - -35. I get this or that compiler or source-code scanner warning when I crank it - up to maximally-pedantic. Can't you guys write proper code? - - Many years ago, we gave up attempting to avoid warnings on every compiler - in the universe. It just got to be a waste of time, and some compilers - were downright silly as well as contradicted each other. So now, we simply - make sure that the code always works. - -36. Valgrind (or some similar memory access checker) says that deflate is - performing a conditional jump that depends on an uninitialized value. - Isn't that a bug? - - No. That is intentional for performance reasons, and the output of deflate - is not affected. This only started showing up recently since zlib 1.2.x - uses malloc() by default for allocations, whereas earlier versions used - calloc(), which zeros out the allocated memory. Even though the code was - correct, versions 1.2.4 and later was changed to not stimulate these - checkers. - -37. Will zlib read the (insert any ancient or arcane format here) compressed - data format? - - Probably not. Look in the comp.compression FAQ for pointers to various - formats and associated software. - -38. How can I encrypt/decrypt zip files with zlib? - - zlib doesn't support encryption. The original PKZIP encryption is very - weak and can be broken with freely available programs. To get strong - encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib - compression. For PKZIP compatible "encryption", look at - http://www.info-zip.org/ - -39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? - - "gzip" is the gzip format, and "deflate" is the zlib format. They should - probably have called the second one "zlib" instead to avoid confusion with - the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 - correctly points to the zlib specification in RFC 1950 for the "deflate" - transfer encoding, there have been reports of servers and browsers that - incorrectly produce or expect raw deflate data per the deflate - specification in RFC 1951, most notably Microsoft. So even though the - "deflate" transfer encoding using the zlib format would be the more - efficient approach (and in fact exactly what the zlib format was designed - for), using the "gzip" transfer encoding is probably more reliable due to - an unfortunate choice of name on the part of the HTTP 1.1 authors. - - Bottom line: use the gzip format for HTTP 1.1 encoding. - -40. Does zlib support the new "Deflate64" format introduced by PKWare? - - No. PKWare has apparently decided to keep that format proprietary, since - they have not documented it as they have previous compression formats. In - any case, the compression improvements are so modest compared to other more - modern approaches, that it's not worth the effort to implement. - -41. I'm having a problem with the zip functions in zlib, can you help? - - There are no zip functions in zlib. You are probably using minizip by - Giles Vollant, which is found in the contrib directory of zlib. It is not - part of zlib. In fact none of the stuff in contrib is part of zlib. The - files in there are not supported by the zlib authors. You need to contact - the authors of the respective contribution for help. - -42. The match.asm code in contrib is under the GNU General Public License. - Since it's part of zlib, doesn't that mean that all of zlib falls under the - GNU GPL? - - No. The files in contrib are not part of zlib. They were contributed by - other authors and are provided as a convenience to the user within the zlib - distribution. Each item in contrib has its own license. - -43. Is zlib subject to export controls? What is its ECCN? - - zlib is not subject to export controls, and so is classified as EAR99. - -44. Can you please sign these lengthy legal documents and fax them back to us - so that we can use your software in our product? - - No. Go away. Shoo. diff --git a/deps/zlib/INDEX b/deps/zlib/INDEX deleted file mode 100644 index 2ba0641204861d..00000000000000 --- a/deps/zlib/INDEX +++ /dev/null @@ -1,68 +0,0 @@ -CMakeLists.txt cmake build file -ChangeLog history of changes -FAQ Frequently Asked Questions about zlib -INDEX this file -Makefile dummy Makefile that tells you to ./configure -Makefile.in template for Unix Makefile -README guess what -configure configure script for Unix -make_vms.com makefile for VMS -test/example.c zlib usages examples for build testing -test/minigzip.c minimal gzip-like functionality for build testing -test/infcover.c inf*.c code coverage for build coverage testing -treebuild.xml XML description of source file dependencies -zconf.h.cmakein zconf.h template for cmake -zconf.h.in zconf.h template for configure -zlib.3 Man page for zlib -zlib.3.pdf Man page in PDF format -zlib.map Linux symbol information -zlib.pc.in Template for pkg-config descriptor -zlib.pc.cmakein zlib.pc template for cmake -zlib2ansi perl script to convert source files for C++ compilation - -amiga/ makefiles for Amiga SAS C -as400/ makefiles for AS/400 -doc/ documentation for formats and algorithms -msdos/ makefiles for MSDOS -nintendods/ makefile for Nintendo DS -old/ makefiles for various architectures and zlib documentation - files that have not yet been updated for zlib 1.2.x -qnx/ makefiles for QNX -watcom/ makefiles for OpenWatcom -win32/ makefiles for Windows - - zlib public header files (required for library use): -zconf.h -zlib.h - - private source files used to build the zlib library: -adler32.c -compress.c -crc32.c -crc32.h -deflate.c -deflate.h -gzclose.c -gzguts.h -gzlib.c -gzread.c -gzwrite.c -infback.c -inffast.c -inffast.h -inffixed.h -inflate.c -inflate.h -inftrees.c -inftrees.h -trees.c -trees.h -uncompr.c -zutil.c -zutil.h - - source files for sample programs -See examples/README.examples - - unsupported contributions by third parties -See contrib/README.contrib diff --git a/deps/zlib/LICENSE b/deps/zlib/LICENSE new file mode 100644 index 00000000000000..9f056865b5719d --- /dev/null +++ b/deps/zlib/LICENSE @@ -0,0 +1,19 @@ +version 1.2.11, January 15th, 2017 + +Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/deps/zlib/Makefile b/deps/zlib/Makefile deleted file mode 100644 index 6bba86c73fca2a..00000000000000 --- a/deps/zlib/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -all: - -@echo "Please use ./configure first. Thank you." - -distclean: - make -f Makefile.in distclean diff --git a/deps/zlib/Makefile.in b/deps/zlib/Makefile.in deleted file mode 100644 index 5a77949ff06857..00000000000000 --- a/deps/zlib/Makefile.in +++ /dev/null @@ -1,410 +0,0 @@ -# Makefile for zlib -# Copyright (C) 1995-2017 Jean-loup Gailly, Mark Adler -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile and test, type: -# ./configure; make test -# Normally configure builds both a static and a shared library. -# If you want to build just a static library, use: ./configure --static - -# To use the asm code, type: -# cp contrib/asm?86/match.S ./match.S -# make LOC=-DASMV OBJA=match.o - -# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type: -# make install -# To install in $HOME instead of /usr/local, use: -# make install prefix=$HOME - -CC=cc - -CFLAGS=-O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-g -DZLIB_DEBUG -#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ -# -Wstrict-prototypes -Wmissing-prototypes - -SFLAGS=-O -LDFLAGS= -TEST_LDFLAGS=-L. libz.a -LDSHARED=$(CC) -CPP=$(CC) -E - -STATICLIB=libz.a -SHAREDLIB=libz.so -SHAREDLIBV=libz.so.1.2.11 -SHAREDLIBM=libz.so.1 -LIBS=$(STATICLIB) $(SHAREDLIBV) - -AR=ar -ARFLAGS=rc -RANLIB=ranlib -LDCONFIG=ldconfig -LDSHAREDLIBC=-lc -TAR=tar -SHELL=/bin/sh -EXE= - -prefix = /usr/local -exec_prefix = ${prefix} -libdir = ${exec_prefix}/lib -sharedlibdir = ${libdir} -includedir = ${prefix}/include -mandir = ${prefix}/share/man -man3dir = ${mandir}/man3 -pkgconfigdir = ${libdir}/pkgconfig -SRCDIR= -ZINC= -ZINCOUT=-I. - -OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o -OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o -OBJC = $(OBJZ) $(OBJG) - -PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo -PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo -PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG) - -# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo -OBJA = -PIC_OBJA = - -OBJS = $(OBJC) $(OBJA) - -PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA) - -all: static shared - -static: example$(EXE) minigzip$(EXE) - -shared: examplesh$(EXE) minigzipsh$(EXE) - -all64: example64$(EXE) minigzip64$(EXE) - -check: test - -test: all teststatic testshared - -teststatic: static - @TMPST=tmpst_$$; \ - if echo hello world | ./minigzip | ./minigzip -d && ./example $$TMPST ; then \ - echo ' *** zlib test OK ***'; \ - else \ - echo ' *** zlib test FAILED ***'; false; \ - fi; \ - rm -f $$TMPST - -testshared: shared - @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ - LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \ - DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \ - SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \ - TMPSH=tmpsh_$$; \ - if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh $$TMPSH; then \ - echo ' *** zlib shared test OK ***'; \ - else \ - echo ' *** zlib shared test FAILED ***'; false; \ - fi; \ - rm -f $$TMPSH - -test64: all64 - @TMP64=tmp64_$$; \ - if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64 $$TMP64; then \ - echo ' *** zlib 64-bit test OK ***'; \ - else \ - echo ' *** zlib 64-bit test FAILED ***'; false; \ - fi; \ - rm -f $$TMP64 - -infcover.o: $(SRCDIR)test/infcover.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/infcover.c - -infcover: infcover.o libz.a - $(CC) $(CFLAGS) -o $@ infcover.o libz.a - -cover: infcover - rm -f *.gcda - ./infcover - gcov inf*.c - -libz.a: $(OBJS) - $(AR) $(ARFLAGS) $@ $(OBJS) - -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 - -match.o: match.S - $(CPP) match.S > _match.s - $(CC) -c _match.s - mv _match.o match.o - rm -f _match.s - -match.lo: match.S - $(CPP) match.S > _match.s - $(CC) -c -fPIC _match.s - mv _match.o match.lo - rm -f _match.s - -example.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/example.c - -minigzip.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/minigzip.c - -example64.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/example.c - -minigzip64.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/minigzip.c - - -adler32.o: $(SRCDIR)adler32.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)adler32.c - -crc32.o: $(SRCDIR)crc32.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)crc32.c - -deflate.o: $(SRCDIR)deflate.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)deflate.c - -infback.o: $(SRCDIR)infback.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)infback.c - -inffast.o: $(SRCDIR)inffast.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inffast.c - -inflate.o: $(SRCDIR)inflate.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inflate.c - -inftrees.o: $(SRCDIR)inftrees.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inftrees.c - -trees.o: $(SRCDIR)trees.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)trees.c - -zutil.o: $(SRCDIR)zutil.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)zutil.c - -compress.o: $(SRCDIR)compress.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)compress.c - -uncompr.o: $(SRCDIR)uncompr.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)uncompr.c - -gzclose.o: $(SRCDIR)gzclose.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzclose.c - -gzlib.o: $(SRCDIR)gzlib.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzlib.c - -gzread.o: $(SRCDIR)gzread.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzread.c - -gzwrite.o: $(SRCDIR)gzwrite.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzwrite.c - - -adler32.lo: $(SRCDIR)adler32.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/adler32.o $(SRCDIR)adler32.c - -@mv objs/adler32.o $@ - -crc32.lo: $(SRCDIR)crc32.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/crc32.o $(SRCDIR)crc32.c - -@mv objs/crc32.o $@ - -deflate.lo: $(SRCDIR)deflate.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/deflate.o $(SRCDIR)deflate.c - -@mv objs/deflate.o $@ - -infback.lo: $(SRCDIR)infback.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/infback.o $(SRCDIR)infback.c - -@mv objs/infback.o $@ - -inffast.lo: $(SRCDIR)inffast.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inffast.o $(SRCDIR)inffast.c - -@mv objs/inffast.o $@ - -inflate.lo: $(SRCDIR)inflate.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inflate.o $(SRCDIR)inflate.c - -@mv objs/inflate.o $@ - -inftrees.lo: $(SRCDIR)inftrees.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inftrees.o $(SRCDIR)inftrees.c - -@mv objs/inftrees.o $@ - -trees.lo: $(SRCDIR)trees.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/trees.o $(SRCDIR)trees.c - -@mv objs/trees.o $@ - -zutil.lo: $(SRCDIR)zutil.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/zutil.o $(SRCDIR)zutil.c - -@mv objs/zutil.o $@ - -compress.lo: $(SRCDIR)compress.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/compress.o $(SRCDIR)compress.c - -@mv objs/compress.o $@ - -uncompr.lo: $(SRCDIR)uncompr.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/uncompr.o $(SRCDIR)uncompr.c - -@mv objs/uncompr.o $@ - -gzclose.lo: $(SRCDIR)gzclose.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzclose.o $(SRCDIR)gzclose.c - -@mv objs/gzclose.o $@ - -gzlib.lo: $(SRCDIR)gzlib.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzlib.o $(SRCDIR)gzlib.c - -@mv objs/gzlib.o $@ - -gzread.lo: $(SRCDIR)gzread.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzread.o $(SRCDIR)gzread.c - -@mv objs/gzread.o $@ - -gzwrite.lo: $(SRCDIR)gzwrite.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzwrite.o $(SRCDIR)gzwrite.c - -@mv objs/gzwrite.o $@ - - -placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a - $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS) - rm -f $(SHAREDLIB) $(SHAREDLIBM) - ln -s $@ $(SHAREDLIB) - ln -s $@ $(SHAREDLIBM) - -@rmdir objs - -example$(EXE): example.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS) - -minigzip$(EXE): minigzip.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS) - -examplesh$(EXE): example.o $(SHAREDLIBV) - $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV) - -minigzipsh$(EXE): minigzip.o $(SHAREDLIBV) - $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV) - -example64$(EXE): example64.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS) - -minigzip64$(EXE): minigzip64.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS) - -install-libs: $(LIBS) - -@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi - -@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi - -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi - -@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi - -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi - rm -f $(DESTDIR)$(libdir)/$(STATICLIB) - cp $(STATICLIB) $(DESTDIR)$(libdir) - chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB) - -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1 - -@if test -n "$(SHAREDLIBV)"; then \ - rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ - cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \ - echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \ - chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ - echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \ - rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ - ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \ - ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ - ($(LDCONFIG) || true) >/dev/null 2>&1; \ - fi - rm -f $(DESTDIR)$(man3dir)/zlib.3 - cp $(SRCDIR)zlib.3 $(DESTDIR)$(man3dir) - chmod 644 $(DESTDIR)$(man3dir)/zlib.3 - rm -f $(DESTDIR)$(pkgconfigdir)/zlib.pc - cp zlib.pc $(DESTDIR)$(pkgconfigdir) - chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc -# The ranlib in install is needed on NeXTSTEP which checks file times -# ldconfig is for Linux - -install: install-libs - -@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi - rm -f $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h - cp $(SRCDIR)zlib.h zconf.h $(DESTDIR)$(includedir) - chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h - -uninstall: - cd $(DESTDIR)$(includedir) && rm -f zlib.h zconf.h - cd $(DESTDIR)$(libdir) && rm -f libz.a; \ - if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \ - rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \ - fi - cd $(DESTDIR)$(man3dir) && rm -f zlib.3 - cd $(DESTDIR)$(pkgconfigdir) && rm -f zlib.pc - -docs: zlib.3.pdf - -zlib.3.pdf: $(SRCDIR)zlib.3 - groff -mandoc -f H -T ps $(SRCDIR)zlib.3 | ps2pdf - $@ - -zconf.h.cmakein: $(SRCDIR)zconf.h.in - -@ TEMPFILE=zconfh_$$; \ - echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\ - sed -f $$TEMPFILE $(SRCDIR)zconf.h.in > $@ &&\ - touch -r $(SRCDIR)zconf.h.in $@ &&\ - rm $$TEMPFILE - -zconf: $(SRCDIR)zconf.h.in - cp -p $(SRCDIR)zconf.h.in zconf.h - -mostlyclean: clean -clean: - rm -f *.o *.lo *~ \ - example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \ - example64$(EXE) minigzip64$(EXE) \ - infcover \ - libz.* foo.gz so_locations \ - _match.s maketree contrib/infback9/*.o - rm -rf objs - rm -f *.gcda *.gcno *.gcov - rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov - -maintainer-clean: distclean -distclean: clean zconf zconf.h.cmakein docs - rm -f Makefile zlib.pc configure.log - -@rm -f .DS_Store - @if [ -f Makefile.in ]; then \ - printf 'all:\n\t-@echo "Please use ./configure first. Thank you."\n' > Makefile ; \ - printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile ; \ - touch -r $(SRCDIR)Makefile.in Makefile ; fi - @if [ ! -f zconf.h.in ]; then rm -f zconf.h zconf.h.cmakein ; fi - @if [ ! -f zlib.3 ]; then rm -f zlib.3.pdf ; fi - -tags: - etags $(SRCDIR)*.[ch] - -adler32.o zutil.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -gzclose.o gzlib.o gzread.o gzwrite.o: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h -compress.o example.o minigzip.o uncompr.o: $(SRCDIR)zlib.h zconf.h -crc32.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h -deflate.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -infback.o inflate.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h -inffast.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h -inftrees.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h -trees.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h - -adler32.lo zutil.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -gzclose.lo gzlib.lo gzread.lo gzwrite.lo: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h -compress.lo example.lo minigzip.lo uncompr.lo: $(SRCDIR)zlib.h zconf.h -crc32.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h -deflate.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -infback.lo inflate.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h -inffast.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h -inftrees.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h -trees.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h diff --git a/deps/zlib/OWNERS b/deps/zlib/OWNERS new file mode 100644 index 00000000000000..069bcd8c2a1445 --- /dev/null +++ b/deps/zlib/OWNERS @@ -0,0 +1,7 @@ +agl@chromium.org +cavalcantii@chromium.org +cblume@chromium.org +mtklein@chromium.org +scroggo@chromium.org + +# COMPONENT: Internals diff --git a/deps/zlib/README b/deps/zlib/README deleted file mode 100644 index 51106de4753292..00000000000000 --- a/deps/zlib/README +++ /dev/null @@ -1,115 +0,0 @@ -ZLIB DATA COMPRESSION LIBRARY - -zlib 1.2.11 is a general purpose data compression library. All the code is -thread safe. The data format used by the zlib library is described by RFCs -(Request for Comments) 1950 to 1952 in the files -http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and -rfc1952 (gzip format). - -All functions of the compression library are documented in the file zlib.h -(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example -of the library is given in the file test/example.c which also tests that -the library is working correctly. Another example is given in the file -test/minigzip.c. The compression library itself is composed of all source -files in the root directory. - -To compile all files and run the test program, follow the instructions given at -the top of Makefile.in. In short "./configure; make test", and if that goes -well, "make install" should work for most flavors of Unix. For Windows, use -one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use -make_vms.com. - -Questions about zlib should be sent to , or to Gilles Vollant - for the Windows DLL version. The zlib home page is -http://zlib.net/ . Before reporting a problem, please check this site to -verify that you have the latest version of zlib; otherwise get the latest -version and check whether the problem still exists or not. - -PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. - -Mark Nelson wrote an article about zlib for the Jan. 1997 -issue of Dr. Dobb's Journal; a copy of the article is available at -http://marknelson.us/1997/01/01/zlib-engine/ . - -The changes made in version 1.2.11 are documented in the file ChangeLog. - -Unsupported third party contributions are provided in directory contrib/ . - -zlib is available in Java using the java.util.zip package, documented at -http://java.sun.com/developer/technicalArticles/Programming/compression/ . - -A Perl interface to zlib written by Paul Marquess is available -at CPAN (Comprehensive Perl Archive Network) sites, including -http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . - -A Python interface to zlib written by A.M. Kuchling is -available in Python 1.5 and later versions, see -http://docs.python.org/library/zlib.html . - -zlib is built into tcl: http://wiki.tcl.tk/4610 . - -An experimental package to read and write files in .zip format, written on top -of zlib by Gilles Vollant , is available in the -contrib/minizip directory of zlib. - - -Notes for some targets: - -- For Windows DLL versions, please see win32/DLL_FAQ.txt - -- For 64-bit Irix, deflate.c must be compiled without any optimization. With - -O, one libpng test fails. The test works in 32 bit mode (with the -n32 - compiler flag). The compiler bug has been reported to SGI. - -- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works - when compiled with cc. - -- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is - necessary to get gzprintf working correctly. This is done by configure. - -- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with - other compilers. Use "make test" to check your compiler. - -- gzdopen is not supported on RISCOS or BEOS. - -- For PalmOs, see http://palmzlib.sourceforge.net/ - - -Acknowledgments: - - The deflate format used by zlib was defined by Phil Katz. The deflate and - zlib specifications were written by L. Peter Deutsch. Thanks to all the - people who reported problems and suggested various improvements in zlib; they - are too numerous to cite here. - -Copyright notice: - - (C) 1995-2017 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - -If you use the zlib library in a product, we would appreciate *not* receiving -lengthy legal documents to sign. The sources are provided for free but without -warranty of any kind. The library has been entirely written by Jean-loup -Gailly and Mark Adler; it does not include third-party code. - -If you redistribute modified sources, we would appreciate that you include in -the file ChangeLog history information documenting your changes. Please read -the FAQ for more information on the distribution of modified source versions. diff --git a/deps/zlib/README.chromium b/deps/zlib/README.chromium new file mode 100644 index 00000000000000..3d90f79be2ffc2 --- /dev/null +++ b/deps/zlib/README.chromium @@ -0,0 +1,28 @@ +Name: zlib +Short Name: zlib +URL: http://zlib.net/ +Version: 1.2.11 +Security Critical: yes +License: Custom license +License File: LICENSE +License Android Compatible: yes + +Description: +"A massively spiffy yet delicately unobtrusive compression library." + +zlib is a free, general-purpose, legally unencumbered lossless data-compression +library. zlib implements the "deflate" compression algorithm described by RFC +1951, which combines the LZ77 (Lempel-Ziv) algorithm with Huffman coding. zlib +also implements the zlib (RFC 1950) and gzip (RFC 1952) wrapper formats. + +Local Modifications: + - Only source code from the zlib distribution used to build the zlib and + minizip libraries are present. Many other files have been omitted. Only *.c + and *.h files from the upstream root directory and contrib/minizip were + imported. + - The contents of the google directory are original Chromium-specific + additions. + - Added chromeconf.h + - Plus the changes in 'patches' folder. + - Code in contrib/ other than contrib/minizip was added to match zlib's + contributor layout. diff --git a/deps/zlib/README.md b/deps/zlib/README.md new file mode 100644 index 00000000000000..a12f0a7876a168 --- /dev/null +++ b/deps/zlib/README.md @@ -0,0 +1,6 @@ +This copy of zlib comes from the Chromium team's zlib fork which incorporated performance improvements not currently available in standard zlib. + +To update this code: + +* Clone https://chromium.googlesource.com/chromium/src/third_party/zlib +* Comment out the `#include "chromeconf.h"` in zconf.h to maintain full compatibility with node addons diff --git a/deps/zlib/adler32.c b/deps/zlib/adler32.c index d0be4380a39c9c..a42f35fce2a2e0 100644 --- a/deps/zlib/adler32.c +++ b/deps/zlib/adler32.c @@ -59,6 +59,13 @@ local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); # define MOD63(a) a %= BASE #endif +#if defined(ADLER32_SIMD_SSSE3) +#include "adler32_simd.h" +#include "x86.h" +#elif defined(ADLER32_SIMD_NEON) +#include "adler32_simd.h" +#endif + /* ========================================================================= */ uLong ZEXPORT adler32_z(adler, buf, len) uLong adler; @@ -68,6 +75,14 @@ uLong ZEXPORT adler32_z(adler, buf, len) unsigned long sum2; unsigned n; +#if defined(ADLER32_SIMD_SSSE3) + if (x86_cpu_enable_ssse3 && buf && len >= 64) + return adler32_simd_(adler, buf, len); +#elif defined(ADLER32_SIMD_NEON) + if (buf && len >= 64) + return adler32_simd_(adler, buf, len); +#endif + /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; @@ -83,9 +98,24 @@ uLong ZEXPORT adler32_z(adler, buf, len) return adler | (sum2 << 16); } +#if defined(ADLER32_SIMD_SSSE3) + /* + * Use SSSE3 to compute the adler32. Since this routine can be + * freely used, check CPU features here. zlib convention is to + * call adler32(0, NULL, 0), before making calls to adler32(). + * So this is a good early (and infrequent) place to cache CPU + * features for those later, more interesting adler32() calls. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling adler32(0, NULL, 0); */ + x86_check_features(); + return 1L; + } +#else /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; +#endif /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { diff --git a/deps/zlib/adler32_simd.c b/deps/zlib/adler32_simd.c new file mode 100644 index 00000000000000..1354915cc099ad --- /dev/null +++ b/deps/zlib/adler32_simd.c @@ -0,0 +1,366 @@ +/* adler32_simd.c + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + * + * Per http://en.wikipedia.org/wiki/Adler-32 the adler32 A value (aka s1) is + * the sum of N input data bytes D1 ... DN, + * + * A = A0 + D1 + D2 + ... + DN + * + * where A0 is the initial value. + * + * SSE2 _mm_sad_epu8() can be used for byte sums (see http://bit.ly/2wpUOeD, + * for example) and accumulating the byte sums can use SSE shuffle-adds (see + * the "Integer" section of http://bit.ly/2erPT8t for details). Arm NEON has + * similar instructions. + * + * The adler32 B value (aka s2) sums the A values from each step: + * + * B0 + (A0 + D1) + (A0 + D1 + D2) + ... + (A0 + D1 + D2 + ... + DN) or + * + * B0 + N.A0 + N.D1 + (N-1).D2 + (N-2).D3 + ... + (N-(N-1)).DN + * + * B0 being the initial value. For 32 bytes (ideal for garden-variety SIMD): + * + * B = B0 + 32.A0 + [D1 D2 D3 ... D32] x [32 31 30 ... 1]. + * + * Adjacent blocks of 32 input bytes can be iterated with the expressions to + * compute the adler32 s1 s2 of M >> 32 input bytes [1]. + * + * As M grows, the s1 s2 sums grow. If left unchecked, they would eventually + * overflow the precision of their integer representation (bad). However, s1 + * and s2 also need to be computed modulo the adler BASE value (reduced). If + * at most NMAX bytes are processed before a reduce, s1 s2 _cannot_ overflow + * a uint32_t type (the NMAX constraint) [2]. + * + * [1] the iterative equations for s2 contain constant factors; these can be + * hoisted from the n-blocks do loop of the SIMD code. + * + * [2] zlib adler32_z() uses this fact to implement NMAX-block-based updates + * of the adler s1 s2 of uint32_t type (see adler32.c). + */ + +#include "adler32_simd.h" + +/* Definitions from adler32.c: largest prime smaller than 65536 */ +#define BASE 65521U +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ +#define NMAX 5552 + +#if defined(ADLER32_SIMD_SSSE3) + +#include + +uint32_t ZLIB_INTERNAL adler32_simd_( /* SSSE3 */ + uint32_t adler, + const unsigned char *buf, + z_size_t len) +{ + /* + * Split Adler-32 into component sums. + */ + uint32_t s1 = adler & 0xffff; + uint32_t s2 = adler >> 16; + + /* + * Process the data in blocks. + */ + const unsigned BLOCK_SIZE = 1 << 5; + + z_size_t blocks = len / BLOCK_SIZE; + len -= blocks * BLOCK_SIZE; + + while (blocks) + { + unsigned n = NMAX / BLOCK_SIZE; /* The NMAX constraint. */ + if (n > blocks) + n = (unsigned) blocks; + blocks -= n; + + const __m128i tap1 = + _mm_setr_epi8(32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17); + const __m128i tap2 = + _mm_setr_epi8(16,15,14,13,12,11,10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + const __m128i zero = + _mm_setr_epi8( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i ones = + _mm_set_epi16( 1, 1, 1, 1, 1, 1, 1, 1); + + /* + * Process n blocks of data. At most NMAX data bytes can be + * processed before s2 must be reduced modulo BASE. + */ + __m128i v_ps = _mm_set_epi32(0, 0, 0, s1 * n); + __m128i v_s2 = _mm_set_epi32(0, 0, 0, s2); + __m128i v_s1 = _mm_set_epi32(0, 0, 0, 0); + + do { + /* + * Load 32 input bytes. + */ + const __m128i bytes1 = _mm_loadu_si128((__m128i*)(buf)); + const __m128i bytes2 = _mm_loadu_si128((__m128i*)(buf + 16)); + + /* + * Add previous block byte sum to v_ps. + */ + v_ps = _mm_add_epi32(v_ps, v_s1); + + /* + * Horizontally add the bytes for s1, multiply-adds the + * bytes by [ 32, 31, 30, ... ] for s2. + */ + v_s1 = _mm_add_epi32(v_s1, _mm_sad_epu8(bytes1, zero)); + const __m128i mad1 = _mm_maddubs_epi16(bytes1, tap1); + v_s2 = _mm_add_epi32(v_s2, _mm_madd_epi16(mad1, ones)); + + v_s1 = _mm_add_epi32(v_s1, _mm_sad_epu8(bytes2, zero)); + const __m128i mad2 = _mm_maddubs_epi16(bytes2, tap2); + v_s2 = _mm_add_epi32(v_s2, _mm_madd_epi16(mad2, ones)); + + buf += BLOCK_SIZE; + + } while (--n); + + v_s2 = _mm_add_epi32(v_s2, _mm_slli_epi32(v_ps, 5)); + + /* + * Sum epi32 ints v_s1(s2) and accumulate in s1(s2). + */ + +#define S23O1 _MM_SHUFFLE(2,3,0,1) /* A B C D -> B A D C */ +#define S1O32 _MM_SHUFFLE(1,0,3,2) /* A B C D -> C D A B */ + + v_s1 = _mm_add_epi32(v_s1, _mm_shuffle_epi32(v_s1, S23O1)); + v_s1 = _mm_add_epi32(v_s1, _mm_shuffle_epi32(v_s1, S1O32)); + + s1 += _mm_cvtsi128_si32(v_s1); + + v_s2 = _mm_add_epi32(v_s2, _mm_shuffle_epi32(v_s2, S23O1)); + v_s2 = _mm_add_epi32(v_s2, _mm_shuffle_epi32(v_s2, S1O32)); + + s2 = _mm_cvtsi128_si32(v_s2); + +#undef S23O1 +#undef S1O32 + + /* + * Reduce. + */ + s1 %= BASE; + s2 %= BASE; + } + + /* + * Handle leftover data. + */ + if (len) { + if (len >= 16) { + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + len -= 16; + } + + while (len--) { + s2 += (s1 += *buf++); + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Return the recombined sums. + */ + return s1 | (s2 << 16); +} + +#elif defined(ADLER32_SIMD_NEON) + +#include + +uint32_t ZLIB_INTERNAL adler32_simd_( /* NEON */ + uint32_t adler, + const unsigned char *buf, + z_size_t len) +{ + /* + * Split Adler-32 into component sums. + */ + uint32_t s1 = adler & 0xffff; + uint32_t s2 = adler >> 16; + + /* + * Serially compute s1 & s2, until the data is 16-byte aligned. + */ + if ((uintptr_t)buf & 15) { + while ((uintptr_t)buf & 15) { + s2 += (s1 += *buf++); + --len; + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Process the data in blocks. + */ + const unsigned BLOCK_SIZE = 1 << 5; + + z_size_t blocks = len / BLOCK_SIZE; + len -= blocks * BLOCK_SIZE; + + while (blocks) + { + unsigned n = NMAX / BLOCK_SIZE; /* The NMAX constraint. */ + if (n > blocks) + n = (unsigned) blocks; + blocks -= n; + + /* + * Process n blocks of data. At most NMAX data bytes can be + * processed before s2 must be reduced modulo BASE. + */ + uint32x4_t v_s2 = (uint32x4_t) { 0, 0, 0, s1 * n }; + uint32x4_t v_s1 = (uint32x4_t) { 0, 0, 0, 0 }; + + uint16x8_t v_column_sum_1 = vdupq_n_u16(0); + uint16x8_t v_column_sum_2 = vdupq_n_u16(0); + uint16x8_t v_column_sum_3 = vdupq_n_u16(0); + uint16x8_t v_column_sum_4 = vdupq_n_u16(0); + + do { + /* + * Load 32 input bytes. + */ + const uint8x16_t bytes1 = vld1q_u8((uint8_t*)(buf)); + const uint8x16_t bytes2 = vld1q_u8((uint8_t*)(buf + 16)); + + /* + * Add previous block byte sum to v_s2. + */ + v_s2 = vaddq_u32(v_s2, v_s1); + + /* + * Horizontally add the bytes for s1. + */ + v_s1 = vpadalq_u16(v_s1, vpadalq_u8(vpaddlq_u8(bytes1), bytes2)); + + /* + * Vertically add the bytes for s2. + */ + v_column_sum_1 = vaddw_u8(v_column_sum_1, vget_low_u8 (bytes1)); + v_column_sum_2 = vaddw_u8(v_column_sum_2, vget_high_u8(bytes1)); + v_column_sum_3 = vaddw_u8(v_column_sum_3, vget_low_u8 (bytes2)); + v_column_sum_4 = vaddw_u8(v_column_sum_4, vget_high_u8(bytes2)); + + buf += BLOCK_SIZE; + + } while (--n); + + v_s2 = vshlq_n_u32(v_s2, 5); + + /* + * Multiply-add bytes by [ 32, 31, 30, ... ] for s2. + */ + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_1), + (uint16x4_t) { 32, 31, 30, 29 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_1), + (uint16x4_t) { 28, 27, 26, 25 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_2), + (uint16x4_t) { 24, 23, 22, 21 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_2), + (uint16x4_t) { 20, 19, 18, 17 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_3), + (uint16x4_t) { 16, 15, 14, 13 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_3), + (uint16x4_t) { 12, 11, 10, 9 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_4), + (uint16x4_t) { 8, 7, 6, 5 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_4), + (uint16x4_t) { 4, 3, 2, 1 }); + + /* + * Sum epi32 ints v_s1(s2) and accumulate in s1(s2). + */ + uint32x2_t sum1 = vpadd_u32(vget_low_u32(v_s1), vget_high_u32(v_s1)); + uint32x2_t sum2 = vpadd_u32(vget_low_u32(v_s2), vget_high_u32(v_s2)); + uint32x2_t s1s2 = vpadd_u32(sum1, sum2); + + s1 += vget_lane_u32(s1s2, 0); + s2 += vget_lane_u32(s1s2, 1); + + /* + * Reduce. + */ + s1 %= BASE; + s2 %= BASE; + } + + /* + * Handle leftover data. + */ + if (len) { + if (len >= 16) { + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + len -= 16; + } + + while (len--) { + s2 += (s1 += *buf++); + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Return the recombined sums. + */ + return s1 | (s2 << 16); +} + +#endif /* ADLER32_SIMD_SSSE3 */ diff --git a/deps/zlib/adler32_simd.h b/deps/zlib/adler32_simd.h new file mode 100644 index 00000000000000..52bb14d16751c8 --- /dev/null +++ b/deps/zlib/adler32_simd.h @@ -0,0 +1,16 @@ +/* adler32_simd.h + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include + +#include "zconf.h" +#include "zutil.h" + +uint32_t ZLIB_INTERNAL adler32_simd_( + uint32_t adler, + const unsigned char *buf, + z_size_t len); diff --git a/deps/zlib/amiga/Makefile.pup b/deps/zlib/amiga/Makefile.pup deleted file mode 100644 index 8940c120fbb970..00000000000000 --- a/deps/zlib/amiga/Makefile.pup +++ /dev/null @@ -1,69 +0,0 @@ -# Amiga powerUP (TM) Makefile -# makefile for libpng and SAS C V6.58/7.00 PPC compiler -# Copyright (C) 1998 by Andreas R. Kleinert - -LIBNAME = libzip.a - -CC = scppc -CFLAGS = NOSTKCHK NOSINT OPTIMIZE OPTGO OPTPEEP OPTINLOCAL OPTINL \ - OPTLOOP OPTRDEP=8 OPTDEP=8 OPTCOMP=8 NOVER -AR = ppc-amigaos-ar cr -RANLIB = ppc-amigaos-ranlib -LD = ppc-amigaos-ld -r -LDFLAGS = -o -LDLIBS = LIB:scppc.a LIB:end.o -RM = delete quiet - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: example minigzip - -check: test -test: all - example - echo hello world | minigzip | minigzip -d - -$(LIBNAME): $(OBJS) - $(AR) $@ $(OBJS) - -$(RANLIB) $@ - -example: example.o $(LIBNAME) - $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) - -minigzip: minigzip.o $(LIBNAME) - $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) - -mostlyclean: clean -clean: - $(RM) *.o example minigzip $(LIBNAME) foo.gz - -zip: - zip -ul9 zlib README ChangeLog Makefile Make????.??? Makefile.?? \ - descrip.mms *.[ch] - -tgz: - cd ..; tar cfz zlib/zlib.tgz zlib/README zlib/ChangeLog zlib/Makefile \ - zlib/Make????.??? zlib/Makefile.?? zlib/descrip.mms zlib/*.[ch] - -# DO NOT DELETE THIS LINE -- make depend depends on it. - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: crc32.h zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -example.o: zlib.h zconf.h -gzclose.o: zlib.h zconf.h gzguts.h -gzlib.o: zlib.h zconf.h gzguts.h -gzread.o: zlib.h zconf.h gzguts.h -gzwrite.o: zlib.h zconf.h gzguts.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -minigzip.o: zlib.h zconf.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/amiga/Makefile.sas b/deps/zlib/amiga/Makefile.sas deleted file mode 100644 index 749e2915271d25..00000000000000 --- a/deps/zlib/amiga/Makefile.sas +++ /dev/null @@ -1,68 +0,0 @@ -# SMakefile for zlib -# Modified from the standard UNIX Makefile Copyright Jean-loup Gailly -# Osma Ahvenlampi -# Amiga, SAS/C 6.56 & Smake - -CC=sc -CFLAGS=OPT -#CFLAGS=OPT CPU=68030 -#CFLAGS=DEBUG=LINE -LDFLAGS=LIB z.lib - -SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \ - NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \ - DEF=POSTINC - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: SCOPTIONS example minigzip - -check: test -test: all - example - echo hello world | minigzip | minigzip -d - -install: z.lib - copy clone zlib.h zconf.h INCLUDE: - copy clone z.lib LIB: - -z.lib: $(OBJS) - oml z.lib r $(OBJS) - -example: example.o z.lib - $(CC) $(CFLAGS) LINK TO $@ example.o $(LDFLAGS) - -minigzip: minigzip.o z.lib - $(CC) $(CFLAGS) LINK TO $@ minigzip.o $(LDFLAGS) - -mostlyclean: clean -clean: - -delete force quiet example minigzip *.o z.lib foo.gz *.lnk SCOPTIONS - -SCOPTIONS: Makefile.sas - copy to $@ + +int ZLIB_INTERNAL arm_cpu_enable_crc32 = 0; +int ZLIB_INTERNAL arm_cpu_enable_pmull = 0; + +#if defined(ARMV8_OS_ANDROID) || defined(ARMV8_OS_LINUX) || defined(ARMV8_OS_FUCHSIA) +#include +#endif + +#if defined(ARMV8_OS_ANDROID) +#include +#elif defined(ARMV8_OS_LINUX) +#include +#include +#elif defined(ARMV8_OS_FUCHSIA) +#include +#include +#include +#elif defined(ARMV8_OS_WINDOWS) +#include +#else +#error arm_features.c ARM feature detection in not defined for your platform +#endif + +static void _arm_check_features(void); + +#if defined(ARMV8_OS_ANDROID) || defined(ARMV8_OS_LINUX) || defined(ARMV8_OS_FUCHSIA) +static pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; +void ZLIB_INTERNAL arm_check_features(void) +{ + pthread_once(&cpu_check_inited_once, _arm_check_features); +} +#elif defined(ARMV8_OS_WINDOWS) +static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; +static BOOL CALLBACK _arm_check_features_forwarder(PINIT_ONCE once, PVOID param, PVOID* context) +{ + _arm_check_features(); + return TRUE; +} +void ZLIB_INTERNAL arm_check_features(void) +{ + InitOnceExecuteOnce(&cpu_check_inited_once, _arm_check_features_forwarder, + NULL, NULL); +} +#endif + +/* + * See http://bit.ly/2CcoEsr for run-time detection of ARM features and also + * crbug.com/931275 for android_getCpuFeatures() use in the Android sandbox. + */ +static void _arm_check_features(void) +{ +#if defined(ARMV8_OS_ANDROID) && defined(__aarch64__) + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM64_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM64_FEATURE_PMULL); +#elif defined(ARMV8_OS_ANDROID) /* aarch32 */ + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM_FEATURE_PMULL); +#elif defined(ARMV8_OS_LINUX) && defined(__aarch64__) + unsigned long features = getauxval(AT_HWCAP); + arm_cpu_enable_crc32 = !!(features & HWCAP_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP_PMULL); +#elif defined(ARMV8_OS_LINUX) && (defined(__ARM_NEON) || defined(__ARM_NEON__)) + /* Query HWCAP2 for ARMV8-A SoCs running in aarch32 mode */ + unsigned long features = getauxval(AT_HWCAP2); + arm_cpu_enable_crc32 = !!(features & HWCAP2_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP2_PMULL); +#elif defined(ARMV8_OS_FUCHSIA) + uint32_t features; + zx_status_t rc = zx_system_get_features(ZX_FEATURE_KIND_CPU, &features); + if (rc != ZX_OK || (features & ZX_ARM64_FEATURE_ISA_ASIMD) == 0) + return; /* Report nothing if ASIMD(NEON) is missing */ + arm_cpu_enable_crc32 = !!(features & ZX_ARM64_FEATURE_ISA_CRC32); + arm_cpu_enable_pmull = !!(features & ZX_ARM64_FEATURE_ISA_PMULL); +#elif defined(ARMV8_OS_WINDOWS) + arm_cpu_enable_crc32 = IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE); + arm_cpu_enable_pmull = IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE); +#endif +} diff --git a/deps/zlib/arm_features.h b/deps/zlib/arm_features.h new file mode 100644 index 00000000000000..09fec259b1c924 --- /dev/null +++ b/deps/zlib/arm_features.h @@ -0,0 +1,13 @@ +/* arm_features.h -- ARM processor features detection. + * + * Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "zlib.h" + +extern int arm_cpu_enable_crc32; +extern int arm_cpu_enable_pmull; + +void arm_check_features(void); diff --git a/deps/zlib/chromeconf.h b/deps/zlib/chromeconf.h new file mode 100644 index 00000000000000..666093d696a583 --- /dev/null +++ b/deps/zlib/chromeconf.h @@ -0,0 +1,195 @@ +/* Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +#ifndef THIRD_PARTY_ZLIB_CHROMECONF_H_ +#define THIRD_PARTY_ZLIB_CHROMECONF_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) +#if defined(ZLIB_IMPLEMENTATION) +#define ZEXTERN __declspec(dllexport) +#else +#define ZEXTERN __declspec(dllimport) +#endif +#elif defined(ZLIB_IMPLEMENTATION) +#define ZEXTERN __attribute__((visibility("default"))) +#endif +#endif + +/* Rename all zlib names with a Cr_z_ prefix. This is based on the Z_PREFIX + * option from zconf.h, but with a custom prefix. Where zconf.h would rename + * both a macro and its underscore-suffixed internal implementation (such as + * deflateInit2 and deflateInit2_), only the implementation is renamed here. + * The Byte type is also omitted. + * + * To generate this list, run + * sed -rn -e 's/^# *define +([^ ]+) +(z_[^ ]+)$/#define \1 Cr_\2/p' zconf.h + * (use -E instead of -r on macOS). + * + * gzread is also addressed by modifications in gzread.c and zlib.h. */ + +#define Z_CR_PREFIX_SET + +#define _dist_code Cr_z__dist_code +#define _length_code Cr_z__length_code +#define _tr_align Cr_z__tr_align +#define _tr_flush_bits Cr_z__tr_flush_bits +#define _tr_flush_block Cr_z__tr_flush_block +#define _tr_init Cr_z__tr_init +#define _tr_stored_block Cr_z__tr_stored_block +#define _tr_tally Cr_z__tr_tally +#define adler32 Cr_z_adler32 +#define adler32_combine Cr_z_adler32_combine +#define adler32_combine64 Cr_z_adler32_combine64 +#define adler32_z Cr_z_adler32_z +#define compress Cr_z_compress +#define compress2 Cr_z_compress2 +#define compressBound Cr_z_compressBound +#define crc32 Cr_z_crc32 +#define crc32_combine Cr_z_crc32_combine +#define crc32_combine64 Cr_z_crc32_combine64 +#define crc32_z Cr_z_crc32_z +#define deflate Cr_z_deflate +#define deflateBound Cr_z_deflateBound +#define deflateCopy Cr_z_deflateCopy +#define deflateEnd Cr_z_deflateEnd +#define deflateGetDictionary Cr_z_deflateGetDictionary +/* #undef deflateInit */ +/* #undef deflateInit2 */ +#define deflateInit2_ Cr_z_deflateInit2_ +#define deflateInit_ Cr_z_deflateInit_ +#define deflateParams Cr_z_deflateParams +#define deflatePending Cr_z_deflatePending +#define deflatePrime Cr_z_deflatePrime +#define deflateReset Cr_z_deflateReset +#define deflateResetKeep Cr_z_deflateResetKeep +#define deflateSetDictionary Cr_z_deflateSetDictionary +#define deflateSetHeader Cr_z_deflateSetHeader +#define deflateTune Cr_z_deflateTune +#define deflate_copyright Cr_z_deflate_copyright +#define get_crc_table Cr_z_get_crc_table +#define gz_error Cr_z_gz_error +#define gz_intmax Cr_z_gz_intmax +#define gz_strwinerror Cr_z_gz_strwinerror +#define gzbuffer Cr_z_gzbuffer +#define gzclearerr Cr_z_gzclearerr +#define gzclose Cr_z_gzclose +#define gzclose_r Cr_z_gzclose_r +#define gzclose_w Cr_z_gzclose_w +#define gzdirect Cr_z_gzdirect +#define gzdopen Cr_z_gzdopen +#define gzeof Cr_z_gzeof +#define gzerror Cr_z_gzerror +#define gzflush Cr_z_gzflush +#define gzfread Cr_z_gzfread +#define gzfwrite Cr_z_gzfwrite +#define gzgetc Cr_z_gzgetc +#define gzgetc_ Cr_z_gzgetc_ +#define gzgets Cr_z_gzgets +#define gzoffset Cr_z_gzoffset +#define gzoffset64 Cr_z_gzoffset64 +#define gzopen Cr_z_gzopen +#define gzopen64 Cr_z_gzopen64 +#define gzopen_w Cr_z_gzopen_w +#define gzprintf Cr_z_gzprintf +#define gzputc Cr_z_gzputc +#define gzputs Cr_z_gzputs +#define gzread Cr_z_gzread +#define gzrewind Cr_z_gzrewind +#define gzseek Cr_z_gzseek +#define gzseek64 Cr_z_gzseek64 +#define gzsetparams Cr_z_gzsetparams +#define gztell Cr_z_gztell +#define gztell64 Cr_z_gztell64 +#define gzungetc Cr_z_gzungetc +#define gzvprintf Cr_z_gzvprintf +#define gzwrite Cr_z_gzwrite +#define inflate Cr_z_inflate +#define inflateBack Cr_z_inflateBack +#define inflateBackEnd Cr_z_inflateBackEnd +/* #undef inflateBackInit */ +#define inflateBackInit_ Cr_z_inflateBackInit_ +#define inflateCodesUsed Cr_z_inflateCodesUsed +#define inflateCopy Cr_z_inflateCopy +#define inflateEnd Cr_z_inflateEnd +#define inflateGetDictionary Cr_z_inflateGetDictionary +#define inflateGetHeader Cr_z_inflateGetHeader +/* #undef inflateInit */ +/* #undef inflateInit2 */ +#define inflateInit2_ Cr_z_inflateInit2_ +#define inflateInit_ Cr_z_inflateInit_ +#define inflateMark Cr_z_inflateMark +#define inflatePrime Cr_z_inflatePrime +#define inflateReset Cr_z_inflateReset +#define inflateReset2 Cr_z_inflateReset2 +#define inflateResetKeep Cr_z_inflateResetKeep +#define inflateSetDictionary Cr_z_inflateSetDictionary +#define inflateSync Cr_z_inflateSync +#define inflateSyncPoint Cr_z_inflateSyncPoint +#define inflateUndermine Cr_z_inflateUndermine +#define inflateValidate Cr_z_inflateValidate +#define inflate_copyright Cr_z_inflate_copyright +#define inflate_fast Cr_z_inflate_fast +#define inflate_table Cr_z_inflate_table +#define uncompress Cr_z_uncompress +#define uncompress2 Cr_z_uncompress2 +#define zError Cr_z_zError +#define zcalloc Cr_z_zcalloc +#define zcfree Cr_z_zcfree +#define zlibCompileFlags Cr_z_zlibCompileFlags +#define zlibVersion Cr_z_zlibVersion +/* #undef Byte */ +#define Bytef Cr_z_Bytef +#define alloc_func Cr_z_alloc_func +#define charf Cr_z_charf +#define free_func Cr_z_free_func +#define gzFile Cr_z_gzFile +#define gz_header Cr_z_gz_header +#define gz_headerp Cr_z_gz_headerp +#define in_func Cr_z_in_func +#define intf Cr_z_intf +#define out_func Cr_z_out_func +#define uInt Cr_z_uInt +#define uIntf Cr_z_uIntf +#define uLong Cr_z_uLong +#define uLongf Cr_z_uLongf +#define voidp Cr_z_voidp +#define voidpc Cr_z_voidpc +#define voidpf Cr_z_voidpf +#define gz_header_s Cr_z_gz_header_s +/* #undef internal_state */ +/* #undef z_off64_t */ + +/* An exported symbol that isn't handled by Z_PREFIX in zconf.h */ +#define z_errmsg Cr_z_z_errmsg + +/* Symbols added in simd.patch */ +#define copy_with_crc Cr_z_copy_with_crc +#define crc_finalize Cr_z_crc_finalize +#define crc_fold_512to32 Cr_z_crc_fold_512to32 +#define crc_fold_copy Cr_z_crc_fold_copy +#define crc_fold_init Cr_z_crc_fold_init +#define crc_reset Cr_z_crc_reset +#define fill_window_sse Cr_z_fill_window_sse +#define deflate_read_buf Cr_z_deflate_read_buf +#define x86_check_features Cr_z_x86_check_features +#define x86_cpu_enable_simd Cr_z_x86_cpu_enable_simd + +/* Symbols added by adler_simd.c */ +#define adler32_simd_ Cr_z_adler32_simd_ +#define x86_cpu_enable_ssse3 Cr_z_x86_cpu_enable_ssse3 + +/* Symbols added by contrib/optimizations/inffast_chunk */ +#define inflate_fast_chunk_ Cr_z_inflate_fast_chunk_ + +/* Symbols added by crc32_simd.c */ +#define crc32_sse42_simd_ Cr_z_crc32_sse42_simd_ + +/* Symbols added by armv8_crc32 */ +#define arm_cpu_enable_crc32 Cr_z_arm_cpu_enable_crc32 +#define arm_cpu_enable_pmull Cr_z_arm_cpu_enable_pmull +#define arm_check_features Cr_z_arm_check_features +#define armv8_crc32_little Cr_z_armv8_crc32_little + +#endif /* THIRD_PARTY_ZLIB_CHROMECONF_H_ */ diff --git a/deps/zlib/compress.c b/deps/zlib/compress.c index e2db404abf888b..6e8517335da018 100644 --- a/deps/zlib/compress.c +++ b/deps/zlib/compress.c @@ -81,6 +81,16 @@ int ZEXPORT compress (dest, destLen, source, sourceLen) uLong ZEXPORT compressBound (sourceLen) uLong sourceLen; { - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13; + sourceLen = sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; + /* FIXME(cavalcantii): usage of CRC32 Castagnoli as a hash function + * for the hash table of symbols used for compression has a side effect + * where for compression level [4, 5] it will increase the output buffer size + * by 0.1% (i.e. less than 1%) for a high entropy input (i.e. random data). + * To avoid a scenario where client code would fail, for safety we increase + * the expected output size by 0.8% (i.e. 8x more than the worst scenario). + * See: http://crbug.com/990489 + */ + sourceLen += sourceLen >> 7; // Equivalent to 1.0078125 + return sourceLen; } diff --git a/deps/zlib/configure b/deps/zlib/configure deleted file mode 100755 index e974d1fd799fbc..00000000000000 --- a/deps/zlib/configure +++ /dev/null @@ -1,921 +0,0 @@ -#!/bin/sh -# configure script for zlib. -# -# Normally configure builds both a static and a shared library. -# If you want to build just a static library, use: ./configure --static -# -# To impose specific compiler or flags or install directory, use for example: -# prefix=$HOME CC=cc CFLAGS="-O4" ./configure -# or for csh/tcsh users: -# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure) - -# Incorrect settings of CC or CFLAGS may prevent creating a shared library. -# If you have problems, try without defining CC and CFLAGS before reporting -# an error. - -# start off configure.log -echo -------------------- >> configure.log -echo $0 $* >> configure.log -date >> configure.log - -# get source directory -SRCDIR=`dirname $0` -if test $SRCDIR = "."; then - ZINC="" - ZINCOUT="-I." - SRCDIR="" -else - ZINC='-include zconf.h' - ZINCOUT='-I. -I$(SRCDIR)' - SRCDIR="$SRCDIR/" -fi - -# set command prefix for cross-compilation -if [ -n "${CHOST}" ]; then - uname="`echo "${CHOST}" | sed -e 's/^[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)-.*$/\1/'`" - CROSS_PREFIX="${CHOST}-" -fi - -# destination name for static library -STATICLIB=libz.a - -# extract zlib version numbers from zlib.h -VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < ${SRCDIR}zlib.h` -VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < ${SRCDIR}zlib.h` -VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` -VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` - -# establish commands for library building -if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then - AR=${AR-"${CROSS_PREFIX}ar"} - test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log -else - AR=${AR-"ar"} - test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log -fi -ARFLAGS=${ARFLAGS-"rc"} -if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then - RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"} - test -n "${CROSS_PREFIX}" && echo Using ${RANLIB} | tee -a configure.log -else - RANLIB=${RANLIB-"ranlib"} -fi -if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then - NM=${NM-"${CROSS_PREFIX}nm"} - test -n "${CROSS_PREFIX}" && echo Using ${NM} | tee -a configure.log -else - NM=${NM-"nm"} -fi - -# set defaults before processing command line options -LDCONFIG=${LDCONFIG-"ldconfig"} -LDSHAREDLIBC="${LDSHAREDLIBC--lc}" -ARCHS= -prefix=${prefix-/usr/local} -exec_prefix=${exec_prefix-'${prefix}'} -libdir=${libdir-'${exec_prefix}/lib'} -sharedlibdir=${sharedlibdir-'${libdir}'} -includedir=${includedir-'${prefix}/include'} -mandir=${mandir-'${prefix}/share/man'} -shared_ext='.so' -shared=1 -solo=0 -cover=0 -zprefix=0 -zconst=0 -build64=0 -gcc=0 -warn=0 -debug=0 -old_cc="$CC" -old_cflags="$CFLAGS" -OBJC='$(OBJZ) $(OBJG)' -PIC_OBJC='$(PIC_OBJZ) $(PIC_OBJG)' - -# leave this script, optionally in a bad way -leave() -{ - if test "$*" != "0"; then - echo "** $0 aborting." | tee -a configure.log - fi - rm -f $test.[co] $test $test$shared_ext $test.gcno ./--version - echo -------------------- >> configure.log - echo >> configure.log - echo >> configure.log - exit $1 -} - -# process command line options -while test $# -ge 1 -do -case "$1" in - -h* | --help) - echo 'usage:' | tee -a configure.log - echo ' configure [--const] [--zprefix] [--prefix=PREFIX] [--eprefix=EXPREFIX]' | tee -a configure.log - echo ' [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]' | tee -a configure.log - echo ' [--includedir=INCLUDEDIR] [--archs="-arch i386 -arch x86_64"]' | tee -a configure.log - exit 0 ;; - -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;; - -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;; - -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;; - --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;; - -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;; - -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;; - -p* | --prefix) prefix="$2"; shift; shift ;; - -e* | --eprefix) exec_prefix="$2"; shift; shift ;; - -l* | --libdir) libdir="$2"; shift; shift ;; - -i* | --includedir) includedir="$2"; shift; shift ;; - -s* | --shared | --enable-shared) shared=1; shift ;; - -t | --static) shared=0; shift ;; - --solo) solo=1; shift ;; - --cover) cover=1; shift ;; - -z* | --zprefix) zprefix=1; shift ;; - -6* | --64) build64=1; shift ;; - -a*=* | --archs=*) ARCHS=`echo $1 | sed 's/.*=//'`; shift ;; - --sysconfdir=*) echo "ignored option: --sysconfdir" | tee -a configure.log; shift ;; - --localstatedir=*) echo "ignored option: --localstatedir" | tee -a configure.log; shift ;; - -c* | --const) zconst=1; shift ;; - -w* | --warn) warn=1; shift ;; - -d* | --debug) debug=1; shift ;; - *) - echo "unknown option: $1" | tee -a configure.log - echo "$0 --help for help" | tee -a configure.log - leave 1;; - esac -done - -# temporary file name -test=ztest$$ - -# put arguments in log, also put test file in log if used in arguments -show() -{ - case "$*" in - *$test.c*) - echo === $test.c === >> configure.log - cat $test.c >> configure.log - echo === >> configure.log;; - esac - echo $* >> configure.log -} - -# check for gcc vs. cc and set compile and link flags based on the system identified by uname -cat > $test.c <&1` in - *gcc*) gcc=1 ;; - *clang*) gcc=1 ;; -esac - -show $cc -c $test.c -if test "$gcc" -eq 1 && ($cc -c $test.c) >> configure.log 2>&1; then - echo ... using gcc >> configure.log - CC="$cc" - CFLAGS="${CFLAGS--O3}" - SFLAGS="${CFLAGS--O3} -fPIC" - if test "$ARCHS"; then - CFLAGS="${CFLAGS} ${ARCHS}" - LDFLAGS="${LDFLAGS} ${ARCHS}" - fi - if test $build64 -eq 1; then - CFLAGS="${CFLAGS} -m64" - SFLAGS="${SFLAGS} -m64" - fi - if test "$warn" -eq 1; then - if test "$zconst" -eq 1; then - CFLAGS="${CFLAGS} -Wall -Wextra -Wcast-qual -pedantic -DZLIB_CONST" - else - CFLAGS="${CFLAGS} -Wall -Wextra -pedantic" - fi - fi - if test $debug -eq 1; then - CFLAGS="${CFLAGS} -DZLIB_DEBUG" - SFLAGS="${SFLAGS} -DZLIB_DEBUG" - fi - if test -z "$uname"; then - uname=`(uname -s || echo unknown) 2>/dev/null` - fi - case "$uname" in - Linux* | linux* | GNU | GNU/* | solaris*) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} ;; - *BSD | *bsd* | DragonFly) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} - LDCONFIG="ldconfig -m" ;; - CYGWIN* | Cygwin* | cygwin* | OS/2*) - EXE='.exe' ;; - MINGW* | mingw*) -# temporary bypass - rm -f $test.[co] $test $test$shared_ext - echo "Please use win32/Makefile.gcc instead." | tee -a configure.log - leave 1 - LDSHARED=${LDSHARED-"$cc -shared"} - LDSHAREDLIBC="" - EXE='.exe' ;; - QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4 - # (alain.bonnefoy@icbt.com) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;; - HP-UX*) - LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"} - case `(uname -m || echo unknown) 2>/dev/null` in - ia64) - shared_ext='.so' - SHAREDLIB='libz.so' ;; - *) - shared_ext='.sl' - SHAREDLIB='libz.sl' ;; - esac ;; - Darwin* | darwin*) - shared_ext='.dylib' - SHAREDLIB=libz$shared_ext - SHAREDLIBV=libz.$VER$shared_ext - SHAREDLIBM=libz.$VER1$shared_ext - LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"} - if libtool -V 2>&1 | grep Apple > /dev/null; then - AR="libtool" - else - AR="/usr/bin/libtool" - fi - ARFLAGS="-o" ;; - *) LDSHARED=${LDSHARED-"$cc -shared"} ;; - esac -else - # find system name and corresponding cc options - CC=${CC-cc} - gcc=0 - echo ... using $CC >> configure.log - if test -z "$uname"; then - uname=`(uname -sr || echo unknown) 2>/dev/null` - fi - case "$uname" in - HP-UX*) SFLAGS=${CFLAGS-"-O +z"} - CFLAGS=${CFLAGS-"-O"} -# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"} - LDSHARED=${LDSHARED-"ld -b"} - case `(uname -m || echo unknown) 2>/dev/null` in - ia64) - shared_ext='.so' - SHAREDLIB='libz.so' ;; - *) - shared_ext='.sl' - SHAREDLIB='libz.sl' ;; - esac ;; - IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."} - CFLAGS=${CFLAGS-"-ansi -O2"} - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; - OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"} - CFLAGS=${CFLAGS-"-O -std1"} - LDFLAGS="${LDFLAGS} -Wl,-rpath,." - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;; - OSF1*) SFLAGS=${CFLAGS-"-O -std1"} - CFLAGS=${CFLAGS-"-O -std1"} - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; - QNX*) SFLAGS=${CFLAGS-"-4 -O"} - CFLAGS=${CFLAGS-"-4 -O"} - LDSHARED=${LDSHARED-"cc"} - RANLIB=${RANLIB-"true"} - AR="cc" - ARFLAGS="-A" ;; - SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "} - CFLAGS=${CFLAGS-"-O3"} - LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;; - SunOS\ 5* | solaris*) - LDSHARED=${LDSHARED-"cc -G -h libz$shared_ext.$VER1"} - SFLAGS=${CFLAGS-"-fast -KPIC"} - CFLAGS=${CFLAGS-"-fast"} - if test $build64 -eq 1; then - # old versions of SunPRO/Workshop/Studio don't support -m64, - # but newer ones do. Check for it. - flag64=`$CC -flags | egrep -- '^-m64'` - if test x"$flag64" != x"" ; then - CFLAGS="${CFLAGS} -m64" - SFLAGS="${SFLAGS} -m64" - else - case `(uname -m || echo unknown) 2>/dev/null` in - i86*) - SFLAGS="$SFLAGS -xarch=amd64" - CFLAGS="$CFLAGS -xarch=amd64" ;; - *) - SFLAGS="$SFLAGS -xarch=v9" - CFLAGS="$CFLAGS -xarch=v9" ;; - esac - fi - fi - if test -n "$ZINC"; then - ZINC='-I- -I. -I$(SRCDIR)' - fi - ;; - SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"} - CFLAGS=${CFLAGS-"-O2"} - LDSHARED=${LDSHARED-"ld"} ;; - SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"} - CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"} - LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;; - UNIX_System_V\ 4.2.0) - SFLAGS=${CFLAGS-"-KPIC -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - UNIX_SV\ 4.2MP) - SFLAGS=${CFLAGS-"-Kconform_pic -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - OpenUNIX\ 5) - SFLAGS=${CFLAGS-"-KPIC -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - AIX*) # Courtesy of dbakker@arrayasolutions.com - SFLAGS=${CFLAGS-"-O -qmaxmem=8192"} - CFLAGS=${CFLAGS-"-O -qmaxmem=8192"} - LDSHARED=${LDSHARED-"xlc -G"} ;; - # send working options for other systems to zlib@gzip.org - *) SFLAGS=${CFLAGS-"-O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -shared"} ;; - esac -fi - -# destination names for shared library if not defined above -SHAREDLIB=${SHAREDLIB-"libz$shared_ext"} -SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"} -SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"} - -echo >> configure.log - -# define functions for testing compiler and library characteristics and logging the results - -cat > $test.c </dev/null; then - try() - { - show $* - test "`( $* ) 2>&1 | tee -a configure.log`" = "" - } - echo - using any output from compiler to indicate an error >> configure.log -else - try() - { - show $* - ( $* ) >> configure.log 2>&1 - ret=$? - if test $ret -ne 0; then - echo "(exit code "$ret")" >> configure.log - fi - return $ret - } -fi - -tryboth() -{ - show $* - got=`( $* ) 2>&1` - ret=$? - printf %s "$got" >> configure.log - if test $ret -ne 0; then - return $ret - fi - test "$got" = "" -} - -cat > $test.c << EOF -int foo() { return 0; } -EOF -echo "Checking for obsessive-compulsive compiler options..." >> configure.log -if try $CC -c $CFLAGS $test.c; then - : -else - echo "Compiler error reporting is too harsh for $0 (perhaps remove -Werror)." | tee -a configure.log - leave 1 -fi - -echo >> configure.log - -# see if shared library build supported -cat > $test.c <> configure.log - show "$NM $test.o | grep _hello" - if test "`$NM $test.o | grep _hello | tee -a configure.log`" = ""; then - CPP="$CPP -DNO_UNDERLINE" - echo Checking for underline in external names... No. | tee -a configure.log - else - echo Checking for underline in external names... Yes. | tee -a configure.log - fi ;; -esac - -echo >> configure.log - -# check for size_t -cat > $test.c < -#include -size_t dummy = 0; -EOF -if try $CC -c $CFLAGS $test.c; then - echo "Checking for size_t... Yes." | tee -a configure.log - need_sizet=0 -else - echo "Checking for size_t... No." | tee -a configure.log - need_sizet=1 -fi - -echo >> configure.log - -# find the size_t integer type, if needed -if test $need_sizet -eq 1; then - cat > $test.c < $test.c < -int main(void) { - if (sizeof(void *) <= sizeof(int)) puts("int"); - else if (sizeof(void *) <= sizeof(long)) puts("long"); - else puts("z_longlong"); - return 0; -} -EOF - else - echo "Checking for long long... No." | tee -a configure.log - cat > $test.c < -int main(void) { - if (sizeof(void *) <= sizeof(int)) puts("int"); - else puts("long"); - return 0; -} -EOF - fi - if try $CC $CFLAGS -o $test $test.c; then - sizet=`./$test` - echo "Checking for a pointer-size integer type..." $sizet"." | tee -a configure.log - else - echo "Failed to find a pointer-size integer type." | tee -a configure.log - leave 1 - fi -fi - -if test $need_sizet -eq 1; then - CFLAGS="${CFLAGS} -DNO_SIZE_T=${sizet}" - SFLAGS="${SFLAGS} -DNO_SIZE_T=${sizet}" -fi - -echo >> configure.log - -# check for large file support, and if none, check for fseeko() -cat > $test.c < -off64_t dummy = 0; -EOF -if try $CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c; then - CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1" - SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1" - ALL="${ALL} all64" - TEST="${TEST} test64" - echo "Checking for off64_t... Yes." | tee -a configure.log - echo "Checking for fseeko... Yes." | tee -a configure.log -else - echo "Checking for off64_t... No." | tee -a configure.log - echo >> configure.log - cat > $test.c < -int main(void) { - fseeko(NULL, 0, 0); - return 0; -} -EOF - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for fseeko... Yes." | tee -a configure.log - else - CFLAGS="${CFLAGS} -DNO_FSEEKO" - SFLAGS="${SFLAGS} -DNO_FSEEKO" - echo "Checking for fseeko... No." | tee -a configure.log - fi -fi - -echo >> configure.log - -# check for strerror() for use by gz* functions -cat > $test.c < -#include -int main() { return strlen(strerror(errno)); } -EOF -if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for strerror... Yes." | tee -a configure.log -else - CFLAGS="${CFLAGS} -DNO_STRERROR" - SFLAGS="${SFLAGS} -DNO_STRERROR" - echo "Checking for strerror... No." | tee -a configure.log -fi - -# copy clean zconf.h for subsequent edits -cp -p ${SRCDIR}zconf.h.in zconf.h - -echo >> configure.log - -# check for unistd.h and save result in zconf.h -cat > $test.c < -int main() { return 0; } -EOF -if try $CC -c $CFLAGS $test.c; then - sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo "Checking for unistd.h... Yes." | tee -a configure.log -else - echo "Checking for unistd.h... No." | tee -a configure.log -fi - -echo >> configure.log - -# check for stdarg.h and save result in zconf.h -cat > $test.c < -int main() { return 0; } -EOF -if try $CC -c $CFLAGS $test.c; then - sed < zconf.h "/^#ifdef HAVE_STDARG_H.* may be/s/def HAVE_STDARG_H\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo "Checking for stdarg.h... Yes." | tee -a configure.log -else - echo "Checking for stdarg.h... No." | tee -a configure.log -fi - -# if the z_ prefix was requested, save that in zconf.h -if test $zprefix -eq 1; then - sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo >> configure.log - echo "Using z_ prefix on all symbols." | tee -a configure.log -fi - -# if --solo compilation was requested, save that in zconf.h and remove gz stuff from object lists -if test $solo -eq 1; then - sed '/#define ZCONF_H/a\ -#define Z_SOLO - -' < zconf.h > zconf.temp.h - mv zconf.temp.h zconf.h -OBJC='$(OBJZ)' -PIC_OBJC='$(PIC_OBJZ)' -fi - -# if code coverage testing was requested, use older gcc if defined, e.g. "gcc-4.2" on Mac OS X -if test $cover -eq 1; then - CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage" - if test -n "$GCC_CLASSIC"; then - CC=$GCC_CLASSIC - fi -fi - -echo >> configure.log - -# conduct a series of tests to resolve eight possible cases of using "vs" or "s" printf functions -# (using stdarg or not), with or without "n" (proving size of buffer), and with or without a -# return value. The most secure result is vsnprintf() with a return value. snprintf() with a -# return value is secure as well, but then gzprintf() will be limited to 20 arguments. -cat > $test.c < -#include -#include "zconf.h" -int main() -{ -#ifndef STDC - choke me -#endif - return 0; -} -EOF -if try $CC -c $CFLAGS $test.c; then - echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()." | tee -a configure.log - - echo >> configure.log - cat > $test.c < -#include -int mytest(const char *fmt, ...) -{ - char buf[20]; - va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return 0; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for vsnprintf() in stdio.h... Yes." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -#include -int mytest(const char *fmt, ...) -{ - int n; - char buf[20]; - va_list ap; - va_start(ap, fmt); - n = vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return n; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of vsnprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_vsnprintf_void" - SFLAGS="$SFLAGS -DHAS_vsnprintf_void" - echo "Checking for return value of vsnprintf()... No." | tee -a configure.log - echo " WARNING: apparently vsnprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - else - CFLAGS="$CFLAGS -DNO_vsnprintf" - SFLAGS="$SFLAGS -DNO_vsnprintf" - echo "Checking for vsnprintf() in stdio.h... No." | tee -a configure.log - echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" | tee -a configure.log - echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -#include -int mytest(const char *fmt, ...) -{ - int n; - char buf[20]; - va_list ap; - va_start(ap, fmt); - n = vsprintf(buf, fmt, ap); - va_end(ap); - return n; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of vsprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_vsprintf_void" - SFLAGS="$SFLAGS -DHAS_vsprintf_void" - echo "Checking for return value of vsprintf()... No." | tee -a configure.log - echo " WARNING: apparently vsprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - fi -else - echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - snprintf(buf, sizeof(buf), "%s", "foo"); - return 0; -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for snprintf() in stdio.h... Yes." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - return snprintf(buf, sizeof(buf), "%s", "foo"); -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of snprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_snprintf_void" - SFLAGS="$SFLAGS -DHAS_snprintf_void" - echo "Checking for return value of snprintf()... No." | tee -a configure.log - echo " WARNING: apparently snprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - else - CFLAGS="$CFLAGS -DNO_snprintf" - SFLAGS="$SFLAGS -DNO_snprintf" - echo "Checking for snprintf() in stdio.h... No." | tee -a configure.log - echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" | tee -a configure.log - echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - return sprintf(buf, "%s", "foo"); -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of sprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_sprintf_void" - SFLAGS="$SFLAGS -DHAS_sprintf_void" - echo "Checking for return value of sprintf()... No." | tee -a configure.log - echo " WARNING: apparently sprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - fi -fi - -# see if we can hide zlib internal symbols that are linked between separate source files -if test "$gcc" -eq 1; then - echo >> configure.log - cat > $test.c <> configure.log -echo ALL = $ALL >> configure.log -echo AR = $AR >> configure.log -echo ARFLAGS = $ARFLAGS >> configure.log -echo CC = $CC >> configure.log -echo CFLAGS = $CFLAGS >> configure.log -echo CPP = $CPP >> configure.log -echo EXE = $EXE >> configure.log -echo LDCONFIG = $LDCONFIG >> configure.log -echo LDFLAGS = $LDFLAGS >> configure.log -echo LDSHARED = $LDSHARED >> configure.log -echo LDSHAREDLIBC = $LDSHAREDLIBC >> configure.log -echo OBJC = $OBJC >> configure.log -echo PIC_OBJC = $PIC_OBJC >> configure.log -echo RANLIB = $RANLIB >> configure.log -echo SFLAGS = $SFLAGS >> configure.log -echo SHAREDLIB = $SHAREDLIB >> configure.log -echo SHAREDLIBM = $SHAREDLIBM >> configure.log -echo SHAREDLIBV = $SHAREDLIBV >> configure.log -echo STATICLIB = $STATICLIB >> configure.log -echo TEST = $TEST >> configure.log -echo VER = $VER >> configure.log -echo Z_U4 = $Z_U4 >> configure.log -echo SRCDIR = $SRCDIR >> configure.log -echo exec_prefix = $exec_prefix >> configure.log -echo includedir = $includedir >> configure.log -echo libdir = $libdir >> configure.log -echo mandir = $mandir >> configure.log -echo prefix = $prefix >> configure.log -echo sharedlibdir = $sharedlibdir >> configure.log -echo uname = $uname >> configure.log - -# udpate Makefile with the configure results -sed < ${SRCDIR}Makefile.in " -/^CC *=/s#=.*#=$CC# -/^CFLAGS *=/s#=.*#=$CFLAGS# -/^SFLAGS *=/s#=.*#=$SFLAGS# -/^LDFLAGS *=/s#=.*#=$LDFLAGS# -/^LDSHARED *=/s#=.*#=$LDSHARED# -/^CPP *=/s#=.*#=$CPP# -/^STATICLIB *=/s#=.*#=$STATICLIB# -/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# -/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# -/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# -/^AR *=/s#=.*#=$AR# -/^ARFLAGS *=/s#=.*#=$ARFLAGS# -/^RANLIB *=/s#=.*#=$RANLIB# -/^LDCONFIG *=/s#=.*#=$LDCONFIG# -/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC# -/^EXE *=/s#=.*#=$EXE# -/^SRCDIR *=/s#=.*#=$SRCDIR# -/^ZINC *=/s#=.*#=$ZINC# -/^ZINCOUT *=/s#=.*#=$ZINCOUT# -/^prefix *=/s#=.*#=$prefix# -/^exec_prefix *=/s#=.*#=$exec_prefix# -/^libdir *=/s#=.*#=$libdir# -/^sharedlibdir *=/s#=.*#=$sharedlibdir# -/^includedir *=/s#=.*#=$includedir# -/^mandir *=/s#=.*#=$mandir# -/^OBJC *=/s#=.*#= $OBJC# -/^PIC_OBJC *=/s#=.*#= $PIC_OBJC# -/^all: */s#:.*#: $ALL# -/^test: */s#:.*#: $TEST# -" > Makefile - -# create zlib.pc with the configure results -sed < ${SRCDIR}zlib.pc.in " -/^CC *=/s#=.*#=$CC# -/^CFLAGS *=/s#=.*#=$CFLAGS# -/^CPP *=/s#=.*#=$CPP# -/^LDSHARED *=/s#=.*#=$LDSHARED# -/^STATICLIB *=/s#=.*#=$STATICLIB# -/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# -/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# -/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# -/^AR *=/s#=.*#=$AR# -/^ARFLAGS *=/s#=.*#=$ARFLAGS# -/^RANLIB *=/s#=.*#=$RANLIB# -/^EXE *=/s#=.*#=$EXE# -/^prefix *=/s#=.*#=$prefix# -/^exec_prefix *=/s#=.*#=$exec_prefix# -/^libdir *=/s#=.*#=$libdir# -/^sharedlibdir *=/s#=.*#=$sharedlibdir# -/^includedir *=/s#=.*#=$includedir# -/^mandir *=/s#=.*#=$mandir# -/^LDFLAGS *=/s#=.*#=$LDFLAGS# -" | sed -e " -s/\@VERSION\@/$VER/g; -" > zlib.pc - -# done -leave 0 diff --git a/deps/zlib/contrib/README.contrib b/deps/zlib/contrib/README.contrib deleted file mode 100644 index a411d5c396bd41..00000000000000 --- a/deps/zlib/contrib/README.contrib +++ /dev/null @@ -1,78 +0,0 @@ -All files under this contrib directory are UNSUPPORTED. There were -provided by users of zlib and were not tested by the authors of zlib. -Use at your own risk. Please contact the authors of the contributions -for help about these, not the zlib authors. Thanks. - - -ada/ by Dmitriy Anisimkov - Support for Ada - See http://zlib-ada.sourceforge.net/ - -amd64/ by Mikhail Teterin - asm code for AMD64 - See patch at http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/96393 - -asm686/ by Brian Raiter - asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax - See http://www.muppetlabs.com/~breadbox/software/assembly.html - -blast/ by Mark Adler - Decompressor for output of PKWare Data Compression Library (DCL) - -delphi/ by Cosmin Truta - Support for Delphi and C++ Builder - -dotzlib/ by Henrik Ravn - Support for Microsoft .Net and Visual C++ .Net - -gcc_gvmat64/by Gilles Vollant - GCC Version of x86 64-bit (AMD64 and Intel EM64t) code for x64 - assembler to replace longest_match() and inflate_fast() - -infback9/ by Mark Adler - Unsupported diffs to infback to decode the deflate64 format - -inflate86/ by Chris Anderson - Tuned x86 gcc asm code to replace inflate_fast() - -iostream/ by Kevin Ruland - A C++ I/O streams interface to the zlib gz* functions - -iostream2/ by Tyge Løvset - Another C++ I/O streams interface - -iostream3/ by Ludwig Schwardt - and Kevin Ruland - Yet another C++ I/O streams interface - -masmx64/ by Gilles Vollant - x86 64-bit (AMD64 and Intel EM64t) code for x64 assembler to - replace longest_match() and inflate_fast(), also masm x86 - 64-bits translation of Chris Anderson inflate_fast() - -masmx86/ by Gilles Vollant - x86 asm code to replace longest_match() and inflate_fast(), - for Visual C++ and MASM (32 bits). - Based on Brian Raiter (asm686) and Chris Anderson (inflate86) - -minizip/ by Gilles Vollant - Mini zip and unzip based on zlib - Includes Zip64 support by Mathias Svensson - See http://www.winimage.com/zLibDll/minizip.html - -pascal/ by Bob Dellaca et al. - Support for Pascal - -puff/ by Mark Adler - Small, low memory usage inflate. Also serves to provide an - unambiguous description of the deflate format. - -testzlib/ by Gilles Vollant - Example of the use of zlib - -untgz/ by Pedro A. Aranda Gutierrez - A very simple tar.gz file extractor using zlib - -vstudio/ by Gilles Vollant - Building a minizip-enhanced zlib with Microsoft Visual Studio - Includes vc11 from kreuzerkrieg and vc12 from davispuh diff --git a/deps/zlib/contrib/ada/buffer_demo.adb b/deps/zlib/contrib/ada/buffer_demo.adb deleted file mode 100644 index 46b8638107fbd5..00000000000000 --- a/deps/zlib/contrib/ada/buffer_demo.adb +++ /dev/null @@ -1,106 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- --- --- $Id: buffer_demo.adb,v 1.3 2004/09/06 06:55:35 vagul Exp $ - --- This demo program provided by Dr Steve Sangwine --- --- Demonstration of a problem with Zlib-Ada (already fixed) when a buffer --- of exactly the correct size is used for decompressed data, and the last --- few bytes passed in to Zlib are checksum bytes. - --- This program compresses a string of text, and then decompresses the --- compressed text into a buffer of the same size as the original text. - -with Ada.Streams; use Ada.Streams; -with Ada.Text_IO; - -with ZLib; use ZLib; - -procedure Buffer_Demo is - EOL : Character renames ASCII.LF; - Text : constant String - := "Four score and seven years ago our fathers brought forth," & EOL & - "upon this continent, a new nation, conceived in liberty," & EOL & - "and dedicated to the proposition that `all men are created equal'."; - - Source : Stream_Element_Array (1 .. Text'Length); - for Source'Address use Text'Address; - -begin - Ada.Text_IO.Put (Text); - Ada.Text_IO.New_Line; - Ada.Text_IO.Put_Line - ("Uncompressed size : " & Positive'Image (Text'Length) & " bytes"); - - declare - Compressed_Data : Stream_Element_Array (1 .. Text'Length); - L : Stream_Element_Offset; - begin - Compress : declare - Compressor : Filter_Type; - I : Stream_Element_Offset; - begin - Deflate_Init (Compressor); - - -- Compress the whole of T at once. - - Translate (Compressor, Source, I, Compressed_Data, L, Finish); - pragma Assert (I = Source'Last); - - Close (Compressor); - - Ada.Text_IO.Put_Line - ("Compressed size : " - & Stream_Element_Offset'Image (L) & " bytes"); - end Compress; - - -- Now we decompress the data, passing short blocks of data to Zlib - -- (because this demonstrates the problem - the last block passed will - -- contain checksum information and there will be no output, only a - -- check inside Zlib that the checksum is correct). - - Decompress : declare - Decompressor : Filter_Type; - - Uncompressed_Data : Stream_Element_Array (1 .. Text'Length); - - Block_Size : constant := 4; - -- This makes sure that the last block contains - -- only Adler checksum data. - - P : Stream_Element_Offset := Compressed_Data'First - 1; - O : Stream_Element_Offset; - begin - Inflate_Init (Decompressor); - - loop - Translate - (Decompressor, - Compressed_Data - (P + 1 .. Stream_Element_Offset'Min (P + Block_Size, L)), - P, - Uncompressed_Data - (Total_Out (Decompressor) + 1 .. Uncompressed_Data'Last), - O, - No_Flush); - - Ada.Text_IO.Put_Line - ("Total in : " & Count'Image (Total_In (Decompressor)) & - ", out : " & Count'Image (Total_Out (Decompressor))); - - exit when P = L; - end loop; - - Ada.Text_IO.New_Line; - Ada.Text_IO.Put_Line - ("Decompressed text matches original text : " - & Boolean'Image (Uncompressed_Data = Source)); - end Decompress; - end; -end Buffer_Demo; diff --git a/deps/zlib/contrib/ada/mtest.adb b/deps/zlib/contrib/ada/mtest.adb deleted file mode 100644 index c4dfd080f0c0a4..00000000000000 --- a/deps/zlib/contrib/ada/mtest.adb +++ /dev/null @@ -1,156 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- --- Continuous test for ZLib multithreading. If the test would fail --- we should provide thread safe allocation routines for the Z_Stream. --- --- $Id: mtest.adb,v 1.4 2004/07/23 07:49:54 vagul Exp $ - -with ZLib; -with Ada.Streams; -with Ada.Numerics.Discrete_Random; -with Ada.Text_IO; -with Ada.Exceptions; -with Ada.Task_Identification; - -procedure MTest is - use Ada.Streams; - use ZLib; - - Stop : Boolean := False; - - pragma Atomic (Stop); - - subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is - new Ada.Numerics.Discrete_Random (Visible_Symbols); - - task type Test_Task; - - task body Test_Task is - Buffer : Stream_Element_Array (1 .. 100_000); - Gen : Random_Elements.Generator; - - Buffer_First : Stream_Element_Offset; - Compare_First : Stream_Element_Offset; - - Deflate : Filter_Type; - Inflate : Filter_Type; - - procedure Further (Item : in Stream_Element_Array); - - procedure Read_Buffer - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - - ------------- - -- Further -- - ------------- - - procedure Further (Item : in Stream_Element_Array) is - - procedure Compare (Item : in Stream_Element_Array); - - ------------- - -- Compare -- - ------------- - - procedure Compare (Item : in Stream_Element_Array) is - Next_First : Stream_Element_Offset := Compare_First + Item'Length; - begin - if Buffer (Compare_First .. Next_First - 1) /= Item then - raise Program_Error; - end if; - - Compare_First := Next_First; - end Compare; - - procedure Compare_Write is new ZLib.Write (Write => Compare); - begin - Compare_Write (Inflate, Item, No_Flush); - end Further; - - ----------------- - -- Read_Buffer -- - ----------------- - - procedure Read_Buffer - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset) - is - Buff_Diff : Stream_Element_Offset := Buffer'Last - Buffer_First; - Next_First : Stream_Element_Offset; - begin - if Item'Length <= Buff_Diff then - Last := Item'Last; - - Next_First := Buffer_First + Item'Length; - - Item := Buffer (Buffer_First .. Next_First - 1); - - Buffer_First := Next_First; - else - Last := Item'First + Buff_Diff; - Item (Item'First .. Last) := Buffer (Buffer_First .. Buffer'Last); - Buffer_First := Buffer'Last + 1; - end if; - end Read_Buffer; - - procedure Translate is new Generic_Translate - (Data_In => Read_Buffer, - Data_Out => Further); - - begin - Random_Elements.Reset (Gen); - - Buffer := (others => 20); - - Main : loop - for J in Buffer'Range loop - Buffer (J) := Random_Elements.Random (Gen); - - Deflate_Init (Deflate); - Inflate_Init (Inflate); - - Buffer_First := Buffer'First; - Compare_First := Buffer'First; - - Translate (Deflate); - - if Compare_First /= Buffer'Last + 1 then - raise Program_Error; - end if; - - Ada.Text_IO.Put_Line - (Ada.Task_Identification.Image - (Ada.Task_Identification.Current_Task) - & Stream_Element_Offset'Image (J) - & ZLib.Count'Image (Total_Out (Deflate))); - - Close (Deflate); - Close (Inflate); - - exit Main when Stop; - end loop; - end loop Main; - exception - when E : others => - Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E)); - Stop := True; - end Test_Task; - - Test : array (1 .. 4) of Test_Task; - - pragma Unreferenced (Test); - - Dummy : Character; - -begin - Ada.Text_IO.Get_Immediate (Dummy); - Stop := True; -end MTest; diff --git a/deps/zlib/contrib/ada/read.adb b/deps/zlib/contrib/ada/read.adb deleted file mode 100644 index 1f2efbfeb80287..00000000000000 --- a/deps/zlib/contrib/ada/read.adb +++ /dev/null @@ -1,156 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: read.adb,v 1.8 2004/05/31 10:53:40 vagul Exp $ - --- Test/demo program for the generic read interface. - -with Ada.Numerics.Discrete_Random; -with Ada.Streams; -with Ada.Text_IO; - -with ZLib; - -procedure Read is - - use Ada.Streams; - - ------------------------------------ - -- Test configuration parameters -- - ------------------------------------ - - File_Size : Stream_Element_Offset := 100_000; - - Continuous : constant Boolean := False; - -- If this constant is True, the test would be repeated again and again, - -- with increment File_Size for every iteration. - - Header : constant ZLib.Header_Type := ZLib.Default; - -- Do not use Header other than Default in ZLib versions 1.1.4 and older. - - Init_Random : constant := 8; - -- We are using the same random sequence, in case of we catch bug, - -- so we would be able to reproduce it. - - -- End -- - - Pack_Size : Stream_Element_Offset; - Offset : Stream_Element_Offset; - - Filter : ZLib.Filter_Type; - - subtype Visible_Symbols - is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is new - Ada.Numerics.Discrete_Random (Visible_Symbols); - - Gen : Random_Elements.Generator; - Period : constant Stream_Element_Offset := 200; - -- Period constant variable for random generator not to be very random. - -- Bigger period, harder random. - - Read_Buffer : Stream_Element_Array (1 .. 2048); - Read_First : Stream_Element_Offset; - Read_Last : Stream_Element_Offset; - - procedure Reset; - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - -- this procedure is for generic instantiation of - -- ZLib.Read - -- reading data from the File_In. - - procedure Read is new ZLib.Read - (Read, - Read_Buffer, - Rest_First => Read_First, - Rest_Last => Read_Last); - - ---------- - -- Read -- - ---------- - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Last := Stream_Element_Offset'Min - (Item'Last, - Item'First + File_Size - Offset); - - for J in Item'First .. Last loop - if J < Item'First + Period then - Item (J) := Random_Elements.Random (Gen); - else - Item (J) := Item (J - Period); - end if; - - Offset := Offset + 1; - end loop; - end Read; - - ----------- - -- Reset -- - ----------- - - procedure Reset is - begin - Random_Elements.Reset (Gen, Init_Random); - Pack_Size := 0; - Offset := 1; - Read_First := Read_Buffer'Last + 1; - Read_Last := Read_Buffer'Last; - end Reset; - -begin - Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); - - loop - for Level in ZLib.Compression_Level'Range loop - - Ada.Text_IO.Put ("Level =" - & ZLib.Compression_Level'Image (Level)); - - -- Deflate using generic instantiation. - - ZLib.Deflate_Init - (Filter, - Level, - Header => Header); - - Reset; - - Ada.Text_IO.Put - (Stream_Element_Offset'Image (File_Size) & " ->"); - - loop - declare - Buffer : Stream_Element_Array (1 .. 1024); - Last : Stream_Element_Offset; - begin - Read (Filter, Buffer, Last); - - Pack_Size := Pack_Size + Last - Buffer'First + 1; - - exit when Last < Buffer'Last; - end; - end loop; - - Ada.Text_IO.Put_Line (Stream_Element_Offset'Image (Pack_Size)); - - ZLib.Close (Filter); - end loop; - - exit when not Continuous; - - File_Size := File_Size + 1; - end loop; -end Read; diff --git a/deps/zlib/contrib/ada/readme.txt b/deps/zlib/contrib/ada/readme.txt deleted file mode 100644 index ce4d2cadf0d928..00000000000000 --- a/deps/zlib/contrib/ada/readme.txt +++ /dev/null @@ -1,65 +0,0 @@ - ZLib for Ada thick binding (ZLib.Ada) - Release 1.3 - -ZLib.Ada is a thick binding interface to the popular ZLib data -compression library, available at http://www.gzip.org/zlib/. -It provides Ada-style access to the ZLib C library. - - - Here are the main changes since ZLib.Ada 1.2: - -- Attension: ZLib.Read generic routine have a initialization requirement - for Read_Last parameter now. It is a bit incompartible with previous version, - but extends functionality, we could use new parameters Allow_Read_Some and - Flush now. - -- Added Is_Open routines to ZLib and ZLib.Streams packages. - -- Add pragma Assert to check Stream_Element is 8 bit. - -- Fix extraction to buffer with exact known decompressed size. Error reported by - Steve Sangwine. - -- Fix definition of ULong (changed to unsigned_long), fix regression on 64 bits - computers. Patch provided by Pascal Obry. - -- Add Status_Error exception definition. - -- Add pragma Assertion that Ada.Streams.Stream_Element size is 8 bit. - - - How to build ZLib.Ada under GNAT - -You should have the ZLib library already build on your computer, before -building ZLib.Ada. Make the directory of ZLib.Ada sources current and -issue the command: - - gnatmake test -largs -L -lz - -Or use the GNAT project file build for GNAT 3.15 or later: - - gnatmake -Pzlib.gpr -L - - - How to build ZLib.Ada under Aonix ObjectAda for Win32 7.2.2 - -1. Make a project with all *.ads and *.adb files from the distribution. -2. Build the libz.a library from the ZLib C sources. -3. Rename libz.a to z.lib. -4. Add the library z.lib to the project. -5. Add the libc.lib library from the ObjectAda distribution to the project. -6. Build the executable using test.adb as a main procedure. - - - How to use ZLib.Ada - -The source files test.adb and read.adb are small demo programs that show -the main functionality of ZLib.Ada. - -The routines from the package specifications are commented. - - -Homepage: http://zlib-ada.sourceforge.net/ -Author: Dmitriy Anisimkov - -Contributors: Pascal Obry , Steve Sangwine diff --git a/deps/zlib/contrib/ada/test.adb b/deps/zlib/contrib/ada/test.adb deleted file mode 100644 index 90773acfa18669..00000000000000 --- a/deps/zlib/contrib/ada/test.adb +++ /dev/null @@ -1,463 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: test.adb,v 1.17 2003/08/12 12:13:30 vagul Exp $ - --- The program has a few aims. --- 1. Test ZLib.Ada95 thick binding functionality. --- 2. Show the example of use main functionality of the ZLib.Ada95 binding. --- 3. Build this program automatically compile all ZLib.Ada95 packages under --- GNAT Ada95 compiler. - -with ZLib.Streams; -with Ada.Streams.Stream_IO; -with Ada.Numerics.Discrete_Random; - -with Ada.Text_IO; - -with Ada.Calendar; - -procedure Test is - - use Ada.Streams; - use Stream_IO; - - ------------------------------------ - -- Test configuration parameters -- - ------------------------------------ - - File_Size : Count := 100_000; - Continuous : constant Boolean := False; - - Header : constant ZLib.Header_Type := ZLib.Default; - -- ZLib.None; - -- ZLib.Auto; - -- ZLib.GZip; - -- Do not use Header other then Default in ZLib versions 1.1.4 - -- and older. - - Strategy : constant ZLib.Strategy_Type := ZLib.Default_Strategy; - Init_Random : constant := 10; - - -- End -- - - In_File_Name : constant String := "testzlib.in"; - -- Name of the input file - - Z_File_Name : constant String := "testzlib.zlb"; - -- Name of the compressed file. - - Out_File_Name : constant String := "testzlib.out"; - -- Name of the decompressed file. - - File_In : File_Type; - File_Out : File_Type; - File_Back : File_Type; - File_Z : ZLib.Streams.Stream_Type; - - Filter : ZLib.Filter_Type; - - Time_Stamp : Ada.Calendar.Time; - - procedure Generate_File; - -- Generate file of spetsified size with some random data. - -- The random data is repeatable, for the good compression. - - procedure Compare_Streams - (Left, Right : in out Root_Stream_Type'Class); - -- The procedure compearing data in 2 streams. - -- It is for compare data before and after compression/decompression. - - procedure Compare_Files (Left, Right : String); - -- Compare files. Based on the Compare_Streams. - - procedure Copy_Streams - (Source, Target : in out Root_Stream_Type'Class; - Buffer_Size : in Stream_Element_Offset := 1024); - -- Copying data from one stream to another. It is for test stream - -- interface of the library. - - procedure Data_In - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - -- this procedure is for generic instantiation of - -- ZLib.Generic_Translate. - -- reading data from the File_In. - - procedure Data_Out (Item : in Stream_Element_Array); - -- this procedure is for generic instantiation of - -- ZLib.Generic_Translate. - -- writing data to the File_Out. - - procedure Stamp; - -- Store the timestamp to the local variable. - - procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count); - -- Print the time statistic with the message. - - procedure Translate is new ZLib.Generic_Translate - (Data_In => Data_In, - Data_Out => Data_Out); - -- This procedure is moving data from File_In to File_Out - -- with compression or decompression, depend on initialization of - -- Filter parameter. - - ------------------- - -- Compare_Files -- - ------------------- - - procedure Compare_Files (Left, Right : String) is - Left_File, Right_File : File_Type; - begin - Open (Left_File, In_File, Left); - Open (Right_File, In_File, Right); - Compare_Streams (Stream (Left_File).all, Stream (Right_File).all); - Close (Left_File); - Close (Right_File); - end Compare_Files; - - --------------------- - -- Compare_Streams -- - --------------------- - - procedure Compare_Streams - (Left, Right : in out Ada.Streams.Root_Stream_Type'Class) - is - Left_Buffer, Right_Buffer : Stream_Element_Array (0 .. 16#FFF#); - Left_Last, Right_Last : Stream_Element_Offset; - begin - loop - Read (Left, Left_Buffer, Left_Last); - Read (Right, Right_Buffer, Right_Last); - - if Left_Last /= Right_Last then - Ada.Text_IO.Put_Line ("Compare error :" - & Stream_Element_Offset'Image (Left_Last) - & " /= " - & Stream_Element_Offset'Image (Right_Last)); - - raise Constraint_Error; - - elsif Left_Buffer (0 .. Left_Last) - /= Right_Buffer (0 .. Right_Last) - then - Ada.Text_IO.Put_Line ("ERROR: IN and OUT files is not equal."); - raise Constraint_Error; - - end if; - - exit when Left_Last < Left_Buffer'Last; - end loop; - end Compare_Streams; - - ------------------ - -- Copy_Streams -- - ------------------ - - procedure Copy_Streams - (Source, Target : in out Ada.Streams.Root_Stream_Type'Class; - Buffer_Size : in Stream_Element_Offset := 1024) - is - Buffer : Stream_Element_Array (1 .. Buffer_Size); - Last : Stream_Element_Offset; - begin - loop - Read (Source, Buffer, Last); - Write (Target, Buffer (1 .. Last)); - - exit when Last < Buffer'Last; - end loop; - end Copy_Streams; - - ------------- - -- Data_In -- - ------------- - - procedure Data_In - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Read (File_In, Item, Last); - end Data_In; - - -------------- - -- Data_Out -- - -------------- - - procedure Data_Out (Item : in Stream_Element_Array) is - begin - Write (File_Out, Item); - end Data_Out; - - ------------------- - -- Generate_File -- - ------------------- - - procedure Generate_File is - subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is - new Ada.Numerics.Discrete_Random (Visible_Symbols); - - Gen : Random_Elements.Generator; - Buffer : Stream_Element_Array := (1 .. 77 => 16#20#) & 10; - - Buffer_Count : constant Count := File_Size / Buffer'Length; - -- Number of same buffers in the packet. - - Density : constant Count := 30; -- from 0 to Buffer'Length - 2; - - procedure Fill_Buffer (J, D : in Count); - -- Change the part of the buffer. - - ----------------- - -- Fill_Buffer -- - ----------------- - - procedure Fill_Buffer (J, D : in Count) is - begin - for K in 0 .. D loop - Buffer - (Stream_Element_Offset ((J + K) mod (Buffer'Length - 1) + 1)) - := Random_Elements.Random (Gen); - - end loop; - end Fill_Buffer; - - begin - Random_Elements.Reset (Gen, Init_Random); - - Create (File_In, Out_File, In_File_Name); - - Fill_Buffer (1, Buffer'Length - 2); - - for J in 1 .. Buffer_Count loop - Write (File_In, Buffer); - - Fill_Buffer (J, Density); - end loop; - - -- fill remain size. - - Write - (File_In, - Buffer - (1 .. Stream_Element_Offset - (File_Size - Buffer'Length * Buffer_Count))); - - Flush (File_In); - Close (File_In); - end Generate_File; - - --------------------- - -- Print_Statistic -- - --------------------- - - procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count) is - use Ada.Calendar; - use Ada.Text_IO; - - package Count_IO is new Integer_IO (ZLib.Count); - - Curr_Dur : Duration := Clock - Time_Stamp; - begin - Put (Msg); - - Set_Col (20); - Ada.Text_IO.Put ("size ="); - - Count_IO.Put - (Data_Size, - Width => Stream_IO.Count'Image (File_Size)'Length); - - Put_Line (" duration =" & Duration'Image (Curr_Dur)); - end Print_Statistic; - - ----------- - -- Stamp -- - ----------- - - procedure Stamp is - begin - Time_Stamp := Ada.Calendar.Clock; - end Stamp; - -begin - Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); - - loop - Generate_File; - - for Level in ZLib.Compression_Level'Range loop - - Ada.Text_IO.Put_Line ("Level =" - & ZLib.Compression_Level'Image (Level)); - - -- Test generic interface. - Open (File_In, In_File, In_File_Name); - Create (File_Out, Out_File, Z_File_Name); - - Stamp; - - -- Deflate using generic instantiation. - - ZLib.Deflate_Init - (Filter => Filter, - Level => Level, - Strategy => Strategy, - Header => Header); - - Translate (Filter); - Print_Statistic ("Generic compress", ZLib.Total_Out (Filter)); - ZLib.Close (Filter); - - Close (File_In); - Close (File_Out); - - Open (File_In, In_File, Z_File_Name); - Create (File_Out, Out_File, Out_File_Name); - - Stamp; - - -- Inflate using generic instantiation. - - ZLib.Inflate_Init (Filter, Header => Header); - - Translate (Filter); - Print_Statistic ("Generic decompress", ZLib.Total_Out (Filter)); - - ZLib.Close (Filter); - - Close (File_In); - Close (File_Out); - - Compare_Files (In_File_Name, Out_File_Name); - - -- Test stream interface. - - -- Compress to the back stream. - - Open (File_In, In_File, In_File_Name); - Create (File_Back, Out_File, Z_File_Name); - - Stamp; - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.Out_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => True, - Level => Level, - Strategy => Strategy, - Header => Header); - - Copy_Streams - (Source => Stream (File_In).all, - Target => File_Z); - - -- Flushing internal buffers to the back stream. - - ZLib.Streams.Flush (File_Z, ZLib.Finish); - - Print_Statistic ("Write compress", - ZLib.Streams.Write_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - - Close (File_In); - Close (File_Back); - - -- Compare reading from original file and from - -- decompression stream. - - Open (File_In, In_File, In_File_Name); - Open (File_Back, In_File, Z_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.In_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => True, - Header => Header); - - Stamp; - Compare_Streams (Stream (File_In).all, File_Z); - - Print_Statistic ("Read decompress", - ZLib.Streams.Read_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - Close (File_In); - Close (File_Back); - - -- Compress by reading from compression stream. - - Open (File_Back, In_File, In_File_Name); - Create (File_Out, Out_File, Z_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.In_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => False, - Level => Level, - Strategy => Strategy, - Header => Header); - - Stamp; - Copy_Streams - (Source => File_Z, - Target => Stream (File_Out).all); - - Print_Statistic ("Read compress", - ZLib.Streams.Read_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - - Close (File_Out); - Close (File_Back); - - -- Decompress to decompression stream. - - Open (File_In, In_File, Z_File_Name); - Create (File_Back, Out_File, Out_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.Out_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => False, - Header => Header); - - Stamp; - - Copy_Streams - (Source => Stream (File_In).all, - Target => File_Z); - - Print_Statistic ("Write decompress", - ZLib.Streams.Write_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - Close (File_In); - Close (File_Back); - - Compare_Files (In_File_Name, Out_File_Name); - end loop; - - Ada.Text_IO.Put_Line (Count'Image (File_Size) & " Ok."); - - exit when not Continuous; - - File_Size := File_Size + 1; - end loop; -end Test; diff --git a/deps/zlib/contrib/ada/zlib-streams.adb b/deps/zlib/contrib/ada/zlib-streams.adb deleted file mode 100644 index b6497bae286e50..00000000000000 --- a/deps/zlib/contrib/ada/zlib-streams.adb +++ /dev/null @@ -1,225 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-streams.adb,v 1.10 2004/05/31 10:53:40 vagul Exp $ - -with Ada.Unchecked_Deallocation; - -package body ZLib.Streams is - - ----------- - -- Close -- - ----------- - - procedure Close (Stream : in out Stream_Type) is - procedure Free is new Ada.Unchecked_Deallocation - (Stream_Element_Array, Buffer_Access); - begin - if Stream.Mode = Out_Stream or Stream.Mode = Duplex then - -- We should flush the data written by the writer. - - Flush (Stream, Finish); - - Close (Stream.Writer); - end if; - - if Stream.Mode = In_Stream or Stream.Mode = Duplex then - Close (Stream.Reader); - Free (Stream.Buffer); - end if; - end Close; - - ------------ - -- Create -- - ------------ - - procedure Create - (Stream : out Stream_Type; - Mode : in Stream_Mode; - Back : in Stream_Access; - Back_Compressed : in Boolean; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Header : in Header_Type := Default; - Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size) - is - - subtype Buffer_Subtype is Stream_Element_Array (1 .. Read_Buffer_Size); - - procedure Init_Filter - (Filter : in out Filter_Type; - Compress : in Boolean); - - ----------------- - -- Init_Filter -- - ----------------- - - procedure Init_Filter - (Filter : in out Filter_Type; - Compress : in Boolean) is - begin - if Compress then - Deflate_Init - (Filter, Level, Strategy, Header => Header); - else - Inflate_Init (Filter, Header => Header); - end if; - end Init_Filter; - - begin - Stream.Back := Back; - Stream.Mode := Mode; - - if Mode = Out_Stream or Mode = Duplex then - Init_Filter (Stream.Writer, Back_Compressed); - Stream.Buffer_Size := Write_Buffer_Size; - else - Stream.Buffer_Size := 0; - end if; - - if Mode = In_Stream or Mode = Duplex then - Init_Filter (Stream.Reader, not Back_Compressed); - - Stream.Buffer := new Buffer_Subtype; - Stream.Rest_First := Stream.Buffer'Last + 1; - Stream.Rest_Last := Stream.Buffer'Last; - end if; - end Create; - - ----------- - -- Flush -- - ----------- - - procedure Flush - (Stream : in out Stream_Type; - Mode : in Flush_Mode := Sync_Flush) - is - Buffer : Stream_Element_Array (1 .. Stream.Buffer_Size); - Last : Stream_Element_Offset; - begin - loop - Flush (Stream.Writer, Buffer, Last, Mode); - - Ada.Streams.Write (Stream.Back.all, Buffer (1 .. Last)); - - exit when Last < Buffer'Last; - end loop; - end Flush; - - ------------- - -- Is_Open -- - ------------- - - function Is_Open (Stream : Stream_Type) return Boolean is - begin - return Is_Open (Stream.Reader) or else Is_Open (Stream.Writer); - end Is_Open; - - ---------- - -- Read -- - ---------- - - procedure Read - (Stream : in out Stream_Type; - Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) - is - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - - ---------- - -- Read -- - ---------- - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Ada.Streams.Read (Stream.Back.all, Item, Last); - end Read; - - procedure Read is new ZLib.Read - (Read => Read, - Buffer => Stream.Buffer.all, - Rest_First => Stream.Rest_First, - Rest_Last => Stream.Rest_Last); - - begin - Read (Stream.Reader, Item, Last); - end Read; - - ------------------- - -- Read_Total_In -- - ------------------- - - function Read_Total_In (Stream : in Stream_Type) return Count is - begin - return Total_In (Stream.Reader); - end Read_Total_In; - - -------------------- - -- Read_Total_Out -- - -------------------- - - function Read_Total_Out (Stream : in Stream_Type) return Count is - begin - return Total_Out (Stream.Reader); - end Read_Total_Out; - - ----------- - -- Write -- - ----------- - - procedure Write - (Stream : in out Stream_Type; - Item : in Stream_Element_Array) - is - - procedure Write (Item : in Stream_Element_Array); - - ----------- - -- Write -- - ----------- - - procedure Write (Item : in Stream_Element_Array) is - begin - Ada.Streams.Write (Stream.Back.all, Item); - end Write; - - procedure Write is new ZLib.Write - (Write => Write, - Buffer_Size => Stream.Buffer_Size); - - begin - Write (Stream.Writer, Item, No_Flush); - end Write; - - -------------------- - -- Write_Total_In -- - -------------------- - - function Write_Total_In (Stream : in Stream_Type) return Count is - begin - return Total_In (Stream.Writer); - end Write_Total_In; - - --------------------- - -- Write_Total_Out -- - --------------------- - - function Write_Total_Out (Stream : in Stream_Type) return Count is - begin - return Total_Out (Stream.Writer); - end Write_Total_Out; - -end ZLib.Streams; diff --git a/deps/zlib/contrib/ada/zlib-streams.ads b/deps/zlib/contrib/ada/zlib-streams.ads deleted file mode 100644 index 8e26cd450838c6..00000000000000 --- a/deps/zlib/contrib/ada/zlib-streams.ads +++ /dev/null @@ -1,114 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-streams.ads,v 1.12 2004/05/31 10:53:40 vagul Exp $ - -package ZLib.Streams is - - type Stream_Mode is (In_Stream, Out_Stream, Duplex); - - type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class; - - type Stream_Type is - new Ada.Streams.Root_Stream_Type with private; - - procedure Read - (Stream : in out Stream_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - - procedure Write - (Stream : in out Stream_Type; - Item : in Ada.Streams.Stream_Element_Array); - - procedure Flush - (Stream : in out Stream_Type; - Mode : in Flush_Mode := Sync_Flush); - -- Flush the written data to the back stream, - -- all data placed to the compressor is flushing to the Back stream. - -- Should not be used until necessary, because it is decreasing - -- compression. - - function Read_Total_In (Stream : in Stream_Type) return Count; - pragma Inline (Read_Total_In); - -- Return total number of bytes read from back stream so far. - - function Read_Total_Out (Stream : in Stream_Type) return Count; - pragma Inline (Read_Total_Out); - -- Return total number of bytes read so far. - - function Write_Total_In (Stream : in Stream_Type) return Count; - pragma Inline (Write_Total_In); - -- Return total number of bytes written so far. - - function Write_Total_Out (Stream : in Stream_Type) return Count; - pragma Inline (Write_Total_Out); - -- Return total number of bytes written to the back stream. - - procedure Create - (Stream : out Stream_Type; - Mode : in Stream_Mode; - Back : in Stream_Access; - Back_Compressed : in Boolean; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Header : in Header_Type := Default; - Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size); - -- Create the Comression/Decompression stream. - -- If mode is In_Stream then Write operation is disabled. - -- If mode is Out_Stream then Read operation is disabled. - - -- If Back_Compressed is true then - -- Data written to the Stream is compressing to the Back stream - -- and data read from the Stream is decompressed data from the Back stream. - - -- If Back_Compressed is false then - -- Data written to the Stream is decompressing to the Back stream - -- and data read from the Stream is compressed data from the Back stream. - - -- !!! When the Need_Header is False ZLib-Ada is using undocumented - -- ZLib 1.1.4 functionality to do not create/wait for ZLib headers. - - function Is_Open (Stream : Stream_Type) return Boolean; - - procedure Close (Stream : in out Stream_Type); - -private - - use Ada.Streams; - - type Buffer_Access is access all Stream_Element_Array; - - type Stream_Type - is new Root_Stream_Type with - record - Mode : Stream_Mode; - - Buffer : Buffer_Access; - Rest_First : Stream_Element_Offset; - Rest_Last : Stream_Element_Offset; - -- Buffer for Read operation. - -- We need to have this buffer in the record - -- because not all read data from back stream - -- could be processed during the read operation. - - Buffer_Size : Stream_Element_Offset; - -- Buffer size for write operation. - -- We do not need to have this buffer - -- in the record because all data could be - -- processed in the write operation. - - Back : Stream_Access; - Reader : Filter_Type; - Writer : Filter_Type; - end record; - -end ZLib.Streams; diff --git a/deps/zlib/contrib/ada/zlib-thin.adb b/deps/zlib/contrib/ada/zlib-thin.adb deleted file mode 100644 index 0ca4a712046af8..00000000000000 --- a/deps/zlib/contrib/ada/zlib-thin.adb +++ /dev/null @@ -1,141 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-thin.adb,v 1.8 2003/12/14 18:27:31 vagul Exp $ - -package body ZLib.Thin is - - ZLIB_VERSION : constant Chars_Ptr := zlibVersion; - - Z_Stream_Size : constant Int := Z_Stream'Size / System.Storage_Unit; - - -------------- - -- Avail_In -- - -------------- - - function Avail_In (Strm : in Z_Stream) return UInt is - begin - return Strm.Avail_In; - end Avail_In; - - --------------- - -- Avail_Out -- - --------------- - - function Avail_Out (Strm : in Z_Stream) return UInt is - begin - return Strm.Avail_Out; - end Avail_Out; - - ------------------ - -- Deflate_Init -- - ------------------ - - function Deflate_Init - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int) - return Int is - begin - return deflateInit2 - (strm, - level, - method, - windowBits, - memLevel, - strategy, - ZLIB_VERSION, - Z_Stream_Size); - end Deflate_Init; - - ------------------ - -- Inflate_Init -- - ------------------ - - function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int is - begin - return inflateInit2 (strm, windowBits, ZLIB_VERSION, Z_Stream_Size); - end Inflate_Init; - - ------------------------ - -- Last_Error_Message -- - ------------------------ - - function Last_Error_Message (Strm : in Z_Stream) return String is - use Interfaces.C.Strings; - begin - if Strm.msg = Null_Ptr then - return ""; - else - return Value (Strm.msg); - end if; - end Last_Error_Message; - - ------------ - -- Set_In -- - ------------ - - procedure Set_In - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt) is - begin - Strm.Next_In := Buffer; - Strm.Avail_In := Size; - end Set_In; - - ------------------ - -- Set_Mem_Func -- - ------------------ - - procedure Set_Mem_Func - (Strm : in out Z_Stream; - Opaque : in Voidp; - Alloc : in alloc_func; - Free : in free_func) is - begin - Strm.opaque := Opaque; - Strm.zalloc := Alloc; - Strm.zfree := Free; - end Set_Mem_Func; - - ------------- - -- Set_Out -- - ------------- - - procedure Set_Out - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt) is - begin - Strm.Next_Out := Buffer; - Strm.Avail_Out := Size; - end Set_Out; - - -------------- - -- Total_In -- - -------------- - - function Total_In (Strm : in Z_Stream) return ULong is - begin - return Strm.Total_In; - end Total_In; - - --------------- - -- Total_Out -- - --------------- - - function Total_Out (Strm : in Z_Stream) return ULong is - begin - return Strm.Total_Out; - end Total_Out; - -end ZLib.Thin; diff --git a/deps/zlib/contrib/ada/zlib-thin.ads b/deps/zlib/contrib/ada/zlib-thin.ads deleted file mode 100644 index 810173cff86fa6..00000000000000 --- a/deps/zlib/contrib/ada/zlib-thin.ads +++ /dev/null @@ -1,450 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-thin.ads,v 1.11 2004/07/23 06:33:11 vagul Exp $ - -with Interfaces.C.Strings; - -with System; - -private package ZLib.Thin is - - -- From zconf.h - - MAX_MEM_LEVEL : constant := 9; -- zconf.h:105 - -- zconf.h:105 - MAX_WBITS : constant := 15; -- zconf.h:115 - -- 32K LZ77 window - -- zconf.h:115 - SEEK_SET : constant := 8#0000#; -- zconf.h:244 - -- Seek from beginning of file. - -- zconf.h:244 - SEEK_CUR : constant := 1; -- zconf.h:245 - -- Seek from current position. - -- zconf.h:245 - SEEK_END : constant := 2; -- zconf.h:246 - -- Set file pointer to EOF plus "offset" - -- zconf.h:246 - - type Byte is new Interfaces.C.unsigned_char; -- 8 bits - -- zconf.h:214 - type UInt is new Interfaces.C.unsigned; -- 16 bits or more - -- zconf.h:216 - type Int is new Interfaces.C.int; - - type ULong is new Interfaces.C.unsigned_long; -- 32 bits or more - -- zconf.h:217 - subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; - - type ULong_Access is access ULong; - type Int_Access is access Int; - - subtype Voidp is System.Address; -- zconf.h:232 - - subtype Byte_Access is Voidp; - - Nul : constant Voidp := System.Null_Address; - -- end from zconf - - Z_NO_FLUSH : constant := 8#0000#; -- zlib.h:125 - -- zlib.h:125 - Z_PARTIAL_FLUSH : constant := 1; -- zlib.h:126 - -- will be removed, use - -- Z_SYNC_FLUSH instead - -- zlib.h:126 - Z_SYNC_FLUSH : constant := 2; -- zlib.h:127 - -- zlib.h:127 - Z_FULL_FLUSH : constant := 3; -- zlib.h:128 - -- zlib.h:128 - Z_FINISH : constant := 4; -- zlib.h:129 - -- zlib.h:129 - Z_OK : constant := 8#0000#; -- zlib.h:132 - -- zlib.h:132 - Z_STREAM_END : constant := 1; -- zlib.h:133 - -- zlib.h:133 - Z_NEED_DICT : constant := 2; -- zlib.h:134 - -- zlib.h:134 - Z_ERRNO : constant := -1; -- zlib.h:135 - -- zlib.h:135 - Z_STREAM_ERROR : constant := -2; -- zlib.h:136 - -- zlib.h:136 - Z_DATA_ERROR : constant := -3; -- zlib.h:137 - -- zlib.h:137 - Z_MEM_ERROR : constant := -4; -- zlib.h:138 - -- zlib.h:138 - Z_BUF_ERROR : constant := -5; -- zlib.h:139 - -- zlib.h:139 - Z_VERSION_ERROR : constant := -6; -- zlib.h:140 - -- zlib.h:140 - Z_NO_COMPRESSION : constant := 8#0000#; -- zlib.h:145 - -- zlib.h:145 - Z_BEST_SPEED : constant := 1; -- zlib.h:146 - -- zlib.h:146 - Z_BEST_COMPRESSION : constant := 9; -- zlib.h:147 - -- zlib.h:147 - Z_DEFAULT_COMPRESSION : constant := -1; -- zlib.h:148 - -- zlib.h:148 - Z_FILTERED : constant := 1; -- zlib.h:151 - -- zlib.h:151 - Z_HUFFMAN_ONLY : constant := 2; -- zlib.h:152 - -- zlib.h:152 - Z_DEFAULT_STRATEGY : constant := 8#0000#; -- zlib.h:153 - -- zlib.h:153 - Z_BINARY : constant := 8#0000#; -- zlib.h:156 - -- zlib.h:156 - Z_ASCII : constant := 1; -- zlib.h:157 - -- zlib.h:157 - Z_UNKNOWN : constant := 2; -- zlib.h:158 - -- zlib.h:158 - Z_DEFLATED : constant := 8; -- zlib.h:161 - -- zlib.h:161 - Z_NULL : constant := 8#0000#; -- zlib.h:164 - -- for initializing zalloc, zfree, opaque - -- zlib.h:164 - type gzFile is new Voidp; -- zlib.h:646 - - type Z_Stream is private; - - type Z_Streamp is access all Z_Stream; -- zlib.h:89 - - type alloc_func is access function - (Opaque : Voidp; - Items : UInt; - Size : UInt) - return Voidp; -- zlib.h:63 - - type free_func is access procedure (opaque : Voidp; address : Voidp); - - function zlibVersion return Chars_Ptr; - - function Deflate (strm : Z_Streamp; flush : Int) return Int; - - function DeflateEnd (strm : Z_Streamp) return Int; - - function Inflate (strm : Z_Streamp; flush : Int) return Int; - - function InflateEnd (strm : Z_Streamp) return Int; - - function deflateSetDictionary - (strm : Z_Streamp; - dictionary : Byte_Access; - dictLength : UInt) - return Int; - - function deflateCopy (dest : Z_Streamp; source : Z_Streamp) return Int; - -- zlib.h:478 - - function deflateReset (strm : Z_Streamp) return Int; -- zlib.h:495 - - function deflateParams - (strm : Z_Streamp; - level : Int; - strategy : Int) - return Int; -- zlib.h:506 - - function inflateSetDictionary - (strm : Z_Streamp; - dictionary : Byte_Access; - dictLength : UInt) - return Int; -- zlib.h:548 - - function inflateSync (strm : Z_Streamp) return Int; -- zlib.h:565 - - function inflateReset (strm : Z_Streamp) return Int; -- zlib.h:580 - - function compress - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong) - return Int; -- zlib.h:601 - - function compress2 - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong; - level : Int) - return Int; -- zlib.h:615 - - function uncompress - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong) - return Int; - - function gzopen (path : Chars_Ptr; mode : Chars_Ptr) return gzFile; - - function gzdopen (fd : Int; mode : Chars_Ptr) return gzFile; - - function gzsetparams - (file : gzFile; - level : Int; - strategy : Int) - return Int; - - function gzread - (file : gzFile; - buf : Voidp; - len : UInt) - return Int; - - function gzwrite - (file : in gzFile; - buf : in Voidp; - len : in UInt) - return Int; - - function gzprintf (file : in gzFile; format : in Chars_Ptr) return Int; - - function gzputs (file : in gzFile; s : in Chars_Ptr) return Int; - - function gzgets - (file : gzFile; - buf : Chars_Ptr; - len : Int) - return Chars_Ptr; - - function gzputc (file : gzFile; char : Int) return Int; - - function gzgetc (file : gzFile) return Int; - - function gzflush (file : gzFile; flush : Int) return Int; - - function gzseek - (file : gzFile; - offset : Int; - whence : Int) - return Int; - - function gzrewind (file : gzFile) return Int; - - function gztell (file : gzFile) return Int; - - function gzeof (file : gzFile) return Int; - - function gzclose (file : gzFile) return Int; - - function gzerror (file : gzFile; errnum : Int_Access) return Chars_Ptr; - - function adler32 - (adler : ULong; - buf : Byte_Access; - len : UInt) - return ULong; - - function crc32 - (crc : ULong; - buf : Byte_Access; - len : UInt) - return ULong; - - function deflateInit - (strm : Z_Streamp; - level : Int; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function deflateInit2 - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function Deflate_Init - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int) - return Int; - pragma Inline (Deflate_Init); - - function inflateInit - (strm : Z_Streamp; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function inflateInit2 - (strm : in Z_Streamp; - windowBits : in Int; - version : in Chars_Ptr; - stream_size : in Int) - return Int; - - function inflateBackInit - (strm : in Z_Streamp; - windowBits : in Int; - window : in Byte_Access; - version : in Chars_Ptr; - stream_size : in Int) - return Int; - -- Size of window have to be 2**windowBits. - - function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int; - pragma Inline (Inflate_Init); - - function zError (err : Int) return Chars_Ptr; - - function inflateSyncPoint (z : Z_Streamp) return Int; - - function get_crc_table return ULong_Access; - - -- Interface to the available fields of the z_stream structure. - -- The application must update next_in and avail_in when avail_in has - -- dropped to zero. It must update next_out and avail_out when avail_out - -- has dropped to zero. The application must initialize zalloc, zfree and - -- opaque before calling the init function. - - procedure Set_In - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt); - pragma Inline (Set_In); - - procedure Set_Out - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt); - pragma Inline (Set_Out); - - procedure Set_Mem_Func - (Strm : in out Z_Stream; - Opaque : in Voidp; - Alloc : in alloc_func; - Free : in free_func); - pragma Inline (Set_Mem_Func); - - function Last_Error_Message (Strm : in Z_Stream) return String; - pragma Inline (Last_Error_Message); - - function Avail_Out (Strm : in Z_Stream) return UInt; - pragma Inline (Avail_Out); - - function Avail_In (Strm : in Z_Stream) return UInt; - pragma Inline (Avail_In); - - function Total_In (Strm : in Z_Stream) return ULong; - pragma Inline (Total_In); - - function Total_Out (Strm : in Z_Stream) return ULong; - pragma Inline (Total_Out); - - function inflateCopy - (dest : in Z_Streamp; - Source : in Z_Streamp) - return Int; - - function compressBound (Source_Len : in ULong) return ULong; - - function deflateBound - (Strm : in Z_Streamp; - Source_Len : in ULong) - return ULong; - - function gzungetc (C : in Int; File : in gzFile) return Int; - - function zlibCompileFlags return ULong; - -private - - type Z_Stream is record -- zlib.h:68 - Next_In : Voidp := Nul; -- next input byte - Avail_In : UInt := 0; -- number of bytes available at next_in - Total_In : ULong := 0; -- total nb of input bytes read so far - Next_Out : Voidp := Nul; -- next output byte should be put there - Avail_Out : UInt := 0; -- remaining free space at next_out - Total_Out : ULong := 0; -- total nb of bytes output so far - msg : Chars_Ptr; -- last error message, NULL if no error - state : Voidp; -- not visible by applications - zalloc : alloc_func := null; -- used to allocate the internal state - zfree : free_func := null; -- used to free the internal state - opaque : Voidp; -- private data object passed to - -- zalloc and zfree - data_type : Int; -- best guess about the data type: - -- ascii or binary - adler : ULong; -- adler32 value of the uncompressed - -- data - reserved : ULong; -- reserved for future use - end record; - - pragma Convention (C, Z_Stream); - - pragma Import (C, zlibVersion, "zlibVersion"); - pragma Import (C, Deflate, "deflate"); - pragma Import (C, DeflateEnd, "deflateEnd"); - pragma Import (C, Inflate, "inflate"); - pragma Import (C, InflateEnd, "inflateEnd"); - pragma Import (C, deflateSetDictionary, "deflateSetDictionary"); - pragma Import (C, deflateCopy, "deflateCopy"); - pragma Import (C, deflateReset, "deflateReset"); - pragma Import (C, deflateParams, "deflateParams"); - pragma Import (C, inflateSetDictionary, "inflateSetDictionary"); - pragma Import (C, inflateSync, "inflateSync"); - pragma Import (C, inflateReset, "inflateReset"); - pragma Import (C, compress, "compress"); - pragma Import (C, compress2, "compress2"); - pragma Import (C, uncompress, "uncompress"); - pragma Import (C, gzopen, "gzopen"); - pragma Import (C, gzdopen, "gzdopen"); - pragma Import (C, gzsetparams, "gzsetparams"); - pragma Import (C, gzread, "gzread"); - pragma Import (C, gzwrite, "gzwrite"); - pragma Import (C, gzprintf, "gzprintf"); - pragma Import (C, gzputs, "gzputs"); - pragma Import (C, gzgets, "gzgets"); - pragma Import (C, gzputc, "gzputc"); - pragma Import (C, gzgetc, "gzgetc"); - pragma Import (C, gzflush, "gzflush"); - pragma Import (C, gzseek, "gzseek"); - pragma Import (C, gzrewind, "gzrewind"); - pragma Import (C, gztell, "gztell"); - pragma Import (C, gzeof, "gzeof"); - pragma Import (C, gzclose, "gzclose"); - pragma Import (C, gzerror, "gzerror"); - pragma Import (C, adler32, "adler32"); - pragma Import (C, crc32, "crc32"); - pragma Import (C, deflateInit, "deflateInit_"); - pragma Import (C, inflateInit, "inflateInit_"); - pragma Import (C, deflateInit2, "deflateInit2_"); - pragma Import (C, inflateInit2, "inflateInit2_"); - pragma Import (C, zError, "zError"); - pragma Import (C, inflateSyncPoint, "inflateSyncPoint"); - pragma Import (C, get_crc_table, "get_crc_table"); - - -- since zlib 1.2.0: - - pragma Import (C, inflateCopy, "inflateCopy"); - pragma Import (C, compressBound, "compressBound"); - pragma Import (C, deflateBound, "deflateBound"); - pragma Import (C, gzungetc, "gzungetc"); - pragma Import (C, zlibCompileFlags, "zlibCompileFlags"); - - pragma Import (C, inflateBackInit, "inflateBackInit_"); - - -- I stopped binding the inflateBack routines, because realize that - -- it does not support zlib and gzip headers for now, and have no - -- symmetric deflateBack routines. - -- ZLib-Ada is symmetric regarding deflate/inflate data transformation - -- and has a similar generic callback interface for the - -- deflate/inflate transformation based on the regular Deflate/Inflate - -- routines. - - -- pragma Import (C, inflateBack, "inflateBack"); - -- pragma Import (C, inflateBackEnd, "inflateBackEnd"); - -end ZLib.Thin; diff --git a/deps/zlib/contrib/ada/zlib.adb b/deps/zlib/contrib/ada/zlib.adb deleted file mode 100644 index 8b6fd686ac77ec..00000000000000 --- a/deps/zlib/contrib/ada/zlib.adb +++ /dev/null @@ -1,701 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib.adb,v 1.31 2004/09/06 06:53:19 vagul Exp $ - -with Ada.Exceptions; -with Ada.Unchecked_Conversion; -with Ada.Unchecked_Deallocation; - -with Interfaces.C.Strings; - -with ZLib.Thin; - -package body ZLib is - - use type Thin.Int; - - type Z_Stream is new Thin.Z_Stream; - - type Return_Code_Enum is - (OK, - STREAM_END, - NEED_DICT, - ERRNO, - STREAM_ERROR, - DATA_ERROR, - MEM_ERROR, - BUF_ERROR, - VERSION_ERROR); - - type Flate_Step_Function is access - function (Strm : in Thin.Z_Streamp; Flush : in Thin.Int) return Thin.Int; - pragma Convention (C, Flate_Step_Function); - - type Flate_End_Function is access - function (Ctrm : in Thin.Z_Streamp) return Thin.Int; - pragma Convention (C, Flate_End_Function); - - type Flate_Type is record - Step : Flate_Step_Function; - Done : Flate_End_Function; - end record; - - subtype Footer_Array is Stream_Element_Array (1 .. 8); - - Simple_GZip_Header : constant Stream_Element_Array (1 .. 10) - := (16#1f#, 16#8b#, -- Magic header - 16#08#, -- Z_DEFLATED - 16#00#, -- Flags - 16#00#, 16#00#, 16#00#, 16#00#, -- Time - 16#00#, -- XFlags - 16#03# -- OS code - ); - -- The simplest gzip header is not for informational, but just for - -- gzip format compatibility. - -- Note that some code below is using assumption - -- Simple_GZip_Header'Last > Footer_Array'Last, so do not make - -- Simple_GZip_Header'Last <= Footer_Array'Last. - - Return_Code : constant array (Thin.Int range <>) of Return_Code_Enum - := (0 => OK, - 1 => STREAM_END, - 2 => NEED_DICT, - -1 => ERRNO, - -2 => STREAM_ERROR, - -3 => DATA_ERROR, - -4 => MEM_ERROR, - -5 => BUF_ERROR, - -6 => VERSION_ERROR); - - Flate : constant array (Boolean) of Flate_Type - := (True => (Step => Thin.Deflate'Access, - Done => Thin.DeflateEnd'Access), - False => (Step => Thin.Inflate'Access, - Done => Thin.InflateEnd'Access)); - - Flush_Finish : constant array (Boolean) of Flush_Mode - := (True => Finish, False => No_Flush); - - procedure Raise_Error (Stream : in Z_Stream); - pragma Inline (Raise_Error); - - procedure Raise_Error (Message : in String); - pragma Inline (Raise_Error); - - procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int); - - procedure Free is new Ada.Unchecked_Deallocation - (Z_Stream, Z_Stream_Access); - - function To_Thin_Access is new Ada.Unchecked_Conversion - (Z_Stream_Access, Thin.Z_Streamp); - - procedure Translate_GZip - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- Separate translate routine for make gzip header. - - procedure Translate_Auto - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- translate routine without additional headers. - - ----------------- - -- Check_Error -- - ----------------- - - procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int) is - use type Thin.Int; - begin - if Code /= Thin.Z_OK then - Raise_Error - (Return_Code_Enum'Image (Return_Code (Code)) - & ": " & Last_Error_Message (Stream)); - end if; - end Check_Error; - - ----------- - -- Close -- - ----------- - - procedure Close - (Filter : in out Filter_Type; - Ignore_Error : in Boolean := False) - is - Code : Thin.Int; - begin - if not Ignore_Error and then not Is_Open (Filter) then - raise Status_Error; - end if; - - Code := Flate (Filter.Compression).Done (To_Thin_Access (Filter.Strm)); - - if Ignore_Error or else Code = Thin.Z_OK then - Free (Filter.Strm); - else - declare - Error_Message : constant String - := Last_Error_Message (Filter.Strm.all); - begin - Free (Filter.Strm); - Ada.Exceptions.Raise_Exception - (ZLib_Error'Identity, - Return_Code_Enum'Image (Return_Code (Code)) - & ": " & Error_Message); - end; - end if; - end Close; - - ----------- - -- CRC32 -- - ----------- - - function CRC32 - (CRC : in Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) - return Unsigned_32 - is - use Thin; - begin - return Unsigned_32 (crc32 (ULong (CRC), - Data'Address, - Data'Length)); - end CRC32; - - procedure CRC32 - (CRC : in out Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) is - begin - CRC := CRC32 (CRC, Data); - end CRC32; - - ------------------ - -- Deflate_Init -- - ------------------ - - procedure Deflate_Init - (Filter : in out Filter_Type; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Method : in Compression_Method := Deflated; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Memory_Level : in Memory_Level_Type := Default_Memory_Level; - Header : in Header_Type := Default) - is - use type Thin.Int; - Win_Bits : Thin.Int := Thin.Int (Window_Bits); - begin - if Is_Open (Filter) then - raise Status_Error; - end if; - - -- We allow ZLib to make header only in case of default header type. - -- Otherwise we would either do header by ourselfs, or do not do - -- header at all. - - if Header = None or else Header = GZip then - Win_Bits := -Win_Bits; - end if; - - -- For the GZip CRC calculation and make headers. - - if Header = GZip then - Filter.CRC := 0; - Filter.Offset := Simple_GZip_Header'First; - else - Filter.Offset := Simple_GZip_Header'Last + 1; - end if; - - Filter.Strm := new Z_Stream; - Filter.Compression := True; - Filter.Stream_End := False; - Filter.Header := Header; - - if Thin.Deflate_Init - (To_Thin_Access (Filter.Strm), - Level => Thin.Int (Level), - method => Thin.Int (Method), - windowBits => Win_Bits, - memLevel => Thin.Int (Memory_Level), - strategy => Thin.Int (Strategy)) /= Thin.Z_OK - then - Raise_Error (Filter.Strm.all); - end if; - end Deflate_Init; - - ----------- - -- Flush -- - ----------- - - procedure Flush - (Filter : in out Filter_Type; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - No_Data : Stream_Element_Array := (1 .. 0 => 0); - Last : Stream_Element_Offset; - begin - Translate (Filter, No_Data, Last, Out_Data, Out_Last, Flush); - end Flush; - - ----------------------- - -- Generic_Translate -- - ----------------------- - - procedure Generic_Translate - (Filter : in out ZLib.Filter_Type; - In_Buffer_Size : in Integer := Default_Buffer_Size; - Out_Buffer_Size : in Integer := Default_Buffer_Size) - is - In_Buffer : Stream_Element_Array - (1 .. Stream_Element_Offset (In_Buffer_Size)); - Out_Buffer : Stream_Element_Array - (1 .. Stream_Element_Offset (Out_Buffer_Size)); - Last : Stream_Element_Offset; - In_Last : Stream_Element_Offset; - In_First : Stream_Element_Offset; - Out_Last : Stream_Element_Offset; - begin - Main : loop - Data_In (In_Buffer, Last); - - In_First := In_Buffer'First; - - loop - Translate - (Filter => Filter, - In_Data => In_Buffer (In_First .. Last), - In_Last => In_Last, - Out_Data => Out_Buffer, - Out_Last => Out_Last, - Flush => Flush_Finish (Last < In_Buffer'First)); - - if Out_Buffer'First <= Out_Last then - Data_Out (Out_Buffer (Out_Buffer'First .. Out_Last)); - end if; - - exit Main when Stream_End (Filter); - - -- The end of in buffer. - - exit when In_Last = Last; - - In_First := In_Last + 1; - end loop; - end loop Main; - - end Generic_Translate; - - ------------------ - -- Inflate_Init -- - ------------------ - - procedure Inflate_Init - (Filter : in out Filter_Type; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Header : in Header_Type := Default) - is - use type Thin.Int; - Win_Bits : Thin.Int := Thin.Int (Window_Bits); - - procedure Check_Version; - -- Check the latest header types compatibility. - - procedure Check_Version is - begin - if Version <= "1.1.4" then - Raise_Error - ("Inflate header type " & Header_Type'Image (Header) - & " incompatible with ZLib version " & Version); - end if; - end Check_Version; - - begin - if Is_Open (Filter) then - raise Status_Error; - end if; - - case Header is - when None => - Check_Version; - - -- Inflate data without headers determined - -- by negative Win_Bits. - - Win_Bits := -Win_Bits; - when GZip => - Check_Version; - - -- Inflate gzip data defined by flag 16. - - Win_Bits := Win_Bits + 16; - when Auto => - Check_Version; - - -- Inflate with automatic detection - -- of gzip or native header defined by flag 32. - - Win_Bits := Win_Bits + 32; - when Default => null; - end case; - - Filter.Strm := new Z_Stream; - Filter.Compression := False; - Filter.Stream_End := False; - Filter.Header := Header; - - if Thin.Inflate_Init - (To_Thin_Access (Filter.Strm), Win_Bits) /= Thin.Z_OK - then - Raise_Error (Filter.Strm.all); - end if; - end Inflate_Init; - - ------------- - -- Is_Open -- - ------------- - - function Is_Open (Filter : in Filter_Type) return Boolean is - begin - return Filter.Strm /= null; - end Is_Open; - - ----------------- - -- Raise_Error -- - ----------------- - - procedure Raise_Error (Message : in String) is - begin - Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Message); - end Raise_Error; - - procedure Raise_Error (Stream : in Z_Stream) is - begin - Raise_Error (Last_Error_Message (Stream)); - end Raise_Error; - - ---------- - -- Read -- - ---------- - - procedure Read - (Filter : in out Filter_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode := No_Flush) - is - In_Last : Stream_Element_Offset; - Item_First : Ada.Streams.Stream_Element_Offset := Item'First; - V_Flush : Flush_Mode := Flush; - - begin - pragma Assert (Rest_First in Buffer'First .. Buffer'Last + 1); - pragma Assert (Rest_Last in Buffer'First - 1 .. Buffer'Last); - - loop - if Rest_Last = Buffer'First - 1 then - V_Flush := Finish; - - elsif Rest_First > Rest_Last then - Read (Buffer, Rest_Last); - Rest_First := Buffer'First; - - if Rest_Last < Buffer'First then - V_Flush := Finish; - end if; - end if; - - Translate - (Filter => Filter, - In_Data => Buffer (Rest_First .. Rest_Last), - In_Last => In_Last, - Out_Data => Item (Item_First .. Item'Last), - Out_Last => Last, - Flush => V_Flush); - - Rest_First := In_Last + 1; - - exit when Stream_End (Filter) - or else Last = Item'Last - or else (Last >= Item'First and then Allow_Read_Some); - - Item_First := Last + 1; - end loop; - end Read; - - ---------------- - -- Stream_End -- - ---------------- - - function Stream_End (Filter : in Filter_Type) return Boolean is - begin - if Filter.Header = GZip and Filter.Compression then - return Filter.Stream_End - and then Filter.Offset = Footer_Array'Last + 1; - else - return Filter.Stream_End; - end if; - end Stream_End; - - -------------- - -- Total_In -- - -------------- - - function Total_In (Filter : in Filter_Type) return Count is - begin - return Count (Thin.Total_In (To_Thin_Access (Filter.Strm).all)); - end Total_In; - - --------------- - -- Total_Out -- - --------------- - - function Total_Out (Filter : in Filter_Type) return Count is - begin - return Count (Thin.Total_Out (To_Thin_Access (Filter.Strm).all)); - end Total_Out; - - --------------- - -- Translate -- - --------------- - - procedure Translate - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) is - begin - if Filter.Header = GZip and then Filter.Compression then - Translate_GZip - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data, - Out_Last => Out_Last, - Flush => Flush); - else - Translate_Auto - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data, - Out_Last => Out_Last, - Flush => Flush); - end if; - end Translate; - - -------------------- - -- Translate_Auto -- - -------------------- - - procedure Translate_Auto - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - use type Thin.Int; - Code : Thin.Int; - - begin - if not Is_Open (Filter) then - raise Status_Error; - end if; - - if Out_Data'Length = 0 and then In_Data'Length = 0 then - raise Constraint_Error; - end if; - - Set_Out (Filter.Strm.all, Out_Data'Address, Out_Data'Length); - Set_In (Filter.Strm.all, In_Data'Address, In_Data'Length); - - Code := Flate (Filter.Compression).Step - (To_Thin_Access (Filter.Strm), - Thin.Int (Flush)); - - if Code = Thin.Z_STREAM_END then - Filter.Stream_End := True; - else - Check_Error (Filter.Strm.all, Code); - end if; - - In_Last := In_Data'Last - - Stream_Element_Offset (Avail_In (Filter.Strm.all)); - Out_Last := Out_Data'Last - - Stream_Element_Offset (Avail_Out (Filter.Strm.all)); - end Translate_Auto; - - -------------------- - -- Translate_GZip -- - -------------------- - - procedure Translate_GZip - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - Out_First : Stream_Element_Offset; - - procedure Add_Data (Data : in Stream_Element_Array); - -- Add data to stream from the Filter.Offset till necessary, - -- used for add gzip headr/footer. - - procedure Put_32 - (Item : in out Stream_Element_Array; - Data : in Unsigned_32); - pragma Inline (Put_32); - - -------------- - -- Add_Data -- - -------------- - - procedure Add_Data (Data : in Stream_Element_Array) is - Data_First : Stream_Element_Offset renames Filter.Offset; - Data_Last : Stream_Element_Offset; - Data_Len : Stream_Element_Offset; -- -1 - Out_Len : Stream_Element_Offset; -- -1 - begin - Out_First := Out_Last + 1; - - if Data_First > Data'Last then - return; - end if; - - Data_Len := Data'Last - Data_First; - Out_Len := Out_Data'Last - Out_First; - - if Data_Len <= Out_Len then - Out_Last := Out_First + Data_Len; - Data_Last := Data'Last; - else - Out_Last := Out_Data'Last; - Data_Last := Data_First + Out_Len; - end if; - - Out_Data (Out_First .. Out_Last) := Data (Data_First .. Data_Last); - - Data_First := Data_Last + 1; - Out_First := Out_Last + 1; - end Add_Data; - - ------------ - -- Put_32 -- - ------------ - - procedure Put_32 - (Item : in out Stream_Element_Array; - Data : in Unsigned_32) - is - D : Unsigned_32 := Data; - begin - for J in Item'First .. Item'First + 3 loop - Item (J) := Stream_Element (D and 16#FF#); - D := Shift_Right (D, 8); - end loop; - end Put_32; - - begin - Out_Last := Out_Data'First - 1; - - if not Filter.Stream_End then - Add_Data (Simple_GZip_Header); - - Translate_Auto - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data (Out_First .. Out_Data'Last), - Out_Last => Out_Last, - Flush => Flush); - - CRC32 (Filter.CRC, In_Data (In_Data'First .. In_Last)); - end if; - - if Filter.Stream_End and then Out_Last <= Out_Data'Last then - -- This detection method would work only when - -- Simple_GZip_Header'Last > Footer_Array'Last - - if Filter.Offset = Simple_GZip_Header'Last + 1 then - Filter.Offset := Footer_Array'First; - end if; - - declare - Footer : Footer_Array; - begin - Put_32 (Footer, Filter.CRC); - Put_32 (Footer (Footer'First + 4 .. Footer'Last), - Unsigned_32 (Total_In (Filter))); - Add_Data (Footer); - end; - end if; - end Translate_GZip; - - ------------- - -- Version -- - ------------- - - function Version return String is - begin - return Interfaces.C.Strings.Value (Thin.zlibVersion); - end Version; - - ----------- - -- Write -- - ----------- - - procedure Write - (Filter : in out Filter_Type; - Item : in Ada.Streams.Stream_Element_Array; - Flush : in Flush_Mode := No_Flush) - is - Buffer : Stream_Element_Array (1 .. Buffer_Size); - In_Last : Stream_Element_Offset; - Out_Last : Stream_Element_Offset; - In_First : Stream_Element_Offset := Item'First; - begin - if Item'Length = 0 and Flush = No_Flush then - return; - end if; - - loop - Translate - (Filter => Filter, - In_Data => Item (In_First .. Item'Last), - In_Last => In_Last, - Out_Data => Buffer, - Out_Last => Out_Last, - Flush => Flush); - - if Out_Last >= Buffer'First then - Write (Buffer (1 .. Out_Last)); - end if; - - exit when In_Last = Item'Last or Stream_End (Filter); - - In_First := In_Last + 1; - end loop; - end Write; - -end ZLib; diff --git a/deps/zlib/contrib/ada/zlib.ads b/deps/zlib/contrib/ada/zlib.ads deleted file mode 100644 index 79ffc4095cf46f..00000000000000 --- a/deps/zlib/contrib/ada/zlib.ads +++ /dev/null @@ -1,328 +0,0 @@ ------------------------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- This library is free software; you can redistribute it and/or modify -- --- it under the terms of the GNU General Public License as published by -- --- the Free Software Foundation; either version 2 of the License, or (at -- --- your option) any later version. -- --- -- --- This library is distributed in the hope that it will be useful, but -- --- WITHOUT ANY WARRANTY; without even the implied warranty of -- --- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- --- General Public License for more details. -- --- -- --- You should have received a copy of the GNU General Public License -- --- along with this library; if not, write to the Free Software Foundation, -- --- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- --- -- --- As a special exception, if other files instantiate generics from this -- --- unit, or you link this unit with other files to produce an executable, -- --- this unit does not by itself cause the resulting executable to be -- --- covered by the GNU General Public License. This exception does not -- --- however invalidate any other reasons why the executable file might be -- --- covered by the GNU Public License. -- ------------------------------------------------------------------------------- - --- $Id: zlib.ads,v 1.26 2004/09/06 06:53:19 vagul Exp $ - -with Ada.Streams; - -with Interfaces; - -package ZLib is - - ZLib_Error : exception; - Status_Error : exception; - - type Compression_Level is new Integer range -1 .. 9; - - type Flush_Mode is private; - - type Compression_Method is private; - - type Window_Bits_Type is new Integer range 8 .. 15; - - type Memory_Level_Type is new Integer range 1 .. 9; - - type Unsigned_32 is new Interfaces.Unsigned_32; - - type Strategy_Type is private; - - type Header_Type is (None, Auto, Default, GZip); - -- Header type usage have a some limitation for inflate. - -- See comment for Inflate_Init. - - subtype Count is Ada.Streams.Stream_Element_Count; - - Default_Memory_Level : constant Memory_Level_Type := 8; - Default_Window_Bits : constant Window_Bits_Type := 15; - - ---------------------------------- - -- Compression method constants -- - ---------------------------------- - - Deflated : constant Compression_Method; - -- Only one method allowed in this ZLib version - - --------------------------------- - -- Compression level constants -- - --------------------------------- - - No_Compression : constant Compression_Level := 0; - Best_Speed : constant Compression_Level := 1; - Best_Compression : constant Compression_Level := 9; - Default_Compression : constant Compression_Level := -1; - - -------------------------- - -- Flush mode constants -- - -------------------------- - - No_Flush : constant Flush_Mode; - -- Regular way for compression, no flush - - Partial_Flush : constant Flush_Mode; - -- Will be removed, use Z_SYNC_FLUSH instead - - Sync_Flush : constant Flush_Mode; - -- All pending output is flushed to the output buffer and the output - -- is aligned on a byte boundary, so that the decompressor can get all - -- input data available so far. (In particular avail_in is zero after the - -- call if enough output space has been provided before the call.) - -- Flushing may degrade compression for some compression algorithms and so - -- it should be used only when necessary. - - Block_Flush : constant Flush_Mode; - -- Z_BLOCK requests that inflate() stop - -- if and when it get to the next deflate block boundary. When decoding the - -- zlib or gzip format, this will cause inflate() to return immediately - -- after the header and before the first block. When doing a raw inflate, - -- inflate() will go ahead and process the first block, and will return - -- when it gets to the end of that block, or when it runs out of data. - - Full_Flush : constant Flush_Mode; - -- All output is flushed as with SYNC_FLUSH, and the compression state - -- is reset so that decompression can restart from this point if previous - -- compressed data has been damaged or if random access is desired. Using - -- Full_Flush too often can seriously degrade the compression. - - Finish : constant Flush_Mode; - -- Just for tell the compressor that input data is complete. - - ------------------------------------ - -- Compression strategy constants -- - ------------------------------------ - - -- RLE stategy could be used only in version 1.2.0 and later. - - Filtered : constant Strategy_Type; - Huffman_Only : constant Strategy_Type; - RLE : constant Strategy_Type; - Default_Strategy : constant Strategy_Type; - - Default_Buffer_Size : constant := 4096; - - type Filter_Type is tagged limited private; - -- The filter is for compression and for decompression. - -- The usage of the type is depend of its initialization. - - function Version return String; - pragma Inline (Version); - -- Return string representation of the ZLib version. - - procedure Deflate_Init - (Filter : in out Filter_Type; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Method : in Compression_Method := Deflated; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Memory_Level : in Memory_Level_Type := Default_Memory_Level; - Header : in Header_Type := Default); - -- Compressor initialization. - -- When Header parameter is Auto or Default, then default zlib header - -- would be provided for compressed data. - -- When Header is GZip, then gzip header would be set instead of - -- default header. - -- When Header is None, no header would be set for compressed data. - - procedure Inflate_Init - (Filter : in out Filter_Type; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Header : in Header_Type := Default); - -- Decompressor initialization. - -- Default header type mean that ZLib default header is expecting in the - -- input compressed stream. - -- Header type None mean that no header is expecting in the input stream. - -- GZip header type mean that GZip header is expecting in the - -- input compressed stream. - -- Auto header type mean that header type (GZip or Native) would be - -- detected automatically in the input stream. - -- Note that header types parameter values None, GZip and Auto are - -- supported for inflate routine only in ZLib versions 1.2.0.2 and later. - -- Deflate_Init is supporting all header types. - - function Is_Open (Filter : in Filter_Type) return Boolean; - pragma Inline (Is_Open); - -- Is the filter opened for compression or decompression. - - procedure Close - (Filter : in out Filter_Type; - Ignore_Error : in Boolean := False); - -- Closing the compression or decompressor. - -- If stream is closing before the complete and Ignore_Error is False, - -- The exception would be raised. - - generic - with procedure Data_In - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - with procedure Data_Out - (Item : in Ada.Streams.Stream_Element_Array); - procedure Generic_Translate - (Filter : in out Filter_Type; - In_Buffer_Size : in Integer := Default_Buffer_Size; - Out_Buffer_Size : in Integer := Default_Buffer_Size); - -- Compress/decompress data fetch from Data_In routine and pass the result - -- to the Data_Out routine. User should provide Data_In and Data_Out - -- for compression/decompression data flow. - -- Compression or decompression depend on Filter initialization. - - function Total_In (Filter : in Filter_Type) return Count; - pragma Inline (Total_In); - -- Returns total number of input bytes read so far - - function Total_Out (Filter : in Filter_Type) return Count; - pragma Inline (Total_Out); - -- Returns total number of bytes output so far - - function CRC32 - (CRC : in Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) - return Unsigned_32; - pragma Inline (CRC32); - -- Compute CRC32, it could be necessary for make gzip format - - procedure CRC32 - (CRC : in out Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array); - pragma Inline (CRC32); - -- Compute CRC32, it could be necessary for make gzip format - - ------------------------------------------------- - -- Below is more complex low level routines. -- - ------------------------------------------------- - - procedure Translate - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- Compress/decompress the In_Data buffer and place the result into - -- Out_Data. In_Last is the index of last element from In_Data accepted by - -- the Filter. Out_Last is the last element of the received data from - -- Filter. To tell the filter that incoming data are complete put the - -- Flush parameter to Finish. - - function Stream_End (Filter : in Filter_Type) return Boolean; - pragma Inline (Stream_End); - -- Return the true when the stream is complete. - - procedure Flush - (Filter : in out Filter_Type; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - pragma Inline (Flush); - -- Flushing the data from the compressor. - - generic - with procedure Write - (Item : in Ada.Streams.Stream_Element_Array); - -- User should provide this routine for accept - -- compressed/decompressed data. - - Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - -- Buffer size for Write user routine. - - procedure Write - (Filter : in out Filter_Type; - Item : in Ada.Streams.Stream_Element_Array; - Flush : in Flush_Mode := No_Flush); - -- Compress/Decompress data from Item to the generic parameter procedure - -- Write. Output buffer size could be set in Buffer_Size generic parameter. - - generic - with procedure Read - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - -- User should provide data for compression/decompression - -- thru this routine. - - Buffer : in out Ada.Streams.Stream_Element_Array; - -- Buffer for keep remaining data from the previous - -- back read. - - Rest_First, Rest_Last : in out Ada.Streams.Stream_Element_Offset; - -- Rest_First have to be initialized to Buffer'Last + 1 - -- Rest_Last have to be initialized to Buffer'Last - -- before usage. - - Allow_Read_Some : in Boolean := False; - -- Is it allowed to return Last < Item'Last before end of data. - - procedure Read - (Filter : in out Filter_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode := No_Flush); - -- Compress/Decompress data from generic parameter procedure Read to the - -- Item. User should provide Buffer and initialized Rest_First, Rest_Last - -- indicators. If Allow_Read_Some is True, Read routines could return - -- Last < Item'Last only at end of stream. - -private - - use Ada.Streams; - - pragma Assert (Ada.Streams.Stream_Element'Size = 8); - pragma Assert (Ada.Streams.Stream_Element'Modulus = 2**8); - - type Flush_Mode is new Integer range 0 .. 5; - - type Compression_Method is new Integer range 8 .. 8; - - type Strategy_Type is new Integer range 0 .. 3; - - No_Flush : constant Flush_Mode := 0; - Partial_Flush : constant Flush_Mode := 1; - Sync_Flush : constant Flush_Mode := 2; - Full_Flush : constant Flush_Mode := 3; - Finish : constant Flush_Mode := 4; - Block_Flush : constant Flush_Mode := 5; - - Filtered : constant Strategy_Type := 1; - Huffman_Only : constant Strategy_Type := 2; - RLE : constant Strategy_Type := 3; - Default_Strategy : constant Strategy_Type := 0; - - Deflated : constant Compression_Method := 8; - - type Z_Stream; - - type Z_Stream_Access is access all Z_Stream; - - type Filter_Type is tagged limited record - Strm : Z_Stream_Access; - Compression : Boolean; - Stream_End : Boolean; - Header : Header_Type; - CRC : Unsigned_32; - Offset : Stream_Element_Offset; - -- Offset for gzip header/footer output. - end record; - -end ZLib; diff --git a/deps/zlib/contrib/ada/zlib.gpr b/deps/zlib/contrib/ada/zlib.gpr deleted file mode 100644 index 296b22aa966706..00000000000000 --- a/deps/zlib/contrib/ada/zlib.gpr +++ /dev/null @@ -1,20 +0,0 @@ -project Zlib is - - for Languages use ("Ada"); - for Source_Dirs use ("."); - for Object_Dir use "."; - for Main use ("test.adb", "mtest.adb", "read.adb", "buffer_demo"); - - package Compiler is - for Default_Switches ("ada") use ("-gnatwcfilopru", "-gnatVcdfimorst", "-gnatyabcefhiklmnoprst"); - end Compiler; - - package Linker is - for Default_Switches ("ada") use ("-lz"); - end Linker; - - package Builder is - for Default_Switches ("ada") use ("-s", "-gnatQ"); - end Builder; - -end Zlib; diff --git a/deps/zlib/contrib/amd64/amd64-match.S b/deps/zlib/contrib/amd64/amd64-match.S deleted file mode 100644 index 81d4a1c9494b1c..00000000000000 --- a/deps/zlib/contrib/amd64/amd64-match.S +++ /dev/null @@ -1,452 +0,0 @@ -/* - * match.S -- optimized version of longest_match() - * based on the similar work by Gilles Vollant, and Brian Raiter, written 1998 - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the BSD License. Use by owners of Che Guevarra - * parafernalia is prohibited, where possible, and highly discouraged - * elsewhere. - */ - -#ifndef NO_UNDERLINE -# define match_init _match_init -# define longest_match _longest_match -#endif - -#define scanend ebx -#define scanendw bx -#define chainlenwmask edx /* high word: current chain len low word: s->wmask */ -#define curmatch rsi -#define curmatchd esi -#define windowbestlen r8 -#define scanalign r9 -#define scanalignd r9d -#define window r10 -#define bestlen r11 -#define bestlend r11d -#define scanstart r12d -#define scanstartw r12w -#define scan r13 -#define nicematch r14d -#define limit r15 -#define limitd r15d -#define prev rcx - -/* - * The 258 is a "magic number, not a parameter -- changing it - * breaks the hell loose - */ -#define MAX_MATCH (258) -#define MIN_MATCH (3) -#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) -#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) - -/* stack frame offsets */ -#define LocalVarsSize (112) -#define _chainlenwmask ( 8-LocalVarsSize)(%rsp) -#define _windowbestlen (16-LocalVarsSize)(%rsp) -#define save_r14 (24-LocalVarsSize)(%rsp) -#define save_rsi (32-LocalVarsSize)(%rsp) -#define save_rbx (40-LocalVarsSize)(%rsp) -#define save_r12 (56-LocalVarsSize)(%rsp) -#define save_r13 (64-LocalVarsSize)(%rsp) -#define save_r15 (80-LocalVarsSize)(%rsp) - - -.globl match_init, longest_match - -/* - * On AMD64 the first argument of a function (in our case -- the pointer to - * deflate_state structure) is passed in %rdi, hence our offsets below are - * all off of that. - */ - -/* you can check the structure offset by running - -#include -#include -#include "deflate.h" - -void print_depl() -{ -deflate_state ds; -deflate_state *s=&ds; -printf("size pointer=%u\n",(int)sizeof(void*)); - -printf("#define dsWSize (%3u)(%%rdi)\n",(int)(((char*)&(s->w_size))-((char*)s))); -printf("#define dsWMask (%3u)(%%rdi)\n",(int)(((char*)&(s->w_mask))-((char*)s))); -printf("#define dsWindow (%3u)(%%rdi)\n",(int)(((char*)&(s->window))-((char*)s))); -printf("#define dsPrev (%3u)(%%rdi)\n",(int)(((char*)&(s->prev))-((char*)s))); -printf("#define dsMatchLen (%3u)(%%rdi)\n",(int)(((char*)&(s->match_length))-((char*)s))); -printf("#define dsPrevMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_match))-((char*)s))); -printf("#define dsStrStart (%3u)(%%rdi)\n",(int)(((char*)&(s->strstart))-((char*)s))); -printf("#define dsMatchStart (%3u)(%%rdi)\n",(int)(((char*)&(s->match_start))-((char*)s))); -printf("#define dsLookahead (%3u)(%%rdi)\n",(int)(((char*)&(s->lookahead))-((char*)s))); -printf("#define dsPrevLen (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_length))-((char*)s))); -printf("#define dsMaxChainLen (%3u)(%%rdi)\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); -printf("#define dsGoodMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->good_match))-((char*)s))); -printf("#define dsNiceMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->nice_match))-((char*)s))); -} - -*/ - - -/* - to compile for XCode 3.2 on MacOSX x86_64 - - run "gcc -g -c -DXCODE_MAC_X64_STRUCTURE amd64-match.S" - */ - - -#ifndef CURRENT_LINX_XCODE_MAC_X64_STRUCTURE -#define dsWSize ( 68)(%rdi) -#define dsWMask ( 76)(%rdi) -#define dsWindow ( 80)(%rdi) -#define dsPrev ( 96)(%rdi) -#define dsMatchLen (144)(%rdi) -#define dsPrevMatch (148)(%rdi) -#define dsStrStart (156)(%rdi) -#define dsMatchStart (160)(%rdi) -#define dsLookahead (164)(%rdi) -#define dsPrevLen (168)(%rdi) -#define dsMaxChainLen (172)(%rdi) -#define dsGoodMatch (188)(%rdi) -#define dsNiceMatch (192)(%rdi) - -#else - -#ifndef STRUCT_OFFSET -# define STRUCT_OFFSET (0) -#endif - - -#define dsWSize ( 56 + STRUCT_OFFSET)(%rdi) -#define dsWMask ( 64 + STRUCT_OFFSET)(%rdi) -#define dsWindow ( 72 + STRUCT_OFFSET)(%rdi) -#define dsPrev ( 88 + STRUCT_OFFSET)(%rdi) -#define dsMatchLen (136 + STRUCT_OFFSET)(%rdi) -#define dsPrevMatch (140 + STRUCT_OFFSET)(%rdi) -#define dsStrStart (148 + STRUCT_OFFSET)(%rdi) -#define dsMatchStart (152 + STRUCT_OFFSET)(%rdi) -#define dsLookahead (156 + STRUCT_OFFSET)(%rdi) -#define dsPrevLen (160 + STRUCT_OFFSET)(%rdi) -#define dsMaxChainLen (164 + STRUCT_OFFSET)(%rdi) -#define dsGoodMatch (180 + STRUCT_OFFSET)(%rdi) -#define dsNiceMatch (184 + STRUCT_OFFSET)(%rdi) - -#endif - - - - -.text - -/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ - -longest_match: -/* - * Retrieve the function arguments. %curmatch will hold cur_match - * throughout the entire function (passed via rsi on amd64). - * rdi will hold the pointer to the deflate_state (first arg on amd64) - */ - mov %rsi, save_rsi - mov %rbx, save_rbx - mov %r12, save_r12 - mov %r13, save_r13 - mov %r14, save_r14 - mov %r15, save_r15 - -/* uInt wmask = s->w_mask; */ -/* unsigned chain_length = s->max_chain_length; */ -/* if (s->prev_length >= s->good_match) { */ -/* chain_length >>= 2; */ -/* } */ - - movl dsPrevLen, %eax - movl dsGoodMatch, %ebx - cmpl %ebx, %eax - movl dsWMask, %eax - movl dsMaxChainLen, %chainlenwmask - jl LastMatchGood - shrl $2, %chainlenwmask -LastMatchGood: - -/* chainlen is decremented once beforehand so that the function can */ -/* use the sign flag instead of the zero flag for the exit test. */ -/* It is then shifted into the high word, to make room for the wmask */ -/* value, which it will always accompany. */ - - decl %chainlenwmask - shll $16, %chainlenwmask - orl %eax, %chainlenwmask - -/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ - - movl dsNiceMatch, %eax - movl dsLookahead, %ebx - cmpl %eax, %ebx - jl LookaheadLess - movl %eax, %ebx -LookaheadLess: movl %ebx, %nicematch - -/* register Bytef *scan = s->window + s->strstart; */ - - mov dsWindow, %window - movl dsStrStart, %limitd - lea (%limit, %window), %scan - -/* Determine how many bytes the scan ptr is off from being */ -/* dword-aligned. */ - - mov %scan, %scanalign - negl %scanalignd - andl $3, %scanalignd - -/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ -/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ - - movl dsWSize, %eax - subl $MIN_LOOKAHEAD, %eax - xorl %ecx, %ecx - subl %eax, %limitd - cmovng %ecx, %limitd - -/* int best_len = s->prev_length; */ - - movl dsPrevLen, %bestlend - -/* Store the sum of s->window + best_len in %windowbestlen locally, and in memory. */ - - lea (%window, %bestlen), %windowbestlen - mov %windowbestlen, _windowbestlen - -/* register ush scan_start = *(ushf*)scan; */ -/* register ush scan_end = *(ushf*)(scan+best_len-1); */ -/* Posf *prev = s->prev; */ - - movzwl (%scan), %scanstart - movzwl -1(%scan, %bestlen), %scanend - mov dsPrev, %prev - -/* Jump into the main loop. */ - - movl %chainlenwmask, _chainlenwmask - jmp LoopEntry - -.balign 16 - -/* do { - * match = s->window + cur_match; - * if (*(ushf*)(match+best_len-1) != scan_end || - * *(ushf*)match != scan_start) continue; - * [...] - * } while ((cur_match = prev[cur_match & wmask]) > limit - * && --chain_length != 0); - * - * Here is the inner loop of the function. The function will spend the - * majority of its time in this loop, and majority of that time will - * be spent in the first ten instructions. - */ -LookupLoop: - andl %chainlenwmask, %curmatchd - movzwl (%prev, %curmatch, 2), %curmatchd - cmpl %limitd, %curmatchd - jbe LeaveNow - subl $0x00010000, %chainlenwmask - js LeaveNow -LoopEntry: cmpw -1(%windowbestlen, %curmatch), %scanendw - jne LookupLoop - cmpw %scanstartw, (%window, %curmatch) - jne LookupLoop - -/* Store the current value of chainlen. */ - movl %chainlenwmask, _chainlenwmask - -/* %scan is the string under scrutiny, and %prev to the string we */ -/* are hoping to match it up with. In actuality, %esi and %edi are */ -/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ -/* initialized to -(MAX_MATCH_8 - scanalign). */ - - mov $(-MAX_MATCH_8), %rdx - lea (%curmatch, %window), %windowbestlen - lea MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen - lea MAX_MATCH_8(%scan, %scanalign), %prev - -/* the prefetching below makes very little difference... */ - prefetcht1 (%windowbestlen, %rdx) - prefetcht1 (%prev, %rdx) - -/* - * Test the strings for equality, 8 bytes at a time. At the end, - * adjust %rdx so that it is offset to the exact byte that mismatched. - * - * It should be confessed that this loop usually does not represent - * much of the total running time. Replacing it with a more - * straightforward "rep cmpsb" would not drastically degrade - * performance -- unrolling it, for example, makes no difference. - */ - -#undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */ - -LoopCmps: -#ifdef USE_SSE - /* Preload the SSE registers */ - movdqu (%windowbestlen, %rdx), %xmm1 - movdqu (%prev, %rdx), %xmm2 - pcmpeqb %xmm2, %xmm1 - movdqu 16(%windowbestlen, %rdx), %xmm3 - movdqu 16(%prev, %rdx), %xmm4 - pcmpeqb %xmm4, %xmm3 - movdqu 32(%windowbestlen, %rdx), %xmm5 - movdqu 32(%prev, %rdx), %xmm6 - pcmpeqb %xmm6, %xmm5 - movdqu 48(%windowbestlen, %rdx), %xmm7 - movdqu 48(%prev, %rdx), %xmm8 - pcmpeqb %xmm8, %xmm7 - - /* Check the comparisions' results */ - pmovmskb %xmm1, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - /* this is the only iteration of the loop with a possibility of having - incremented rdx by 0x108 (each loop iteration add 16*4 = 0x40 - and (0x40*4)+8=0x108 */ - add $8, %rdx - jz LenMaximum - add $8, %rdx - - - pmovmskb %xmm3, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - - add $16, %rdx - - - pmovmskb %xmm5, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - add $16, %rdx - - - pmovmskb %xmm7, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - add $16, %rdx - - jmp LoopCmps -LeaveLoopCmps: add %rax, %rdx -#else - mov (%windowbestlen, %rdx), %rax - xor (%prev, %rdx), %rax - jnz LeaveLoopCmps - - mov 8(%windowbestlen, %rdx), %rax - xor 8(%prev, %rdx), %rax - jnz LeaveLoopCmps8 - - mov 16(%windowbestlen, %rdx), %rax - xor 16(%prev, %rdx), %rax - jnz LeaveLoopCmps16 - - add $24, %rdx - jnz LoopCmps - jmp LenMaximum -# if 0 -/* - * This three-liner is tantalizingly simple, but bsf is a slow instruction, - * and the complicated alternative down below is quite a bit faster. Sad... - */ - -LeaveLoopCmps: bsf %rax, %rax /* find the first non-zero bit */ - shrl $3, %eax /* divide by 8 to get the byte */ - add %rax, %rdx -# else -LeaveLoopCmps16: - add $8, %rdx -LeaveLoopCmps8: - add $8, %rdx -LeaveLoopCmps: testl $0xFFFFFFFF, %eax /* Check the first 4 bytes */ - jnz Check16 - add $4, %rdx - shr $32, %rax -Check16: testw $0xFFFF, %ax - jnz LenLower - add $2, %rdx - shrl $16, %eax -LenLower: subb $1, %al - adc $0, %rdx -# endif -#endif - -/* Calculate the length of the match. If it is longer than MAX_MATCH, */ -/* then automatically accept it as the best possible match and leave. */ - - lea (%prev, %rdx), %rax - sub %scan, %rax - cmpl $MAX_MATCH, %eax - jge LenMaximum - -/* If the length of the match is not longer than the best match we */ -/* have so far, then forget it and return to the lookup loop. */ - - cmpl %bestlend, %eax - jg LongerMatch - mov _windowbestlen, %windowbestlen - mov dsPrev, %prev - movl _chainlenwmask, %edx - jmp LookupLoop - -/* s->match_start = cur_match; */ -/* best_len = len; */ -/* if (len >= nice_match) break; */ -/* scan_end = *(ushf*)(scan+best_len-1); */ - -LongerMatch: - movl %eax, %bestlend - movl %curmatchd, dsMatchStart - cmpl %nicematch, %eax - jge LeaveNow - - lea (%window, %bestlen), %windowbestlen - mov %windowbestlen, _windowbestlen - - movzwl -1(%scan, %rax), %scanend - mov dsPrev, %prev - movl _chainlenwmask, %chainlenwmask - jmp LookupLoop - -/* Accept the current string, with the maximum possible length. */ - -LenMaximum: - movl $MAX_MATCH, %bestlend - movl %curmatchd, dsMatchStart - -/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ -/* return s->lookahead; */ - -LeaveNow: - movl dsLookahead, %eax - cmpl %eax, %bestlend - cmovngl %bestlend, %eax -LookaheadRet: - -/* Restore the registers and return from whence we came. */ - - mov save_rsi, %rsi - mov save_rbx, %rbx - mov save_r12, %r12 - mov save_r13, %r13 - mov save_r14, %r14 - mov save_r15, %r15 - - ret - -match_init: ret diff --git a/deps/zlib/contrib/asm686/README.686 b/deps/zlib/contrib/asm686/README.686 deleted file mode 100644 index a0bf3bea4aff5b..00000000000000 --- a/deps/zlib/contrib/asm686/README.686 +++ /dev/null @@ -1,51 +0,0 @@ -This is a patched version of zlib, modified to use -Pentium-Pro-optimized assembly code in the deflation algorithm. The -files changed/added by this patch are: - -README.686 -match.S - -The speedup that this patch provides varies, depending on whether the -compiler used to build the original version of zlib falls afoul of the -PPro's speed traps. My own tests show a speedup of around 10-20% at -the default compression level, and 20-30% using -9, against a version -compiled using gcc 2.7.2.3. Your mileage may vary. - -Note that this code has been tailored for the PPro/PII in particular, -and will not perform particuarly well on a Pentium. - -If you are using an assembler other than GNU as, you will have to -translate match.S to use your assembler's syntax. (Have fun.) - -Brian Raiter -breadbox@muppetlabs.com -April, 1998 - - -Added for zlib 1.1.3: - -The patches come from -http://www.muppetlabs.com/~breadbox/software/assembly.html - -To compile zlib with this asm file, copy match.S to the zlib directory -then do: - -CFLAGS="-O3 -DASMV" ./configure -make OBJA=match.o - - -Update: - -I've been ignoring these assembly routines for years, believing that -gcc's generated code had caught up with it sometime around gcc 2.95 -and the major rearchitecting of the Pentium 4. However, I recently -learned that, despite what I believed, this code still has some life -in it. On the Pentium 4 and AMD64 chips, it continues to run about 8% -faster than the code produced by gcc 4.1. - -In acknowledgement of its continuing usefulness, I've altered the -license to match that of the rest of zlib. Share and Enjoy! - -Brian Raiter -breadbox@muppetlabs.com -April, 2007 diff --git a/deps/zlib/contrib/asm686/match.S b/deps/zlib/contrib/asm686/match.S deleted file mode 100644 index fa421092785d4c..00000000000000 --- a/deps/zlib/contrib/asm686/match.S +++ /dev/null @@ -1,357 +0,0 @@ -/* match.S -- x86 assembly version of the zlib longest_match() function. - * Optimized for the Intel 686 chips (PPro and later). - * - * Copyright (C) 1998, 2007 Brian Raiter - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the author be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ - -#ifndef NO_UNDERLINE -#define match_init _match_init -#define longest_match _longest_match -#endif - -#define MAX_MATCH (258) -#define MIN_MATCH (3) -#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) -#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) - -/* stack frame offsets */ - -#define chainlenwmask 0 /* high word: current chain len */ - /* low word: s->wmask */ -#define window 4 /* local copy of s->window */ -#define windowbestlen 8 /* s->window + bestlen */ -#define scanstart 16 /* first two bytes of string */ -#define scanend 12 /* last two bytes of string */ -#define scanalign 20 /* dword-misalignment of string */ -#define nicematch 24 /* a good enough match size */ -#define bestlen 28 /* size of best match so far */ -#define scan 32 /* ptr to string wanting match */ - -#define LocalVarsSize (36) -/* saved ebx 36 */ -/* saved edi 40 */ -/* saved esi 44 */ -/* saved ebp 48 */ -/* return address 52 */ -#define deflatestate 56 /* the function arguments */ -#define curmatch 60 - -/* All the +zlib1222add offsets are due to the addition of fields - * in zlib in the deflate_state structure since the asm code was first written - * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). - * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). - * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - */ - -#define zlib1222add (8) - -#define dsWSize (36+zlib1222add) -#define dsWMask (44+zlib1222add) -#define dsWindow (48+zlib1222add) -#define dsPrev (56+zlib1222add) -#define dsMatchLen (88+zlib1222add) -#define dsPrevMatch (92+zlib1222add) -#define dsStrStart (100+zlib1222add) -#define dsMatchStart (104+zlib1222add) -#define dsLookahead (108+zlib1222add) -#define dsPrevLen (112+zlib1222add) -#define dsMaxChainLen (116+zlib1222add) -#define dsGoodMatch (132+zlib1222add) -#define dsNiceMatch (136+zlib1222add) - - -.file "match.S" - -.globl match_init, longest_match - -.text - -/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ -.cfi_sections .debug_frame - -longest_match: - -.cfi_startproc -/* Save registers that the compiler may be using, and adjust %esp to */ -/* make room for our stack frame. */ - - pushl %ebp - .cfi_def_cfa_offset 8 - .cfi_offset ebp, -8 - pushl %edi - .cfi_def_cfa_offset 12 - pushl %esi - .cfi_def_cfa_offset 16 - pushl %ebx - .cfi_def_cfa_offset 20 - subl $LocalVarsSize, %esp - .cfi_def_cfa_offset LocalVarsSize+20 - -/* Retrieve the function arguments. %ecx will hold cur_match */ -/* throughout the entire function. %edx will hold the pointer to the */ -/* deflate_state structure during the function's setup (before */ -/* entering the main loop). */ - - movl deflatestate(%esp), %edx - movl curmatch(%esp), %ecx - -/* uInt wmask = s->w_mask; */ -/* unsigned chain_length = s->max_chain_length; */ -/* if (s->prev_length >= s->good_match) { */ -/* chain_length >>= 2; */ -/* } */ - - movl dsPrevLen(%edx), %eax - movl dsGoodMatch(%edx), %ebx - cmpl %ebx, %eax - movl dsWMask(%edx), %eax - movl dsMaxChainLen(%edx), %ebx - jl LastMatchGood - shrl $2, %ebx -LastMatchGood: - -/* chainlen is decremented once beforehand so that the function can */ -/* use the sign flag instead of the zero flag for the exit test. */ -/* It is then shifted into the high word, to make room for the wmask */ -/* value, which it will always accompany. */ - - decl %ebx - shll $16, %ebx - orl %eax, %ebx - movl %ebx, chainlenwmask(%esp) - -/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ - - movl dsNiceMatch(%edx), %eax - movl dsLookahead(%edx), %ebx - cmpl %eax, %ebx - jl LookaheadLess - movl %eax, %ebx -LookaheadLess: movl %ebx, nicematch(%esp) - -/* register Bytef *scan = s->window + s->strstart; */ - - movl dsWindow(%edx), %esi - movl %esi, window(%esp) - movl dsStrStart(%edx), %ebp - lea (%esi,%ebp), %edi - movl %edi, scan(%esp) - -/* Determine how many bytes the scan ptr is off from being */ -/* dword-aligned. */ - - movl %edi, %eax - negl %eax - andl $3, %eax - movl %eax, scanalign(%esp) - -/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ -/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ - - movl dsWSize(%edx), %eax - subl $MIN_LOOKAHEAD, %eax - subl %eax, %ebp - jg LimitPositive - xorl %ebp, %ebp -LimitPositive: - -/* int best_len = s->prev_length; */ - - movl dsPrevLen(%edx), %eax - movl %eax, bestlen(%esp) - -/* Store the sum of s->window + best_len in %esi locally, and in %esi. */ - - addl %eax, %esi - movl %esi, windowbestlen(%esp) - -/* register ush scan_start = *(ushf*)scan; */ -/* register ush scan_end = *(ushf*)(scan+best_len-1); */ -/* Posf *prev = s->prev; */ - - movzwl (%edi), %ebx - movl %ebx, scanstart(%esp) - movzwl -1(%edi,%eax), %ebx - movl %ebx, scanend(%esp) - movl dsPrev(%edx), %edi - -/* Jump into the main loop. */ - - movl chainlenwmask(%esp), %edx - jmp LoopEntry - -.balign 16 - -/* do { - * match = s->window + cur_match; - * if (*(ushf*)(match+best_len-1) != scan_end || - * *(ushf*)match != scan_start) continue; - * [...] - * } while ((cur_match = prev[cur_match & wmask]) > limit - * && --chain_length != 0); - * - * Here is the inner loop of the function. The function will spend the - * majority of its time in this loop, and majority of that time will - * be spent in the first ten instructions. - * - * Within this loop: - * %ebx = scanend - * %ecx = curmatch - * %edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) - * %esi = windowbestlen - i.e., (window + bestlen) - * %edi = prev - * %ebp = limit - */ -LookupLoop: - andl %edx, %ecx - movzwl (%edi,%ecx,2), %ecx - cmpl %ebp, %ecx - jbe LeaveNow - subl $0x00010000, %edx - js LeaveNow -LoopEntry: movzwl -1(%esi,%ecx), %eax - cmpl %ebx, %eax - jnz LookupLoop - movl window(%esp), %eax - movzwl (%eax,%ecx), %eax - cmpl scanstart(%esp), %eax - jnz LookupLoop - -/* Store the current value of chainlen. */ - - movl %edx, chainlenwmask(%esp) - -/* Point %edi to the string under scrutiny, and %esi to the string we */ -/* are hoping to match it up with. In actuality, %esi and %edi are */ -/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ -/* initialized to -(MAX_MATCH_8 - scanalign). */ - - movl window(%esp), %esi - movl scan(%esp), %edi - addl %ecx, %esi - movl scanalign(%esp), %eax - movl $(-MAX_MATCH_8), %edx - lea MAX_MATCH_8(%edi,%eax), %edi - lea MAX_MATCH_8(%esi,%eax), %esi - -/* Test the strings for equality, 8 bytes at a time. At the end, - * adjust %edx so that it is offset to the exact byte that mismatched. - * - * We already know at this point that the first three bytes of the - * strings match each other, and they can be safely passed over before - * starting the compare loop. So what this code does is skip over 0-3 - * bytes, as much as necessary in order to dword-align the %edi - * pointer. (%esi will still be misaligned three times out of four.) - * - * It should be confessed that this loop usually does not represent - * much of the total running time. Replacing it with a more - * straightforward "rep cmpsb" would not drastically degrade - * performance. - */ -LoopCmps: - movl (%esi,%edx), %eax - xorl (%edi,%edx), %eax - jnz LeaveLoopCmps - movl 4(%esi,%edx), %eax - xorl 4(%edi,%edx), %eax - jnz LeaveLoopCmps4 - addl $8, %edx - jnz LoopCmps - jmp LenMaximum -LeaveLoopCmps4: addl $4, %edx -LeaveLoopCmps: testl $0x0000FFFF, %eax - jnz LenLower - addl $2, %edx - shrl $16, %eax -LenLower: subb $1, %al - adcl $0, %edx - -/* Calculate the length of the match. If it is longer than MAX_MATCH, */ -/* then automatically accept it as the best possible match and leave. */ - - lea (%edi,%edx), %eax - movl scan(%esp), %edi - subl %edi, %eax - cmpl $MAX_MATCH, %eax - jge LenMaximum - -/* If the length of the match is not longer than the best match we */ -/* have so far, then forget it and return to the lookup loop. */ - - movl deflatestate(%esp), %edx - movl bestlen(%esp), %ebx - cmpl %ebx, %eax - jg LongerMatch - movl windowbestlen(%esp), %esi - movl dsPrev(%edx), %edi - movl scanend(%esp), %ebx - movl chainlenwmask(%esp), %edx - jmp LookupLoop - -/* s->match_start = cur_match; */ -/* best_len = len; */ -/* if (len >= nice_match) break; */ -/* scan_end = *(ushf*)(scan+best_len-1); */ - -LongerMatch: movl nicematch(%esp), %ebx - movl %eax, bestlen(%esp) - movl %ecx, dsMatchStart(%edx) - cmpl %ebx, %eax - jge LeaveNow - movl window(%esp), %esi - addl %eax, %esi - movl %esi, windowbestlen(%esp) - movzwl -1(%edi,%eax), %ebx - movl dsPrev(%edx), %edi - movl %ebx, scanend(%esp) - movl chainlenwmask(%esp), %edx - jmp LookupLoop - -/* Accept the current string, with the maximum possible length. */ - -LenMaximum: movl deflatestate(%esp), %edx - movl $MAX_MATCH, bestlen(%esp) - movl %ecx, dsMatchStart(%edx) - -/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ -/* return s->lookahead; */ - -LeaveNow: - movl deflatestate(%esp), %edx - movl bestlen(%esp), %ebx - movl dsLookahead(%edx), %eax - cmpl %eax, %ebx - jg LookaheadRet - movl %ebx, %eax -LookaheadRet: - -/* Restore the stack and return from whence we came. */ - - addl $LocalVarsSize, %esp - .cfi_def_cfa_offset 20 - popl %ebx - .cfi_def_cfa_offset 16 - popl %esi - .cfi_def_cfa_offset 12 - popl %edi - .cfi_def_cfa_offset 8 - popl %ebp - .cfi_def_cfa_offset 4 -.cfi_endproc -match_init: ret diff --git a/deps/zlib/contrib/bench/OWNERS b/deps/zlib/contrib/bench/OWNERS new file mode 100644 index 00000000000000..f1e3d4f472e484 --- /dev/null +++ b/deps/zlib/contrib/bench/OWNERS @@ -0,0 +1 @@ +noel@chromium.org diff --git a/deps/zlib/contrib/bench/zlib_bench.cc b/deps/zlib/contrib/bench/zlib_bench.cc new file mode 100644 index 00000000000000..5dcdef09f36b76 --- /dev/null +++ b/deps/zlib/contrib/bench/zlib_bench.cc @@ -0,0 +1,316 @@ +/* + * Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + * + * A benchmark test harness for measuring decoding performance of gzip or zlib + * (deflate) encoded compressed data. Given a file containing any data, encode + * (compress) it into gzip or zlib format and then decode (uncompress). Output + * the median and maximum encoding and decoding rates in MB/s. + * + * Raw deflate (no gzip or zlib stream wrapper) mode is also supported. Select + * it with the [raw] argument. Use the [gzip] [zlib] arguments to select those + * stream wrappers. + * + * Note this code can be compiled outside of the Chromium build system against + * the system zlib (-lz) with g++ or clang++ as follows: + * + * g++|clang++ -O3 -Wall -std=c++11 -lstdc++ -lz zlib_bench.cc + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "zlib.h" + +void error_exit(const char* error, int code) { + fprintf(stderr, "%s (%d)\n", error, code); + exit(code); +} + +inline char* string_data(std::string* s) { + return s->empty() ? 0 : &*s->begin(); +} + +struct Data { + Data(size_t s) { data.reset(new (std::nothrow) char[size = s]); } + std::unique_ptr data; + size_t size; +}; + +Data read_file_data_or_exit(const char* name) { + std::ifstream file(name, std::ios::in | std::ios::binary); + if (!file) { + perror(name); + exit(1); + } + + file.seekg(0, std::ios::end); + Data data(file.tellg()); + file.seekg(0, std::ios::beg); + + if (file && data.data) + file.read(data.data.get(), data.size); + + if (!file || !data.data || !data.size) { + perror((std::string("failed: reading ") + name).c_str()); + exit(1); + } + + return data; +} + +size_t zlib_estimate_compressed_size(size_t input_size) { + return compressBound(input_size); +} + +enum zlib_wrapper { + kWrapperNONE, + kWrapperZLIB, + kWrapperGZIP, + kWrapperZRAW, +}; + +inline int zlib_stream_wrapper_type(zlib_wrapper type) { + if (type == kWrapperZLIB) // zlib DEFLATE stream wrapper + return MAX_WBITS; + if (type == kWrapperGZIP) // gzip DEFLATE stream wrapper + return MAX_WBITS + 16; + if (type == kWrapperZRAW) // no wrapper, use raw DEFLATE + return -MAX_WBITS; + error_exit("bad wrapper type", int(type)); + return 0; +} + +const char* zlib_wrapper_name(zlib_wrapper type) { + if (type == kWrapperZLIB) + return "ZLIB"; + if (type == kWrapperGZIP) + return "GZIP"; + if (type == kWrapperZRAW) + return "RAW"; + error_exit("bad wrapper type", int(type)); + return 0; +} + +static int zlib_compression_level; + +void zlib_compress( + const zlib_wrapper type, + const char* input, + const size_t input_size, + std::string* output, + bool resize_output = false) +{ + if (resize_output) + output->resize(zlib_estimate_compressed_size(input_size)); + size_t output_size = output->size(); + + z_stream stream; + memset(&stream, 0, sizeof(stream)); + + int result = deflateInit2(&stream, zlib_compression_level, Z_DEFLATED, + zlib_stream_wrapper_type(type), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + if (result != Z_OK) + error_exit("deflateInit2 failed", result); + + stream.next_out = (Bytef*)string_data(output); + stream.avail_out = (uInt)output_size; + stream.next_in = (z_const Bytef*)input; + stream.avail_in = (uInt)input_size; + + result = deflate(&stream, Z_FINISH); + if (result == Z_STREAM_END) + output_size = stream.total_out; + result |= deflateEnd(&stream); + if (result != Z_STREAM_END) + error_exit("compress failed", result); + + if (resize_output) + output->resize(output_size); +} + +void zlib_uncompress( + const zlib_wrapper type, + const std::string& input, + const size_t output_size, + std::string* output) +{ + z_stream stream; + memset(&stream, 0, sizeof(stream)); + + int result = inflateInit2(&stream, zlib_stream_wrapper_type(type)); + if (result != Z_OK) + error_exit("inflateInit2 failed", result); + + stream.next_out = (Bytef*)string_data(output); + stream.avail_out = (uInt)output->size(); + stream.next_in = (z_const Bytef*)input.data(); + stream.avail_in = (uInt)input.size(); + + result = inflate(&stream, Z_FINISH); + if (stream.total_out != output_size) + result = Z_DATA_ERROR; + result |= inflateEnd(&stream); + if (result == Z_STREAM_END) + return; + + std::string error("uncompress failed: "); + if (stream.msg) + error.append(stream.msg); + error_exit(error.c_str(), result); +} + +void verify_equal(const char* input, size_t size, std::string* output) { + const char* data = string_data(output); + if (output->size() == size && !memcmp(data, input, size)) + return; + fprintf(stderr, "uncompressed data does not match the input data\n"); + exit(3); +} + +void zlib_file(const char* name, const zlib_wrapper type) { + /* + * Read the file data. + */ + const auto file = read_file_data_or_exit(name); + const int length = static_cast(file.size); + const char* data = file.data.get(); + printf("%-40s :\n", name); + + /* + * Chop the data into blocks. + */ + const int block_size = 1 << 20; + const int blocks = (length + block_size - 1) / block_size; + + std::vector input(blocks); + std::vector input_length(blocks); + std::vector compressed(blocks); + std::vector output(blocks); + + for (int b = 0; b < blocks; ++b) { + int input_start = b * block_size; + int input_limit = std::min((b + 1) * block_size, length); + input[b] = data + input_start; + input_length[b] = input_limit - input_start; + } + + /* + * Run the zlib compress/uncompress loop a few times with |repeats| to + * process about 10MB of data if the length is small relative to 10MB. + * If length is large relative to 10MB, process the data once. + */ + const int mega_byte = 1024 * 1024; + const int repeats = (10 * mega_byte + length) / (length + 1); + const int runs = 5; + double ctime[runs]; + double utime[runs]; + + for (int run = 0; run < runs; ++run) { + const auto now = [] { return std::chrono::steady_clock::now(); }; + + // Pre-grow the output buffer so we don't measure string resize time. + for (int b = 0; b < blocks; ++b) + compressed[b].resize(zlib_estimate_compressed_size(block_size)); + + auto start = now(); + for (int b = 0; b < blocks; ++b) + for (int r = 0; r < repeats; ++r) + zlib_compress(type, input[b], input_length[b], &compressed[b]); + ctime[run] = std::chrono::duration(now() - start).count(); + + // Compress again, resizing compressed, so we don't leave junk at the + // end of the compressed string that could confuse zlib_uncompress(). + for (int b = 0; b < blocks; ++b) + zlib_compress(type, input[b], input_length[b], &compressed[b], true); + + for (int b = 0; b < blocks; ++b) + output[b].resize(input_length[b]); + + start = now(); + for (int r = 0; r < repeats; ++r) + for (int b = 0; b < blocks; ++b) + zlib_uncompress(type, compressed[b], input_length[b], &output[b]); + utime[run] = std::chrono::duration(now() - start).count(); + + for (int b = 0; b < blocks; ++b) + verify_equal(input[b], input_length[b], &output[b]); + } + + /* + * Output the median/maximum compress/uncompress rates in MB/s. + */ + size_t output_length = 0; + for (size_t i = 0; i < compressed.size(); ++i) + output_length += compressed[i].size(); + + std::sort(ctime, ctime + runs); + std::sort(utime, utime + runs); + + double deflate_rate_med = length * repeats / mega_byte / ctime[runs / 2]; + double inflate_rate_med = length * repeats / mega_byte / utime[runs / 2]; + double deflate_rate_max = length * repeats / mega_byte / ctime[0]; + double inflate_rate_max = length * repeats / mega_byte / utime[0]; + + // type, block size, compression ratio, etc + printf("%s: [b %dM] bytes %6d -> %6u %4.1f%%", + zlib_wrapper_name(type), block_size / (1 << 20), length, + static_cast(output_length), output_length * 100.0 / length); + + // compress / uncompress median (max) rates + printf(" comp %5.1f (%5.1f) MB/s uncomp %5.1f (%5.1f) MB/s\n", + deflate_rate_med, deflate_rate_max, inflate_rate_med, inflate_rate_max); +} + +static int argn = 1; + +char* get_option(int argc, char* argv[], const char* option) { + if (argn < argc) + return !strcmp(argv[argn], option) ? argv[argn++] : 0; + return 0; +} + +bool get_compression(int argc, char* argv[], int* value) { + if (argn < argc) + *value = atoi(argv[argn++]); + return *value >= 1 && *value <= 9; +} + +void usage_exit(const char* program) { + printf("usage: %s gzip|zlib|raw [--compression 1:9] files...\n", program); + exit(1); +} + +int main(int argc, char* argv[]) { + zlib_wrapper type; + if (get_option(argc, argv, "zlib")) + type = kWrapperZLIB; + else if (get_option(argc, argv, "gzip")) + type = kWrapperGZIP; + else if (get_option(argc, argv, "raw")) + type = kWrapperZRAW; + else + usage_exit(argv[0]); + + if (!get_option(argc, argv, "--compression")) + zlib_compression_level = Z_DEFAULT_COMPRESSION; + else if (!get_compression(argc, argv, &zlib_compression_level)) + usage_exit(argv[0]); + + if (argn >= argc) + usage_exit(argv[0]); + while (argn < argc) + zlib_file(argv[argn++], type); + + return 0; +} diff --git a/deps/zlib/contrib/blast/Makefile b/deps/zlib/contrib/blast/Makefile deleted file mode 100644 index 9be80bafe050ee..00000000000000 --- a/deps/zlib/contrib/blast/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -blast: blast.c blast.h - cc -DTEST -o blast blast.c - -test: blast - blast < test.pk | cmp - test.txt - -clean: - rm -f blast blast.o diff --git a/deps/zlib/contrib/blast/README b/deps/zlib/contrib/blast/README deleted file mode 100644 index e3a60b3f5cce7b..00000000000000 --- a/deps/zlib/contrib/blast/README +++ /dev/null @@ -1,4 +0,0 @@ -Read blast.h for purpose and usage. - -Mark Adler -madler@alumni.caltech.edu diff --git a/deps/zlib/contrib/blast/blast.c b/deps/zlib/contrib/blast/blast.c deleted file mode 100644 index e6e659073c630a..00000000000000 --- a/deps/zlib/contrib/blast/blast.c +++ /dev/null @@ -1,466 +0,0 @@ -/* blast.c - * Copyright (C) 2003, 2012, 2013 Mark Adler - * For conditions of distribution and use, see copyright notice in blast.h - * version 1.3, 24 Aug 2013 - * - * blast.c decompresses data compressed by the PKWare Compression Library. - * This function provides functionality similar to the explode() function of - * the PKWare library, hence the name "blast". - * - * This decompressor is based on the excellent format description provided by - * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the - * example Ben provided in the post is incorrect. The distance 110001 should - * instead be 111000. When corrected, the example byte stream becomes: - * - * 00 04 82 24 25 8f 80 7f - * - * which decompresses to "AIAIAIAIAIAIA" (without the quotes). - */ - -/* - * Change history: - * - * 1.0 12 Feb 2003 - First version - * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data - * 1.2 24 Oct 2012 - Add note about using binary mode in stdio - * - Fix comparisons of differently signed integers - * 1.3 24 Aug 2013 - Return unused input from blast() - * - Fix test code to correctly report unused input - * - Enable the provision of initial input to blast() - */ - -#include /* for NULL */ -#include /* for setjmp(), longjmp(), and jmp_buf */ -#include "blast.h" /* prototype for blast() */ - -#define local static /* for local function definitions */ -#define MAXBITS 13 /* maximum code length */ -#define MAXWIN 4096 /* maximum window size */ - -/* input and output state */ -struct state { - /* input state */ - blast_in infun; /* input function provided by user */ - void *inhow; /* opaque information passed to infun() */ - unsigned char *in; /* next input location */ - unsigned left; /* available input at in */ - int bitbuf; /* bit buffer */ - int bitcnt; /* number of bits in bit buffer */ - - /* input limit error return state for bits() and decode() */ - jmp_buf env; - - /* output state */ - blast_out outfun; /* output function provided by user */ - void *outhow; /* opaque information passed to outfun() */ - unsigned next; /* index of next write location in out[] */ - int first; /* true to check distances (for first 4K) */ - unsigned char out[MAXWIN]; /* output buffer and sliding window */ -}; - -/* - * Return need bits from the input stream. This always leaves less than - * eight bits in the buffer. bits() works properly for need == 0. - * - * Format notes: - * - * - Bits are stored in bytes from the least significant bit to the most - * significant bit. Therefore bits are dropped from the bottom of the bit - * buffer, using shift right, and new bytes are appended to the top of the - * bit buffer, using shift left. - */ -local int bits(struct state *s, int need) -{ - int val; /* bit accumulator */ - - /* load at least need bits into val */ - val = s->bitbuf; - while (s->bitcnt < need) { - if (s->left == 0) { - s->left = s->infun(s->inhow, &(s->in)); - if (s->left == 0) longjmp(s->env, 1); /* out of input */ - } - val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */ - s->left--; - s->bitcnt += 8; - } - - /* drop need bits and update buffer, always zero to seven bits left */ - s->bitbuf = val >> need; - s->bitcnt -= need; - - /* return need bits, zeroing the bits above that */ - return val & ((1 << need) - 1); -} - -/* - * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of - * each length, which for a canonical code are stepped through in order. - * symbol[] are the symbol values in canonical order, where the number of - * entries is the sum of the counts in count[]. The decoding process can be - * seen in the function decode() below. - */ -struct huffman { - short *count; /* number of symbols of each length */ - short *symbol; /* canonically ordered symbols */ -}; - -/* - * Decode a code from the stream s using huffman table h. Return the symbol or - * a negative value if there is an error. If all of the lengths are zero, i.e. - * an empty code, or if the code is incomplete and an invalid code is received, - * then -9 is returned after reading MAXBITS bits. - * - * Format notes: - * - * - The codes as stored in the compressed data are bit-reversed relative to - * a simple integer ordering of codes of the same lengths. Hence below the - * bits are pulled from the compressed data one at a time and used to - * build the code value reversed from what is in the stream in order to - * permit simple integer comparisons for decoding. - * - * - The first code for the shortest length is all ones. Subsequent codes of - * the same length are simply integer decrements of the previous code. When - * moving up a length, a one bit is appended to the code. For a complete - * code, the last code of the longest length will be all zeros. To support - * this ordering, the bits pulled during decoding are inverted to apply the - * more "natural" ordering starting with all zeros and incrementing. - */ -local int decode(struct state *s, struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - int bitbuf; /* bits from stream */ - int left; /* bits left in next or left to process */ - short *next; /* next number of codes */ - - bitbuf = s->bitbuf; - left = s->bitcnt; - code = first = index = 0; - len = 1; - next = h->count + 1; - while (1) { - while (left--) { - code |= (bitbuf & 1) ^ 1; /* invert code */ - bitbuf >>= 1; - count = *next++; - if (code < first + count) { /* if length len, return symbol */ - s->bitbuf = bitbuf; - s->bitcnt = (s->bitcnt - len) & 7; - return h->symbol[index + (code - first)]; - } - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - len++; - } - left = (MAXBITS+1) - len; - if (left == 0) break; - if (s->left == 0) { - s->left = s->infun(s->inhow, &(s->in)); - if (s->left == 0) longjmp(s->env, 1); /* out of input */ - } - bitbuf = *(s->in)++; - s->left--; - if (left > 8) left = 8; - } - return -9; /* ran out of codes */ -} - -/* - * Given a list of repeated code lengths rep[0..n-1], where each byte is a - * count (high four bits + 1) and a code length (low four bits), generate the - * list of code lengths. This compaction reduces the size of the object code. - * Then given the list of code lengths length[0..n-1] representing a canonical - * Huffman code for n symbols, construct the tables required to decode those - * codes. Those tables are the number of codes of each length, and the symbols - * sorted by length, retaining their original order within each length. The - * return value is zero for a complete code set, negative for an over- - * subscribed code set, and positive for an incomplete code set. The tables - * can be used if the return value is zero or positive, but they cannot be used - * if the return value is negative. If the return value is zero, it is not - * possible for decode() using that table to return an error--any stream of - * enough bits will resolve to a symbol. If the return value is positive, then - * it is possible for decode() using that table to return an error for received - * codes past the end of the incomplete lengths. - */ -local int construct(struct huffman *h, const unsigned char *rep, int n) -{ - int symbol; /* current symbol when stepping through length[] */ - int len; /* current length when stepping through h->count[] */ - int left; /* number of possible codes left of current length */ - short offs[MAXBITS+1]; /* offsets in symbol table for each length */ - short length[256]; /* code lengths */ - - /* convert compact repeat counts into symbol bit length list */ - symbol = 0; - do { - len = *rep++; - left = (len >> 4) + 1; - len &= 15; - do { - length[symbol++] = len; - } while (--left); - } while (--n); - n = symbol; - - /* count number of codes of each length */ - for (len = 0; len <= MAXBITS; len++) - h->count[len] = 0; - for (symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; /* assumes lengths are within bounds */ - if (h->count[0] == n) /* no codes! */ - return 0; /* complete, but decode() will fail */ - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; /* one possible code of zero length */ - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; /* one more bit, double codes left */ - left -= h->count[len]; /* deduct count from possible codes */ - if (left < 0) return left; /* over-subscribed--return negative */ - } /* left > 0 means incomplete */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + h->count[len]; - - /* - * put symbols in table sorted by length, by symbol order within each - * length - */ - for (symbol = 0; symbol < n; symbol++) - if (length[symbol] != 0) - h->symbol[offs[length[symbol]]++] = symbol; - - /* return zero for complete set, positive for incomplete set */ - return left; -} - -/* - * Decode PKWare Compression Library stream. - * - * Format notes: - * - * - First byte is 0 if literals are uncoded or 1 if they are coded. Second - * byte is 4, 5, or 6 for the number of extra bits in the distance code. - * This is the base-2 logarithm of the dictionary size minus six. - * - * - Compressed data is a combination of literals and length/distance pairs - * terminated by an end code. Literals are either Huffman coded or - * uncoded bytes. A length/distance pair is a coded length followed by a - * coded distance to represent a string that occurs earlier in the - * uncompressed data that occurs again at the current location. - * - * - A bit preceding a literal or length/distance pair indicates which comes - * next, 0 for literals, 1 for length/distance. - * - * - If literals are uncoded, then the next eight bits are the literal, in the - * normal bit order in the stream, i.e. no bit-reversal is needed. Similarly, - * no bit reversal is needed for either the length extra bits or the distance - * extra bits. - * - * - Literal bytes are simply written to the output. A length/distance pair is - * an instruction to copy previously uncompressed bytes to the output. The - * copy is from distance bytes back in the output stream, copying for length - * bytes. - * - * - Distances pointing before the beginning of the output data are not - * permitted. - * - * - Overlapped copies, where the length is greater than the distance, are - * allowed and common. For example, a distance of one and a length of 518 - * simply copies the last byte 518 times. A distance of four and a length of - * twelve copies the last four bytes three times. A simple forward copy - * ignoring whether the length is greater than the distance or not implements - * this correctly. - */ -local int decomp(struct state *s) -{ - int lit; /* true if literals are coded */ - int dict; /* log2(dictionary size) - 6 */ - int symbol; /* decoded symbol, extra bits for distance */ - int len; /* length for copy */ - unsigned dist; /* distance for copy */ - int copy; /* copy counter */ - unsigned char *from, *to; /* copy pointers */ - static int virgin = 1; /* build tables once */ - static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */ - static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */ - static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */ - static struct huffman litcode = {litcnt, litsym}; /* length code */ - static struct huffman lencode = {lencnt, lensym}; /* length code */ - static struct huffman distcode = {distcnt, distsym};/* distance code */ - /* bit lengths of literal codes */ - static const unsigned char litlen[] = { - 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, - 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, - 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, - 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, - 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, - 44, 173}; - /* bit lengths of length codes 0..15 */ - static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23}; - /* bit lengths of distance codes 0..63 */ - static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248}; - static const short base[16] = { /* base for length codes */ - 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264}; - static const char extra[16] = { /* extra bits for length codes */ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8}; - - /* set up decoding tables (once--might not be thread-safe) */ - if (virgin) { - construct(&litcode, litlen, sizeof(litlen)); - construct(&lencode, lenlen, sizeof(lenlen)); - construct(&distcode, distlen, sizeof(distlen)); - virgin = 0; - } - - /* read header */ - lit = bits(s, 8); - if (lit > 1) return -1; - dict = bits(s, 8); - if (dict < 4 || dict > 6) return -2; - - /* decode literals and length/distance pairs */ - do { - if (bits(s, 1)) { - /* get length */ - symbol = decode(s, &lencode); - len = base[symbol] + bits(s, extra[symbol]); - if (len == 519) break; /* end code */ - - /* get distance */ - symbol = len == 2 ? 2 : dict; - dist = decode(s, &distcode) << symbol; - dist += bits(s, symbol); - dist++; - if (s->first && dist > s->next) - return -3; /* distance too far back */ - - /* copy length bytes from distance bytes back */ - do { - to = s->out + s->next; - from = to - dist; - copy = MAXWIN; - if (s->next < dist) { - from += copy; - copy = dist; - } - copy -= s->next; - if (copy > len) copy = len; - len -= copy; - s->next += copy; - do { - *to++ = *from++; - } while (--copy); - if (s->next == MAXWIN) { - if (s->outfun(s->outhow, s->out, s->next)) return 1; - s->next = 0; - s->first = 0; - } - } while (len != 0); - } - else { - /* get literal and write it */ - symbol = lit ? decode(s, &litcode) : bits(s, 8); - s->out[s->next++] = symbol; - if (s->next == MAXWIN) { - if (s->outfun(s->outhow, s->out, s->next)) return 1; - s->next = 0; - s->first = 0; - } - } - } while (1); - return 0; -} - -/* See comments in blast.h */ -int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, - unsigned *left, unsigned char **in) -{ - struct state s; /* input/output state */ - int err; /* return value */ - - /* initialize input state */ - s.infun = infun; - s.inhow = inhow; - if (left != NULL && *left) { - s.left = *left; - s.in = *in; - } - else - s.left = 0; - s.bitbuf = 0; - s.bitcnt = 0; - - /* initialize output state */ - s.outfun = outfun; - s.outhow = outhow; - s.next = 0; - s.first = 1; - - /* return if bits() or decode() tries to read past available input */ - if (setjmp(s.env) != 0) /* if came back here via longjmp(), */ - err = 2; /* then skip decomp(), return error */ - else - err = decomp(&s); /* decompress */ - - /* return unused input */ - if (left != NULL) - *left = s.left; - if (in != NULL) - *in = s.left ? s.in : NULL; - - /* write any leftover output and update the error code if needed */ - if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) - err = 1; - return err; -} - -#ifdef TEST -/* Example of how to use blast() */ -#include -#include - -#define CHUNK 16384 - -local unsigned inf(void *how, unsigned char **buf) -{ - static unsigned char hold[CHUNK]; - - *buf = hold; - return fread(hold, 1, CHUNK, (FILE *)how); -} - -local int outf(void *how, unsigned char *buf, unsigned len) -{ - return fwrite(buf, 1, len, (FILE *)how) != len; -} - -/* Decompress a PKWare Compression Library stream from stdin to stdout */ -int main(void) -{ - int ret; - unsigned left; - - /* decompress to stdout */ - left = 0; - ret = blast(inf, stdin, outf, stdout, &left, NULL); - if (ret != 0) - fprintf(stderr, "blast error: %d\n", ret); - - /* count any leftover bytes */ - while (getchar() != EOF) - left++; - if (left) - fprintf(stderr, "blast warning: %u unused bytes of input\n", left); - - /* return blast() error code */ - return ret; -} -#endif diff --git a/deps/zlib/contrib/blast/blast.h b/deps/zlib/contrib/blast/blast.h deleted file mode 100644 index 6cf65eda16e5b8..00000000000000 --- a/deps/zlib/contrib/blast/blast.h +++ /dev/null @@ -1,83 +0,0 @@ -/* blast.h -- interface for blast.c - Copyright (C) 2003, 2012, 2013 Mark Adler - version 1.3, 24 Aug 2013 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - - -/* - * blast() decompresses the PKWare Data Compression Library (DCL) compressed - * format. It provides the same functionality as the explode() function in - * that library. (Note: PKWare overused the "implode" verb, and the format - * used by their library implode() function is completely different and - * incompatible with the implode compression method supported by PKZIP.) - * - * The binary mode for stdio functions should be used to assure that the - * compressed data is not corrupted when read or written. For example: - * fopen(..., "rb") and fopen(..., "wb"). - */ - - -typedef unsigned (*blast_in)(void *how, unsigned char **buf); -typedef int (*blast_out)(void *how, unsigned char *buf, unsigned len); -/* Definitions for input/output functions passed to blast(). See below for - * what the provided functions need to do. - */ - - -int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, - unsigned *left, unsigned char **in); -/* Decompress input to output using the provided infun() and outfun() calls. - * On success, the return value of blast() is zero. If there is an error in - * the source data, i.e. it is not in the proper format, then a negative value - * is returned. If there is not enough input available or there is not enough - * output space, then a positive error is returned. - * - * The input function is invoked: len = infun(how, &buf), where buf is set by - * infun() to point to the input buffer, and infun() returns the number of - * available bytes there. If infun() returns zero, then blast() returns with - * an input error. (blast() only asks for input if it needs it.) inhow is for - * use by the application to pass an input descriptor to infun(), if desired. - * - * If left and in are not NULL and *left is not zero when blast() is called, - * then the *left bytes are *in are consumed for input before infun() is used. - * - * The output function is invoked: err = outfun(how, buf, len), where the bytes - * to be written are buf[0..len-1]. If err is not zero, then blast() returns - * with an output error. outfun() is always called with len <= 4096. outhow - * is for use by the application to pass an output descriptor to outfun(), if - * desired. - * - * If there is any unused input, *left is set to the number of bytes that were - * read and *in points to them. Otherwise *left is set to zero and *in is set - * to NULL. If left or in are NULL, then they are not set. - * - * The return codes are: - * - * 2: ran out of input before completing decompression - * 1: output error before completing decompression - * 0: successful decompression - * -1: literal flag not zero or one - * -2: dictionary size not in 4..6 - * -3: distance is too far back - * - * At the bottom of blast.c is an example program that uses blast() that can be - * compiled to produce a command-line decompression filter by defining TEST. - */ diff --git a/deps/zlib/contrib/blast/test.pk b/deps/zlib/contrib/blast/test.pk deleted file mode 100644 index be10b2bbb25175..00000000000000 Binary files a/deps/zlib/contrib/blast/test.pk and /dev/null differ diff --git a/deps/zlib/contrib/blast/test.txt b/deps/zlib/contrib/blast/test.txt deleted file mode 100644 index bfdf1c5dca0a66..00000000000000 --- a/deps/zlib/contrib/blast/test.txt +++ /dev/null @@ -1 +0,0 @@ -AIAIAIAIAIAIA \ No newline at end of file diff --git a/deps/zlib/contrib/delphi/ZLib.pas b/deps/zlib/contrib/delphi/ZLib.pas deleted file mode 100644 index 060e1991186b19..00000000000000 --- a/deps/zlib/contrib/delphi/ZLib.pas +++ /dev/null @@ -1,557 +0,0 @@ -{*******************************************************} -{ } -{ Borland Delphi Supplemental Components } -{ ZLIB Data Compression Interface Unit } -{ } -{ Copyright (c) 1997,99 Borland Corporation } -{ } -{*******************************************************} - -{ Updated for zlib 1.2.x by Cosmin Truta } - -unit ZLib; - -interface - -uses SysUtils, Classes; - -type - TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl; - TFree = procedure (AppData, Block: Pointer); cdecl; - - // Internal structure. Ignore. - TZStreamRec = packed record - next_in: PChar; // next input byte - avail_in: Integer; // number of bytes available at next_in - total_in: Longint; // total nb of input bytes read so far - - next_out: PChar; // next output byte should be put here - avail_out: Integer; // remaining free space at next_out - total_out: Longint; // total nb of bytes output so far - - msg: PChar; // last error message, NULL if no error - internal: Pointer; // not visible by applications - - zalloc: TAlloc; // used to allocate the internal state - zfree: TFree; // used to free the internal state - AppData: Pointer; // private data object passed to zalloc and zfree - - data_type: Integer; // best guess about the data type: ascii or binary - adler: Longint; // adler32 value of the uncompressed data - reserved: Longint; // reserved for future use - end; - - // Abstract ancestor class - TCustomZlibStream = class(TStream) - private - FStrm: TStream; - FStrmPos: Integer; - FOnProgress: TNotifyEvent; - FZRec: TZStreamRec; - FBuffer: array [Word] of Char; - protected - procedure Progress(Sender: TObject); dynamic; - property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; - constructor Create(Strm: TStream); - end; - -{ TCompressionStream compresses data on the fly as data is written to it, and - stores the compressed data to another stream. - - TCompressionStream is write-only and strictly sequential. Reading from the - stream will raise an exception. Using Seek to move the stream pointer - will raise an exception. - - Output data is cached internally, written to the output stream only when - the internal output buffer is full. All pending output data is flushed - when the stream is destroyed. - - The Position property returns the number of uncompressed bytes of - data that have been written to the stream so far. - - CompressionRate returns the on-the-fly percentage by which the original - data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100 - If raw data size = 100 and compressed data size = 25, the CompressionRate - is 75% - - The OnProgress event is called each time the output buffer is filled and - written to the output stream. This is useful for updating a progress - indicator when you are writing a large chunk of data to the compression - stream in a single call.} - - - TCompressionLevel = (clNone, clFastest, clDefault, clMax); - - TCompressionStream = class(TCustomZlibStream) - private - function GetCompressionRate: Single; - public - constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream); - destructor Destroy; override; - function Read(var Buffer; Count: Longint): Longint; override; - function Write(const Buffer; Count: Longint): Longint; override; - function Seek(Offset: Longint; Origin: Word): Longint; override; - property CompressionRate: Single read GetCompressionRate; - property OnProgress; - end; - -{ TDecompressionStream decompresses data on the fly as data is read from it. - - Compressed data comes from a separate source stream. TDecompressionStream - is read-only and unidirectional; you can seek forward in the stream, but not - backwards. The special case of setting the stream position to zero is - allowed. Seeking forward decompresses data until the requested position in - the uncompressed data has been reached. Seeking backwards, seeking relative - to the end of the stream, requesting the size of the stream, and writing to - the stream will raise an exception. - - The Position property returns the number of bytes of uncompressed data that - have been read from the stream so far. - - The OnProgress event is called each time the internal input buffer of - compressed data is exhausted and the next block is read from the input stream. - This is useful for updating a progress indicator when you are reading a - large chunk of data from the decompression stream in a single call.} - - TDecompressionStream = class(TCustomZlibStream) - public - constructor Create(Source: TStream); - destructor Destroy; override; - function Read(var Buffer; Count: Longint): Longint; override; - function Write(const Buffer; Count: Longint): Longint; override; - function Seek(Offset: Longint; Origin: Word): Longint; override; - property OnProgress; - end; - - - -{ CompressBuf compresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - Out: OutBuf = ptr to newly allocated buffer containing decompressed data - OutBytes = number of bytes in OutBuf } -procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; - out OutBuf: Pointer; out OutBytes: Integer); - - -{ DecompressBuf decompresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - OutEstimate = zero, or est. size of the decompressed data - Out: OutBuf = ptr to newly allocated buffer containing decompressed data - OutBytes = number of bytes in OutBuf } -procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; - OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); - -{ DecompressToUserBuf decompresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - Out: OutBuf = ptr to user-allocated buffer to contain decompressed data - BufSize = number of bytes in OutBuf } -procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; - const OutBuf: Pointer; BufSize: Integer); - -const - zlib_version = '1.2.11'; - -type - EZlibError = class(Exception); - ECompressionError = class(EZlibError); - EDecompressionError = class(EZlibError); - -implementation - -uses ZLibConst; - -const - Z_NO_FLUSH = 0; - Z_PARTIAL_FLUSH = 1; - Z_SYNC_FLUSH = 2; - Z_FULL_FLUSH = 3; - Z_FINISH = 4; - - Z_OK = 0; - Z_STREAM_END = 1; - Z_NEED_DICT = 2; - Z_ERRNO = (-1); - Z_STREAM_ERROR = (-2); - Z_DATA_ERROR = (-3); - Z_MEM_ERROR = (-4); - Z_BUF_ERROR = (-5); - Z_VERSION_ERROR = (-6); - - Z_NO_COMPRESSION = 0; - Z_BEST_SPEED = 1; - Z_BEST_COMPRESSION = 9; - Z_DEFAULT_COMPRESSION = (-1); - - Z_FILTERED = 1; - Z_HUFFMAN_ONLY = 2; - Z_RLE = 3; - Z_DEFAULT_STRATEGY = 0; - - Z_BINARY = 0; - Z_ASCII = 1; - Z_UNKNOWN = 2; - - Z_DEFLATED = 8; - - -{$L adler32.obj} -{$L compress.obj} -{$L crc32.obj} -{$L deflate.obj} -{$L infback.obj} -{$L inffast.obj} -{$L inflate.obj} -{$L inftrees.obj} -{$L trees.obj} -{$L uncompr.obj} -{$L zutil.obj} - -procedure adler32; external; -procedure compressBound; external; -procedure crc32; external; -procedure deflateInit2_; external; -procedure deflateParams; external; - -function _malloc(Size: Integer): Pointer; cdecl; -begin - Result := AllocMem(Size); -end; - -procedure _free(Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; -begin - FillChar(P^, count, B); -end; - -procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; -begin - Move(source^, dest^, count); -end; - - - -// deflate compresses data -function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar; - recsize: Integer): Integer; external; -function deflate(var strm: TZStreamRec; flush: Integer): Integer; external; -function deflateEnd(var strm: TZStreamRec): Integer; external; - -// inflate decompresses data -function inflateInit_(var strm: TZStreamRec; version: PChar; - recsize: Integer): Integer; external; -function inflate(var strm: TZStreamRec; flush: Integer): Integer; external; -function inflateEnd(var strm: TZStreamRec): Integer; external; -function inflateReset(var strm: TZStreamRec): Integer; external; - - -function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl; -begin -// GetMem(Result, Items*Size); - Result := AllocMem(Items * Size); -end; - -procedure zlibFreeMem(AppData, Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -{function zlibCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise EZlibError.Create('error'); //!! -end;} - -function CCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise ECompressionError.Create('error'); //!! -end; - -function DCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise EDecompressionError.Create('error'); //!! -end; - -procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; - out OutBuf: Pointer; out OutBytes: Integer); -var - strm: TZStreamRec; - P: Pointer; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255; - GetMem(OutBuf, OutBytes); - try - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := OutBytes; - CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm))); - try - while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, 256); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := 256; - end; - finally - CCheck(deflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - - -procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; - OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); -var - strm: TZStreamRec; - P: Pointer; - BufInc: Integer; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - BufInc := (InBytes + 255) and not 255; - if OutEstimate = 0 then - OutBytes := BufInc - else - OutBytes := OutEstimate; - GetMem(OutBuf, OutBytes); - try - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := OutBytes; - DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); - try - while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, BufInc); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := BufInc; - end; - finally - DCheck(inflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - -procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; - const OutBuf: Pointer; BufSize: Integer); -var - strm: TZStreamRec; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := BufSize; - DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); - try - if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then - raise EZlibError.CreateRes(@sTargetBufferTooSmall); - finally - DCheck(inflateEnd(strm)); - end; -end; - -// TCustomZlibStream - -constructor TCustomZLibStream.Create(Strm: TStream); -begin - inherited Create; - FStrm := Strm; - FStrmPos := Strm.Position; - FZRec.zalloc := zlibAllocMem; - FZRec.zfree := zlibFreeMem; -end; - -procedure TCustomZLibStream.Progress(Sender: TObject); -begin - if Assigned(FOnProgress) then FOnProgress(Sender); -end; - - -// TCompressionStream - -constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; - Dest: TStream); -const - Levels: array [TCompressionLevel] of ShortInt = - (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); -begin - inherited Create(Dest); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); -end; - -destructor TCompressionStream.Destroy; -begin - FZRec.next_in := nil; - FZRec.avail_in := 0; - try - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) - and (FZRec.avail_out = 0) do - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - end; - if FZRec.avail_out < sizeof(FBuffer) then - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); - finally - deflateEnd(FZRec); - end; - inherited Destroy; -end; - -function TCompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - raise ECompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TCompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - FZRec.next_in := @Buffer; - FZRec.avail_in := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_in > 0) do - begin - CCheck(deflate(FZRec, 0)); - if FZRec.avail_out = 0 then - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - FStrmPos := FStrm.Position; - Progress(Self); - end; - end; - Result := Count; -end; - -function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -begin - if (Offset = 0) and (Origin = soFromCurrent) then - Result := FZRec.total_in - else - raise ECompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TCompressionStream.GetCompressionRate: Single; -begin - if FZRec.total_in = 0 then - Result := 0 - else - Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; -end; - - -// TDecompressionStream - -constructor TDecompressionStream.Create(Source: TStream); -begin - inherited Create(Source); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); -end; - -destructor TDecompressionStream.Destroy; -begin - FStrm.Seek(-FZRec.avail_in, 1); - inflateEnd(FZRec); - inherited Destroy; -end; - -function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - FZRec.next_out := @Buffer; - FZRec.avail_out := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_out > 0) do - begin - if FZRec.avail_in = 0 then - begin - FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer)); - if FZRec.avail_in = 0 then - begin - Result := Count - FZRec.avail_out; - Exit; - end; - FZRec.next_in := FBuffer; - FStrmPos := FStrm.Position; - Progress(Self); - end; - CCheck(inflate(FZRec, 0)); - end; - Result := Count; -end; - -function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - raise EDecompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -var - I: Integer; - Buf: array [0..4095] of Char; -begin - if (Offset = 0) and (Origin = soFromBeginning) then - begin - DCheck(inflateReset(FZRec)); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - FStrm.Position := 0; - FStrmPos := 0; - end - else if ( (Offset >= 0) and (Origin = soFromCurrent)) or - ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then - begin - if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); - if Offset > 0 then - begin - for I := 1 to Offset div sizeof(Buf) do - ReadBuffer(Buf, sizeof(Buf)); - ReadBuffer(Buf, Offset mod sizeof(Buf)); - end; - end - else - raise EDecompressionError.CreateRes(@sInvalidStreamOp); - Result := FZRec.total_out; -end; - - -end. diff --git a/deps/zlib/contrib/delphi/ZLibConst.pas b/deps/zlib/contrib/delphi/ZLibConst.pas deleted file mode 100644 index cdfe13671d3544..00000000000000 --- a/deps/zlib/contrib/delphi/ZLibConst.pas +++ /dev/null @@ -1,11 +0,0 @@ -unit ZLibConst; - -interface - -resourcestring - sTargetBufferTooSmall = 'ZLib error: target buffer may be too small'; - sInvalidStreamOp = 'Invalid stream operation'; - -implementation - -end. diff --git a/deps/zlib/contrib/delphi/readme.txt b/deps/zlib/contrib/delphi/readme.txt deleted file mode 100644 index 2dc9a8bba2f96e..00000000000000 --- a/deps/zlib/contrib/delphi/readme.txt +++ /dev/null @@ -1,76 +0,0 @@ - -Overview -======== - -This directory contains an update to the ZLib interface unit, -distributed by Borland as a Delphi supplemental component. - -The original ZLib unit is Copyright (c) 1997,99 Borland Corp., -and is based on zlib version 1.0.4. There are a series of bugs -and security problems associated with that old zlib version, and -we recommend the users to update their ZLib unit. - - -Summary of modifications -======================== - -- Improved makefile, adapted to zlib version 1.2.1. - -- Some field types from TZStreamRec are changed from Integer to - Longint, for consistency with the zlib.h header, and for 64-bit - readiness. - -- The zlib_version constant is updated. - -- The new Z_RLE strategy has its corresponding symbolic constant. - -- The allocation and deallocation functions and function types - (TAlloc, TFree, zlibAllocMem and zlibFreeMem) are now cdecl, - and _malloc and _free are added as C RTL stubs. As a result, - the original C sources of zlib can be compiled out of the box, - and linked to the ZLib unit. - - -Suggestions for improvements -============================ - -Currently, the ZLib unit provides only a limited wrapper around -the zlib library, and much of the original zlib functionality is -missing. Handling compressed file formats like ZIP/GZIP or PNG -cannot be implemented without having this functionality. -Applications that handle these formats are either using their own, -duplicated code, or not using the ZLib unit at all. - -Here are a few suggestions: - -- Checksum class wrappers around adler32() and crc32(), similar - to the Java classes that implement the java.util.zip.Checksum - interface. - -- The ability to read and write raw deflate streams, without the - zlib stream header and trailer. Raw deflate streams are used - in the ZIP file format. - -- The ability to read and write gzip streams, used in the GZIP - file format, and normally produced by the gzip program. - -- The ability to select a different compression strategy, useful - to PNG and MNG image compression, and to multimedia compression - in general. Besides the compression level - - TCompressionLevel = (clNone, clFastest, clDefault, clMax); - - which, in fact, could have used the 'z' prefix and avoided - TColor-like symbols - - TCompressionLevel = (zcNone, zcFastest, zcDefault, zcMax); - - there could be a compression strategy - - TCompressionStrategy = (zsDefault, zsFiltered, zsHuffmanOnly, zsRle); - -- ZIP and GZIP stream handling via TStreams. - - --- -Cosmin Truta diff --git a/deps/zlib/contrib/delphi/zlibd32.mak b/deps/zlib/contrib/delphi/zlibd32.mak deleted file mode 100644 index 9bb00b7cc4211c..00000000000000 --- a/deps/zlib/contrib/delphi/zlibd32.mak +++ /dev/null @@ -1,99 +0,0 @@ -# Makefile for zlib -# For use with Delphi and C++ Builder under Win32 -# Updated for zlib 1.2.x by Cosmin Truta - -# ------------ Borland C++ ------------ - -# This project uses the Delphi (fastcall/register) calling convention: -LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl - -CC = bcc32 -LD = bcc32 -AR = tlib -# do not use "-pr" in CFLAGS -CFLAGS = -a -d -k- -O2 $(LOC) -LDFLAGS = - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del *.obj - -del *.exe - -del *.lib - -del *.tds - -del zlib.bak - -del foo.gz - diff --git a/deps/zlib/contrib/dotzlib/DotZLib.build b/deps/zlib/contrib/dotzlib/DotZLib.build deleted file mode 100644 index 4ab1ca281e3f0a..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib.build +++ /dev/null @@ -1,33 +0,0 @@ - - - A .Net wrapper library around ZLib1.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/DotZLib.chm b/deps/zlib/contrib/dotzlib/DotZLib.chm deleted file mode 100644 index f214a444aebb20..00000000000000 Binary files a/deps/zlib/contrib/dotzlib/DotZLib.chm and /dev/null differ diff --git a/deps/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs b/deps/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs deleted file mode 100644 index 724c5347f35367..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly: AssemblyTitle("DotZLib")] -[assembly: AssemblyDescription(".Net bindings for ZLib compression dll 1.2.x")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Henrik Ravn")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("1.0.*")] - -// -// In order to sign your assembly you must specify a key to use. Refer to the -// Microsoft .NET Framework documentation for more information on assembly signing. -// -// Use the attributes below to control which key is used for signing. -// -// Notes: -// (*) If no key is specified, the assembly is not signed. -// (*) KeyName refers to a key that has been installed in the Crypto Service -// Provider (CSP) on your machine. KeyFile refers to a file which contains -// a key. -// (*) If the KeyFile and the KeyName values are both specified, the -// following processing occurs: -// (1) If the KeyName can be found in the CSP, that key is used. -// (2) If the KeyName does not exist and the KeyFile does exist, the key -// in the KeyFile is installed into the CSP and used. -// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. -// When specifying the KeyFile, the location of the KeyFile should be -// relative to the project output directory which is -// %Project Directory%\obj\. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] diff --git a/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs b/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs deleted file mode 100644 index b110dae6a1908d..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs +++ /dev/null @@ -1,202 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Runtime.InteropServices; -using System.Text; - - -namespace DotZLib -{ - #region ChecksumGeneratorBase - /// - /// Implements the common functionality needed for all s - /// - /// - public abstract class ChecksumGeneratorBase : ChecksumGenerator - { - /// - /// The value of the current checksum - /// - protected uint _current; - - /// - /// Initializes a new instance of the checksum generator base - the current checksum is - /// set to zero - /// - public ChecksumGeneratorBase() - { - _current = 0; - } - - /// - /// Initializes a new instance of the checksum generator basewith a specified value - /// - /// The value to set the current checksum to - public ChecksumGeneratorBase(uint initialValue) - { - _current = initialValue; - } - - /// - /// Resets the current checksum to zero - /// - public void Reset() { _current = 0; } - - /// - /// Gets the current checksum value - /// - public uint Value { get { return _current; } } - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - /// All the other Update methods are implmeneted in terms of this one. - /// This is therefore the only method a derived class has to implement - public abstract void Update(byte[] data, int offset, int count); - - /// - /// Updates the current checksum with an array of bytes. - /// - /// The data to update the checksum with - public void Update(byte[] data) - { - Update(data, 0, data.Length); - } - - /// - /// Updates the current checksum with the data from a string - /// - /// The string to update the checksum with - /// The characters in the string are converted by the UTF-8 encoding - public void Update(string data) - { - Update(Encoding.UTF8.GetBytes(data)); - } - - /// - /// Updates the current checksum with the data from a string, using a specific encoding - /// - /// The string to update the checksum with - /// The encoding to use - public void Update(string data, Encoding encoding) - { - Update(encoding.GetBytes(data)); - } - - } - #endregion - - #region CRC32 - /// - /// Implements a CRC32 checksum generator - /// - public sealed class CRC32Checksum : ChecksumGeneratorBase - { - #region DLL imports - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint crc32(uint crc, int data, uint length); - - #endregion - - /// - /// Initializes a new instance of the CRC32 checksum generator - /// - public CRC32Checksum() : base() {} - - /// - /// Initializes a new instance of the CRC32 checksum generator with a specified value - /// - /// The value to set the current checksum to - public CRC32Checksum(uint initialValue) : base(initialValue) {} - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - public override void Update(byte[] data, int offset, int count) - { - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); - try - { - _current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); - } - finally - { - hData.Free(); - } - } - - } - #endregion - - #region Adler - /// - /// Implements a checksum generator that computes the Adler checksum on data - /// - public sealed class AdlerChecksum : ChecksumGeneratorBase - { - #region DLL imports - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint adler32(uint adler, int data, uint length); - - #endregion - - /// - /// Initializes a new instance of the Adler checksum generator - /// - public AdlerChecksum() : base() {} - - /// - /// Initializes a new instance of the Adler checksum generator with a specified value - /// - /// The value to set the current checksum to - public AdlerChecksum(uint initialValue) : base(initialValue) {} - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - public override void Update(byte[] data, int offset, int count) - { - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); - try - { - _current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); - } - finally - { - hData.Free(); - } - } - - } - #endregion - -} \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs b/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs deleted file mode 100644 index 9c8d601954fafc..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; - -namespace DotZLib -{ - - /// - /// This class implements a circular buffer - /// - internal class CircularBuffer - { - #region Private data - private int _capacity; - private int _head; - private int _tail; - private int _size; - private byte[] _buffer; - #endregion - - public CircularBuffer(int capacity) - { - Debug.Assert( capacity > 0 ); - _buffer = new byte[capacity]; - _capacity = capacity; - _head = 0; - _tail = 0; - _size = 0; - } - - public int Size { get { return _size; } } - - public int Put(byte[] source, int offset, int count) - { - Debug.Assert( count > 0 ); - int trueCount = Math.Min(count, _capacity - Size); - for (int i = 0; i < trueCount; ++i) - _buffer[(_tail+i) % _capacity] = source[offset+i]; - _tail += trueCount; - _tail %= _capacity; - _size += trueCount; - return trueCount; - } - - public bool Put(byte b) - { - if (Size == _capacity) // no room - return false; - _buffer[_tail++] = b; - _tail %= _capacity; - ++_size; - return true; - } - - public int Get(byte[] destination, int offset, int count) - { - int trueCount = Math.Min(count,Size); - for (int i = 0; i < trueCount; ++i) - destination[offset + i] = _buffer[(_head+i) % _capacity]; - _head += trueCount; - _head %= _capacity; - _size -= trueCount; - return trueCount; - } - - public int Get() - { - if (Size == 0) - return -1; - - int result = (int)_buffer[_head++ % _capacity]; - --_size; - return result; - } - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs b/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs deleted file mode 100644 index b0eb78a0221a48..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - /// - /// Implements the common functionality needed for all s - /// - public abstract class CodecBase : Codec, IDisposable - { - - #region Data members - - /// - /// Instance of the internal zlib buffer structure that is - /// passed to all functions in the zlib dll - /// - internal ZStream _ztream = new ZStream(); - - /// - /// True if the object instance has been disposed, false otherwise - /// - protected bool _isDisposed = false; - - /// - /// The size of the internal buffers - /// - protected const int kBufferSize = 16384; - - private byte[] _outBuffer = new byte[kBufferSize]; - private byte[] _inBuffer = new byte[kBufferSize]; - - private GCHandle _hInput; - private GCHandle _hOutput; - - private uint _checksum = 0; - - #endregion - - /// - /// Initializes a new instance of the CodeBase class. - /// - public CodecBase() - { - try - { - _hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned); - _hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned); - } - catch (Exception) - { - CleanUp(false); - throw; - } - } - - - #region Codec Members - - /// - /// Occurs when more processed data are available. - /// - public event DataAvailableHandler DataAvailable; - - /// - /// Fires the event - /// - protected void OnDataAvailable() - { - if (_ztream.total_out > 0) - { - if (DataAvailable != null) - DataAvailable( _outBuffer, 0, (int)_ztream.total_out); - resetOutput(); - } - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// Adding data may, or may not, raise the DataAvailable event - public void Add(byte[] data) - { - Add(data,0,data.Length); - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - /// This must be implemented by a derived class - public abstract void Add(byte[] data, int offset, int count); - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - /// This must be implemented by a derived class - public abstract void Finish(); - - /// - /// Gets the checksum of the data that has been added so far - /// - public uint Checksum { get { return _checksum; } } - - #endregion - - #region Destructor & IDisposable stuff - - /// - /// Destroys this instance - /// - ~CodecBase() - { - CleanUp(false); - } - - /// - /// Releases any unmanaged resources and calls the method of the derived class - /// - public void Dispose() - { - CleanUp(true); - } - - /// - /// Performs any codec specific cleanup - /// - /// This must be implemented by a derived class - protected abstract void CleanUp(); - - // performs the release of the handles and calls the dereived CleanUp() - private void CleanUp(bool isDisposing) - { - if (!_isDisposed) - { - CleanUp(); - if (_hInput.IsAllocated) - _hInput.Free(); - if (_hOutput.IsAllocated) - _hOutput.Free(); - - _isDisposed = true; - } - } - - - #endregion - - #region Helper methods - - /// - /// Copies a number of bytes to the internal codec buffer - ready for proccesing - /// - /// The byte array that contains the data to copy - /// The index of the first byte to copy - /// The number of bytes to copy from data - protected void copyInput(byte[] data, int startIndex, int count) - { - Array.Copy(data, startIndex, _inBuffer,0, count); - _ztream.next_in = _hInput.AddrOfPinnedObject(); - _ztream.total_in = 0; - _ztream.avail_in = (uint)count; - - } - - /// - /// Resets the internal output buffers to a known state - ready for processing - /// - protected void resetOutput() - { - _ztream.total_out = 0; - _ztream.avail_out = kBufferSize; - _ztream.next_out = _hOutput.AddrOfPinnedObject(); - } - - /// - /// Updates the running checksum property - /// - /// The new checksum value - protected void setChecksum(uint newSum) - { - _checksum = newSum; - } - #endregion - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs b/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs deleted file mode 100644 index 9039f41f663702..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs +++ /dev/null @@ -1,106 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - - /// - /// Implements a data compressor, using the deflate algorithm in the ZLib dll - /// - public sealed class Deflater : CodecBase - { - #region Dll imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflate(ref ZStream sz, int flush); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflateReset(ref ZStream sz); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflateEnd(ref ZStream sz); - #endregion - - /// - /// Constructs an new instance of the Deflater - /// - /// The compression level to use for this Deflater - public Deflater(CompressLevel level) : base() - { - int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream)); - if (retval != 0) - throw new ZLibException(retval, "Could not initialize deflater"); - - resetOutput(); - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - public override void Add(byte[] data, int offset, int count) - { - if (data == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - - int total = count; - int inputIndex = offset; - int err = 0; - - while (err >= 0 && inputIndex < total) - { - copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); - while (err >= 0 && _ztream.avail_in > 0) - { - err = deflate(ref _ztream, (int)FlushTypes.None); - if (err == 0) - while (_ztream.avail_out == 0) - { - OnDataAvailable(); - err = deflate(ref _ztream, (int)FlushTypes.None); - } - inputIndex += (int)_ztream.total_in; - } - } - setChecksum( _ztream.adler ); - } - - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - public override void Finish() - { - int err; - do - { - err = deflate(ref _ztream, (int)FlushTypes.Finish); - OnDataAvailable(); - } - while (err == 0); - setChecksum( _ztream.adler ); - deflateReset(ref _ztream); - resetOutput(); - } - - /// - /// Closes the internal zlib deflate stream - /// - protected override void CleanUp() { deflateEnd(ref _ztream); } - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs b/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs deleted file mode 100644 index 90c7c3b3807333..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs +++ /dev/null @@ -1,288 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - - -namespace DotZLib -{ - - #region Internal types - - /// - /// Defines constants for the various flush types used with zlib - /// - internal enum FlushTypes - { - None, Partial, Sync, Full, Finish, Block - } - - #region ZStream structure - // internal mapping of the zlib zstream structure for marshalling - [StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)] - internal struct ZStream - { - public IntPtr next_in; - public uint avail_in; - public uint total_in; - - public IntPtr next_out; - public uint avail_out; - public uint total_out; - - [MarshalAs(UnmanagedType.LPStr)] - string msg; - uint state; - - uint zalloc; - uint zfree; - uint opaque; - - int data_type; - public uint adler; - uint reserved; - } - - #endregion - - #endregion - - #region Public enums - /// - /// Defines constants for the available compression levels in zlib - /// - public enum CompressLevel : int - { - /// - /// The default compression level with a reasonable compromise between compression and speed - /// - Default = -1, - /// - /// No compression at all. The data are passed straight through. - /// - None = 0, - /// - /// The maximum compression rate available. - /// - Best = 9, - /// - /// The fastest available compression level. - /// - Fastest = 1 - } - #endregion - - #region Exception classes - /// - /// The exception that is thrown when an error occurs on the zlib dll - /// - public class ZLibException : ApplicationException - { - /// - /// Initializes a new instance of the class with a specified - /// error message and error code - /// - /// The zlib error code that caused the exception - /// A message that (hopefully) describes the error - public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg)) - { - } - - /// - /// Initializes a new instance of the class with a specified - /// error code - /// - /// The zlib error code that caused the exception - public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode)) - { - } - } - #endregion - - #region Interfaces - - /// - /// Declares methods and properties that enables a running checksum to be calculated - /// - public interface ChecksumGenerator - { - /// - /// Gets the current value of the checksum - /// - uint Value { get; } - - /// - /// Clears the current checksum to 0 - /// - void Reset(); - - /// - /// Updates the current checksum with an array of bytes - /// - /// The data to update the checksum with - void Update(byte[] data); - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - void Update(byte[] data, int offset, int count); - - /// - /// Updates the current checksum with the data from a string - /// - /// The string to update the checksum with - /// The characters in the string are converted by the UTF-8 encoding - void Update(string data); - - /// - /// Updates the current checksum with the data from a string, using a specific encoding - /// - /// The string to update the checksum with - /// The encoding to use - void Update(string data, Encoding encoding); - } - - - /// - /// Represents the method that will be called from a codec when new data - /// are available. - /// - /// The byte array containing the processed data - /// The index of the first processed byte in data - /// The number of processed bytes available - /// On return from this method, the data may be overwritten, so grab it while you can. - /// You cannot assume that startIndex will be zero. - /// - public delegate void DataAvailableHandler(byte[] data, int startIndex, int count); - - /// - /// Declares methods and events for implementing compressors/decompressors - /// - public interface Codec - { - /// - /// Occurs when more processed data are available. - /// - event DataAvailableHandler DataAvailable; - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// Adding data may, or may not, raise the DataAvailable event - void Add(byte[] data); - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - void Add(byte[] data, int offset, int count); - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - void Finish(); - - /// - /// Gets the checksum of the data that has been added so far - /// - uint Checksum { get; } - - - } - - #endregion - - #region Classes - /// - /// Encapsulates general information about the ZLib library - /// - public class Info - { - #region DLL imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint zlibCompileFlags(); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern string zlibVersion(); - #endregion - - #region Private stuff - private uint _flags; - - // helper function that unpacks a bitsize mask - private static int bitSize(uint bits) - { - switch (bits) - { - case 0: return 16; - case 1: return 32; - case 2: return 64; - } - return -1; - } - #endregion - - /// - /// Constructs an instance of the Info class. - /// - public Info() - { - _flags = zlibCompileFlags(); - } - - /// - /// True if the library is compiled with debug info - /// - public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } } - - /// - /// True if the library is compiled with assembly optimizations - /// - public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } } - - /// - /// Gets the size of the unsigned int that was compiled into Zlib - /// - public int SizeOfUInt { get { return bitSize(_flags & 3); } } - - /// - /// Gets the size of the unsigned long that was compiled into Zlib - /// - public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } } - - /// - /// Gets the size of the pointers that were compiled into Zlib - /// - public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } } - - /// - /// Gets the size of the z_off_t type that was compiled into Zlib - /// - public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } } - - /// - /// Gets the version of ZLib as a string, e.g. "1.2.1" - /// - public static string Version { get { return zlibVersion(); } } - } - - #endregion - -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj b/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj deleted file mode 100644 index dea7fb16a94a13..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs b/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs deleted file mode 100644 index f0eada1d24bb88..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs +++ /dev/null @@ -1,301 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.IO; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - /// - /// Implements a compressed , in GZip (.gz) format. - /// - public class GZipStream : Stream, IDisposable - { - #region Dll Imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern IntPtr gzopen(string name, string mode); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzclose(IntPtr gzFile); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzwrite(IntPtr gzFile, int data, int length); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzread(IntPtr gzFile, int data, int length); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzgetc(IntPtr gzFile); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzputc(IntPtr gzFile, int c); - - #endregion - - #region Private data - private IntPtr _gzFile; - private bool _isDisposed = false; - private bool _isWriting; - #endregion - - #region Constructors - /// - /// Creates a new file as a writeable GZipStream - /// - /// The name of the compressed file to create - /// The compression level to use when adding data - /// If an error occurred in the internal zlib function - public GZipStream(string fileName, CompressLevel level) - { - _isWriting = true; - _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level)); - if (_gzFile == IntPtr.Zero) - throw new ZLibException(-1, "Could not open " + fileName); - } - - /// - /// Opens an existing file as a readable GZipStream - /// - /// The name of the file to open - /// If an error occurred in the internal zlib function - public GZipStream(string fileName) - { - _isWriting = false; - _gzFile = gzopen(fileName, "rb"); - if (_gzFile == IntPtr.Zero) - throw new ZLibException(-1, "Could not open " + fileName); - - } - #endregion - - #region Access properties - /// - /// Returns true of this stream can be read from, false otherwise - /// - public override bool CanRead - { - get - { - return !_isWriting; - } - } - - - /// - /// Returns false. - /// - public override bool CanSeek - { - get - { - return false; - } - } - - /// - /// Returns true if this tsream is writeable, false otherwise - /// - public override bool CanWrite - { - get - { - return _isWriting; - } - } - #endregion - - #region Destructor & IDispose stuff - - /// - /// Destroys this instance - /// - ~GZipStream() - { - cleanUp(false); - } - - /// - /// Closes the external file handle - /// - public void Dispose() - { - cleanUp(true); - } - - // Does the actual closing of the file handle. - private void cleanUp(bool isDisposing) - { - if (!_isDisposed) - { - gzclose(_gzFile); - _isDisposed = true; - } - } - #endregion - - #region Basic reading and writing - /// - /// Attempts to read a number of bytes from the stream. - /// - /// The destination data buffer - /// The index of the first destination byte in buffer - /// The number of bytes requested - /// The number of bytes read - /// If buffer is null - /// If count or offset are negative - /// If offset + count is > buffer.Length - /// If this stream is not readable. - /// If this stream has been disposed. - public override int Read(byte[] buffer, int offset, int count) - { - if (!CanRead) throw new NotSupportedException(); - if (buffer == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > buffer.Length) throw new ArgumentException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); - int result; - try - { - result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); - if (result < 0) - throw new IOException(); - } - finally - { - h.Free(); - } - return result; - } - - /// - /// Attempts to read a single byte from the stream. - /// - /// The byte that was read, or -1 in case of error or End-Of-File - public override int ReadByte() - { - if (!CanRead) throw new NotSupportedException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - return gzgetc(_gzFile); - } - - /// - /// Writes a number of bytes to the stream - /// - /// - /// - /// - /// If buffer is null - /// If count or offset are negative - /// If offset + count is > buffer.Length - /// If this stream is not writeable. - /// If this stream has been disposed. - public override void Write(byte[] buffer, int offset, int count) - { - if (!CanWrite) throw new NotSupportedException(); - if (buffer == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > buffer.Length) throw new ArgumentException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try - { - int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); - if (result < 0) - throw new IOException(); - } - finally - { - h.Free(); - } - } - - /// - /// Writes a single byte to the stream - /// - /// The byte to add to the stream. - /// If this stream is not writeable. - /// If this stream has been disposed. - public override void WriteByte(byte value) - { - if (!CanWrite) throw new NotSupportedException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - int result = gzputc(_gzFile, (int)value); - if (result < 0) - throw new IOException(); - } - #endregion - - #region Position & length stuff - /// - /// Not supported. - /// - /// - /// Always thrown - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - /// - /// Not suppported. - /// - /// - /// - /// - /// Always thrown - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - /// - /// Flushes the GZipStream. - /// - /// In this implementation, this method does nothing. This is because excessive - /// flushing may degrade the achievable compression rates. - public override void Flush() - { - // left empty on purpose - } - - /// - /// Gets/sets the current position in the GZipStream. Not suppported. - /// - /// In this implementation this property is not supported - /// Always thrown - public override long Position - { - get - { - throw new NotSupportedException(); - } - set - { - throw new NotSupportedException(); - } - } - - /// - /// Gets the size of the stream. Not suppported. - /// - /// In this implementation this property is not supported - /// Always thrown - public override long Length - { - get - { - throw new NotSupportedException(); - } - } - #endregion - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs b/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs deleted file mode 100644 index d295f268048696..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - - /// - /// Implements a data decompressor, using the inflate algorithm in the ZLib dll - /// - public class Inflater : CodecBase - { - #region Dll imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern int inflateInit_(ref ZStream sz, string vs, int size); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflate(ref ZStream sz, int flush); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflateReset(ref ZStream sz); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflateEnd(ref ZStream sz); - #endregion - - /// - /// Constructs an new instance of the Inflater - /// - public Inflater() : base() - { - int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream)); - if (retval != 0) - throw new ZLibException(retval, "Could not initialize inflater"); - - resetOutput(); - } - - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - public override void Add(byte[] data, int offset, int count) - { - if (data == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - - int total = count; - int inputIndex = offset; - int err = 0; - - while (err >= 0 && inputIndex < total) - { - copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); - err = inflate(ref _ztream, (int)FlushTypes.None); - if (err == 0) - while (_ztream.avail_out == 0) - { - OnDataAvailable(); - err = inflate(ref _ztream, (int)FlushTypes.None); - } - - inputIndex += (int)_ztream.total_in; - } - setChecksum( _ztream.adler ); - } - - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - public override void Finish() - { - int err; - do - { - err = inflate(ref _ztream, (int)FlushTypes.Finish); - OnDataAvailable(); - } - while (err == 0); - setChecksum( _ztream.adler ); - inflateReset(ref _ztream); - resetOutput(); - } - - /// - /// Closes the internal zlib inflate stream - /// - protected override void CleanUp() { inflateEnd(ref _ztream); } - - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs b/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs deleted file mode 100644 index 6d8aebb7994ef4..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs +++ /dev/null @@ -1,274 +0,0 @@ -// -// © Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Collections; -using System.IO; - -// uncomment the define below to include unit tests -//#define nunit -#if nunit -using NUnit.Framework; - -// Unit tests for the DotZLib class library -// ---------------------------------------- -// -// Use this with NUnit 2 from http://www.nunit.org -// - -namespace DotZLibTests -{ - using DotZLib; - - // helper methods - internal class Utils - { - public static bool byteArrEqual( byte[] lhs, byte[] rhs ) - { - if (lhs.Length != rhs.Length) - return false; - for (int i = lhs.Length-1; i >= 0; --i) - if (lhs[i] != rhs[i]) - return false; - return true; - } - - } - - - [TestFixture] - public class CircBufferTests - { - #region Circular buffer tests - [Test] - public void SinglePutGet() - { - CircularBuffer buf = new CircularBuffer(10); - Assert.AreEqual( 0, buf.Size ); - Assert.AreEqual( -1, buf.Get() ); - - Assert.IsTrue(buf.Put( 1 )); - Assert.AreEqual( 1, buf.Size ); - Assert.AreEqual( 1, buf.Get() ); - Assert.AreEqual( 0, buf.Size ); - Assert.AreEqual( -1, buf.Get() ); - } - - [Test] - public void BlockPutGet() - { - CircularBuffer buf = new CircularBuffer(10); - byte[] arr = {1,2,3,4,5,6,7,8,9,10}; - Assert.AreEqual( 10, buf.Put(arr,0,10) ); - Assert.AreEqual( 10, buf.Size ); - Assert.IsFalse( buf.Put(11) ); - Assert.AreEqual( 1, buf.Get() ); - Assert.IsTrue( buf.Put(11) ); - - byte[] arr2 = (byte[])arr.Clone(); - Assert.AreEqual( 9, buf.Get(arr2,1,9) ); - Assert.IsTrue( Utils.byteArrEqual(arr,arr2) ); - } - - #endregion - } - - [TestFixture] - public class ChecksumTests - { - #region CRC32 Tests - [Test] - public void CRC32_Null() - { - CRC32Checksum crc32 = new CRC32Checksum(); - Assert.AreEqual( 0, crc32.Value ); - - crc32 = new CRC32Checksum(1); - Assert.AreEqual( 1, crc32.Value ); - - crc32 = new CRC32Checksum(556); - Assert.AreEqual( 556, crc32.Value ); - } - - [Test] - public void CRC32_Data() - { - CRC32Checksum crc32 = new CRC32Checksum(); - byte[] data = { 1,2,3,4,5,6,7 }; - crc32.Update(data); - Assert.AreEqual( 0x70e46888, crc32.Value ); - - crc32 = new CRC32Checksum(); - crc32.Update("penguin"); - Assert.AreEqual( 0x0e5c1a120, crc32.Value ); - - crc32 = new CRC32Checksum(1); - crc32.Update("penguin"); - Assert.AreEqual(0x43b6aa94, crc32.Value); - - } - #endregion - - #region Adler tests - - [Test] - public void Adler_Null() - { - AdlerChecksum adler = new AdlerChecksum(); - Assert.AreEqual(0, adler.Value); - - adler = new AdlerChecksum(1); - Assert.AreEqual( 1, adler.Value ); - - adler = new AdlerChecksum(556); - Assert.AreEqual( 556, adler.Value ); - } - - [Test] - public void Adler_Data() - { - AdlerChecksum adler = new AdlerChecksum(1); - byte[] data = { 1,2,3,4,5,6,7 }; - adler.Update(data); - Assert.AreEqual( 0x5b001d, adler.Value ); - - adler = new AdlerChecksum(); - adler.Update("penguin"); - Assert.AreEqual(0x0bcf02f6, adler.Value ); - - adler = new AdlerChecksum(1); - adler.Update("penguin"); - Assert.AreEqual(0x0bd602f7, adler.Value); - - } - #endregion - } - - [TestFixture] - public class InfoTests - { - #region Info tests - [Test] - public void Info_Version() - { - Info info = new Info(); - Assert.AreEqual("1.2.11", Info.Version); - Assert.AreEqual(32, info.SizeOfUInt); - Assert.AreEqual(32, info.SizeOfULong); - Assert.AreEqual(32, info.SizeOfPointer); - Assert.AreEqual(32, info.SizeOfOffset); - } - #endregion - } - - [TestFixture] - public class DeflateInflateTests - { - #region Deflate tests - [Test] - public void Deflate_Init() - { - using (Deflater def = new Deflater(CompressLevel.Default)) - { - } - } - - private ArrayList compressedData = new ArrayList(); - private uint adler1; - - private ArrayList uncompressedData = new ArrayList(); - private uint adler2; - - public void CDataAvail(byte[] data, int startIndex, int count) - { - for (int i = 0; i < count; ++i) - compressedData.Add(data[i+startIndex]); - } - - [Test] - public void Deflate_Compress() - { - compressedData.Clear(); - - byte[] testData = new byte[35000]; - for (int i = 0; i < testData.Length; ++i) - testData[i] = 5; - - using (Deflater def = new Deflater((CompressLevel)5)) - { - def.DataAvailable += new DataAvailableHandler(CDataAvail); - def.Add(testData); - def.Finish(); - adler1 = def.Checksum; - } - } - #endregion - - #region Inflate tests - [Test] - public void Inflate_Init() - { - using (Inflater inf = new Inflater()) - { - } - } - - private void DDataAvail(byte[] data, int startIndex, int count) - { - for (int i = 0; i < count; ++i) - uncompressedData.Add(data[i+startIndex]); - } - - [Test] - public void Inflate_Expand() - { - uncompressedData.Clear(); - - using (Inflater inf = new Inflater()) - { - inf.DataAvailable += new DataAvailableHandler(DDataAvail); - inf.Add((byte[])compressedData.ToArray(typeof(byte))); - inf.Finish(); - adler2 = inf.Checksum; - } - Assert.AreEqual( adler1, adler2 ); - } - #endregion - } - - [TestFixture] - public class GZipStreamTests - { - #region GZipStream test - [Test] - public void GZipStream_WriteRead() - { - using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best)) - { - BinaryWriter writer = new BinaryWriter(gzOut); - writer.Write("hi there"); - writer.Write(Math.PI); - writer.Write(42); - } - - using (GZipStream gzIn = new GZipStream("gzstream.gz")) - { - BinaryReader reader = new BinaryReader(gzIn); - string s = reader.ReadString(); - Assert.AreEqual("hi there",s); - double d = reader.ReadDouble(); - Assert.AreEqual(Math.PI, d); - int i = reader.ReadInt32(); - Assert.AreEqual(42,i); - } - - } - #endregion - } -} - -#endif diff --git a/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt b/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt deleted file mode 100644 index 127a5bc39ba030..00000000000000 --- a/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/readme.txt b/deps/zlib/contrib/dotzlib/readme.txt deleted file mode 100644 index 4d8c2dd9324c4c..00000000000000 --- a/deps/zlib/contrib/dotzlib/readme.txt +++ /dev/null @@ -1,58 +0,0 @@ -This directory contains a .Net wrapper class library for the ZLib1.dll - -The wrapper includes support for inflating/deflating memory buffers, -.Net streaming wrappers for the gz streams part of zlib, and wrappers -for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples. - -Directory structure: --------------------- - -LICENSE_1_0.txt - License file. -readme.txt - This file. -DotZLib.chm - Class library documentation -DotZLib.build - NAnt build file -DotZLib.sln - Microsoft Visual Studio 2003 solution file - -DotZLib\*.cs - Source files for the class library - -Unit tests: ------------ -The file DotZLib/UnitTests.cs contains unit tests for use with NUnit 2.1 or higher. -To include unit tests in the build, define nunit before building. - - -Build instructions: -------------------- - -1. Using Visual Studio.Net 2003: - Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll) - will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on - you are building the release or debug version of the library. Check - DotZLib/UnitTests.cs for instructions on how to include unit tests in the - build. - -2. Using NAnt: - Open a command prompt with access to the build environment and run nant - in the same directory as the DotZLib.build file. - You can define 2 properties on the nant command-line to control the build: - debug={true|false} to toggle between release/debug builds (default=true). - nunit={true|false} to include or esclude unit tests (default=true). - Also the target clean will remove binaries. - Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release - or ./DotZLib/bin/debug, depending on whether you are building the release - or debug version of the library. - - Examples: - nant -D:debug=false -D:nunit=false - will build a release mode version of the library without unit tests. - nant - will build a debug version of the library with unit tests - nant clean - will remove all previously built files. - - ---------------------------------- -Copyright (c) Henrik Ravn 2004 - -Use, modification and distribution are subject to the Boost Software License, Version 1.0. -(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/deps/zlib/contrib/gcc_gvmat64/gvmat64.S b/deps/zlib/contrib/gcc_gvmat64/gvmat64.S deleted file mode 100644 index 23309fa286e535..00000000000000 --- a/deps/zlib/contrib/gcc_gvmat64/gvmat64.S +++ /dev/null @@ -1,574 +0,0 @@ -/* -;uInt longest_match_x64( -; deflate_state *s, -; IPos cur_match); // current match - -; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64 -; (AMD64 on Athlon 64, Opteron, Phenom -; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) -; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode) -; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; -; File written by Gilles Vollant, by converting to assembly the longest_match -; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. -; and by taking inspiration on asm686 with masm, optimised assembly code -; from Brian Raiter, written 1998 -; -; This software is provided 'as-is', without any express or implied -; warranty. In no event will the authors be held liable for any damages -; arising from the use of this software. -; -; Permission is granted to anyone to use this software for any purpose, -; including commercial applications, and to alter it and redistribute it -; freely, subject to the following restrictions: -; -; 1. The origin of this software must not be misrepresented; you must not -; claim that you wrote the original software. If you use this software -; in a product, an acknowledgment in the product documentation would be -; appreciated but is not required. -; 2. Altered source versions must be plainly marked as such, and must not be -; misrepresented as being the original software -; 3. This notice may not be removed or altered from any source distribution. -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; to compile this file for zLib, I use option: -; gcc -c -arch x86_64 gvmat64.S - - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; // current match / -; -; with XCode for Mac, I had strange error with some jump on intel syntax -; this is why BEFORE_JMP and AFTER_JMP are used - */ - - -#define BEFORE_JMP .att_syntax -#define AFTER_JMP .intel_syntax noprefix - -#ifndef NO_UNDERLINE -# define match_init _match_init -# define longest_match _longest_match -#endif - -.intel_syntax noprefix - -.globl match_init, longest_match -.text -longest_match: - - - -#define LocalVarsSize 96 -/* -; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 -; free register : r14,r15 -; register can be saved : rsp -*/ - -#define chainlenwmask (rsp + 8 - LocalVarsSize) -#define nicematch (rsp + 16 - LocalVarsSize) - -#define save_rdi (rsp + 24 - LocalVarsSize) -#define save_rsi (rsp + 32 - LocalVarsSize) -#define save_rbx (rsp + 40 - LocalVarsSize) -#define save_rbp (rsp + 48 - LocalVarsSize) -#define save_r12 (rsp + 56 - LocalVarsSize) -#define save_r13 (rsp + 64 - LocalVarsSize) -#define save_r14 (rsp + 72 - LocalVarsSize) -#define save_r15 (rsp + 80 - LocalVarsSize) - - -/* -; all the +4 offsets are due to the addition of pending_buf_size (in zlib -; in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, remove the +4). -; Note : these value are good with a 8 bytes boundary pack structure -*/ - -#define MAX_MATCH 258 -#define MIN_MATCH 3 -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) - -/* -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). -*/ - - - -/* you can check the structure offset by running - -#include -#include -#include "deflate.h" - -void print_depl() -{ -deflate_state ds; -deflate_state *s=&ds; -printf("size pointer=%u\n",(int)sizeof(void*)); - -printf("#define dsWSize %u\n",(int)(((char*)&(s->w_size))-((char*)s))); -printf("#define dsWMask %u\n",(int)(((char*)&(s->w_mask))-((char*)s))); -printf("#define dsWindow %u\n",(int)(((char*)&(s->window))-((char*)s))); -printf("#define dsPrev %u\n",(int)(((char*)&(s->prev))-((char*)s))); -printf("#define dsMatchLen %u\n",(int)(((char*)&(s->match_length))-((char*)s))); -printf("#define dsPrevMatch %u\n",(int)(((char*)&(s->prev_match))-((char*)s))); -printf("#define dsStrStart %u\n",(int)(((char*)&(s->strstart))-((char*)s))); -printf("#define dsMatchStart %u\n",(int)(((char*)&(s->match_start))-((char*)s))); -printf("#define dsLookahead %u\n",(int)(((char*)&(s->lookahead))-((char*)s))); -printf("#define dsPrevLen %u\n",(int)(((char*)&(s->prev_length))-((char*)s))); -printf("#define dsMaxChainLen %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); -printf("#define dsGoodMatch %u\n",(int)(((char*)&(s->good_match))-((char*)s))); -printf("#define dsNiceMatch %u\n",(int)(((char*)&(s->nice_match))-((char*)s))); -} -*/ - -#define dsWSize 68 -#define dsWMask 76 -#define dsWindow 80 -#define dsPrev 96 -#define dsMatchLen 144 -#define dsPrevMatch 148 -#define dsStrStart 156 -#define dsMatchStart 160 -#define dsLookahead 164 -#define dsPrevLen 168 -#define dsMaxChainLen 172 -#define dsGoodMatch 188 -#define dsNiceMatch 192 - -#define window_size [ rcx + dsWSize] -#define WMask [ rcx + dsWMask] -#define window_ad [ rcx + dsWindow] -#define prev_ad [ rcx + dsPrev] -#define strstart [ rcx + dsStrStart] -#define match_start [ rcx + dsMatchStart] -#define Lookahead [ rcx + dsLookahead] //; 0ffffffffh on infozip -#define prev_length [ rcx + dsPrevLen] -#define max_chain_length [ rcx + dsMaxChainLen] -#define good_match [ rcx + dsGoodMatch] -#define nice_match [ rcx + dsNiceMatch] - -/* -; windows: -; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match) - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. - -; -; gcc on macosx-linux: -; see http://www.x86-64.org/documentation/abi-0.99.pdf -; param 1 in rdi, param 2 in rsi -; rbx, rsp, rbp, r12 to r15 must be preserved - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - -;;; Retrieve the function arguments. r8d will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - -; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) -; mac: param 1 in rdi, param 2 rsi -; this clear high 32 bits of r8, which can be garbage in both r8 and rdx -*/ - mov [save_rbx],rbx - mov [save_rbp],rbp - - - mov rcx,rdi - - mov r8d,esi - - - mov [save_r12],r12 - mov [save_r13],r13 - mov [save_r14],r14 - mov [save_r15],r15 - - -//;;; uInt wmask = s->w_mask; -//;;; unsigned chain_length = s->max_chain_length; -//;;; if (s->prev_length >= s->good_match) { -//;;; chain_length >>= 2; -//;;; } - - - mov edi, prev_length - mov esi, good_match - mov eax, WMask - mov ebx, max_chain_length - cmp edi, esi - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -//;;; chainlen is decremented once beforehand so that the function can -//;;; use the sign flag instead of the zero flag for the exit test. -//;;; It is then shifted into the high word, to make room for the wmask -//;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - -//;;; on zlib only -//;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - - - mov eax, nice_match - mov [chainlenwmask], ebx - mov r10d, Lookahead - cmp r10d, eax - cmovnl r10d, eax - mov [nicematch],r10d - - - -//;;; register Bytef *scan = s->window + s->strstart; - mov r10, window_ad - mov ebp, strstart - lea r13, [r10 + rbp] - -//;;; Determine how many bytes the scan ptr is off from being -//;;; dword-aligned. - - mov r9,r13 - neg r13 - and r13,3 - -//;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -//;;; s->strstart - (IPos)MAX_DIST(s) : NIL; - - - mov eax, window_size - sub eax, MIN_LOOKAHEAD - - - xor edi,edi - sub ebp, eax - - mov r11d, prev_length - - cmovng ebp,edi - -//;;; int best_len = s->prev_length; - - -//;;; Store the sum of s->window + best_len in esi locally, and in esi. - - lea rsi,[r10+r11] - -//;;; register ush scan_start = *(ushf*)scan; -//;;; register ush scan_end = *(ushf*)(scan+best_len-1); -//;;; Posf *prev = s->prev; - - movzx r12d,word ptr [r9] - movzx ebx, word ptr [r9 + r11 - 1] - - mov rdi, prev_ad - -//;;; Jump into the main loop. - - mov edx, [chainlenwmask] - - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - - - -LookupLoop1: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - - - - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry1: - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jz LookupLoopIsZero - AFTER_JMP - -LookupLoop2: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry2: - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jz LookupLoopIsZero - AFTER_JMP - -LookupLoop4: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry4: - - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jnz LookupLoop1 - jmp LookupLoopIsZero - AFTER_JMP -/* -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; r8d = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit -*/ -.balign 16 -LookupLoop: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry: - - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jnz LookupLoop1 - AFTER_JMP -LookupLoopIsZero: - cmp r12w, word ptr [r10 + r8] - BEFORE_JMP - jnz LookupLoop1 - AFTER_JMP - - -//;;; Store the current value of chainlen. - mov [chainlenwmask], edx -/* -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). -*/ - lea rsi,[r8+r10] - mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8) - lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8] - lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8] - - prefetcht1 [rsi+rdx] - prefetcht1 [rdi+rdx] - -/* -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust rdx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (rsi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. -*/ - -LoopCmps: - mov rax, [rsi + rdx] - xor rax, [rdi + rdx] - jnz LeaveLoopCmps - - mov rax, [rsi + rdx + 8] - xor rax, [rdi + rdx + 8] - jnz LeaveLoopCmps8 - - - mov rax, [rsi + rdx + 8+8] - xor rax, [rdi + rdx + 8+8] - jnz LeaveLoopCmps16 - - add rdx,8+8+8 - - BEFORE_JMP - jnz LoopCmps - jmp LenMaximum - AFTER_JMP - -LeaveLoopCmps16: add rdx,8 -LeaveLoopCmps8: add rdx,8 -LeaveLoopCmps: - - test eax, 0x0000FFFF - jnz LenLower - - test eax,0xffffffff - - jnz LenLower32 - - add rdx,4 - shr rax,32 - or ax,ax - BEFORE_JMP - jnz LenLower - AFTER_JMP - -LenLower32: - shr eax,16 - add rdx,2 - -LenLower: - sub al, 1 - adc rdx, 0 -//;;; Calculate the length of the match. If it is longer than MAX_MATCH, -//;;; then automatically accept it as the best possible match and leave. - - lea rax, [rdi + rdx] - sub rax, r9 - cmp eax, MAX_MATCH - BEFORE_JMP - jge LenMaximum - AFTER_JMP -/* -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. -;/////////////////////////////////// -*/ - cmp eax, r11d - jg LongerMatch - - lea rsi,[r10+r11] - - mov rdi, prev_ad - mov edx, [chainlenwmask] - BEFORE_JMP - jmp LookupLoop - AFTER_JMP -/* -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); -*/ -LongerMatch: - mov r11d, eax - mov match_start, r8d - cmp eax, [nicematch] - BEFORE_JMP - jge LeaveNow - AFTER_JMP - - lea rsi,[r10+rax] - - movzx ebx, word ptr [r9 + rax - 1] - mov rdi, prev_ad - mov edx, [chainlenwmask] - BEFORE_JMP - jmp LookupLoop - AFTER_JMP - -//;;; Accept the current string, with the maximum possible length. - -LenMaximum: - mov r11d,MAX_MATCH - mov match_start, r8d - -//;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -//;;; return s->lookahead; - -LeaveNow: - mov eax, Lookahead - cmp r11d, eax - cmovng eax, r11d - - - -//;;; Restore the stack and return from whence we came. - - -// mov rsi,[save_rsi] -// mov rdi,[save_rdi] - mov rbx,[save_rbx] - mov rbp,[save_rbp] - mov r12,[save_r12] - mov r13,[save_r13] - mov r14,[save_r14] - mov r15,[save_r15] - - - ret 0 -//; please don't remove this string ! -//; Your can freely use gvmat64 in any free or commercial app -//; but it is far better don't remove the string in the binary! - // db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 - - -match_init: - ret 0 - - diff --git a/deps/zlib/contrib/infback9/README b/deps/zlib/contrib/infback9/README deleted file mode 100644 index e75ed132948f3b..00000000000000 --- a/deps/zlib/contrib/infback9/README +++ /dev/null @@ -1 +0,0 @@ -See infback9.h for what this is and how to use it. diff --git a/deps/zlib/contrib/infback9/infback9.c b/deps/zlib/contrib/infback9/infback9.c deleted file mode 100644 index 05fb3e338070d6..00000000000000 --- a/deps/zlib/contrib/infback9/infback9.c +++ /dev/null @@ -1,615 +0,0 @@ -/* infback9.c -- inflate deflate64 data using a call-back interface - * Copyright (C) 1995-2008 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "infback9.h" -#include "inftree9.h" -#include "inflate9.h" - -#define WSIZE 65536UL - -/* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - window is a user-supplied window and output buffer that is 64K bytes. - */ -int ZEXPORT inflateBack9Init_(strm, window, version, stream_size) -z_stream FAR *strm; -unsigned char FAR *window; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (voidpf)state; - state->window = window; - return Z_OK; -} - -/* - Build and output length and distance decoding tables for fixed code - decoding. - */ -#ifdef MAKEFIXED -#include - -void makefixed9(void) -{ - unsigned sym, bits, low, size; - code *next, *lenfix, *distfix; - struct inflate_state state; - code fixed[544]; - - /* literal/length table */ - sym = 0; - while (sym < 144) state.lens[sym++] = 8; - while (sym < 256) state.lens[sym++] = 9; - while (sym < 280) state.lens[sym++] = 7; - while (sym < 288) state.lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work); - - /* distance table */ - sym = 0; - while (sym < 32) state.lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work); - - /* write tables */ - puts(" /* inffix9.h -- table for decoding deflate64 fixed codes"); - puts(" * Generated automatically by makefixed9()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits, - lenfix[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 5) == 0) printf("\n "); - printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits, - distfix[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* Macros for inflateBack(): */ - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ - do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ - do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n <= 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ - do { \ - if (left == 0) { \ - put = window; \ - left = WSIZE; \ - wrap = 1; \ - if (out(out_desc, put, (unsigned)left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ -int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc) -z_stream FAR *strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; -{ - struct inflate_state FAR *state; - z_const unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have; /* available input */ - unsigned long left; /* available output */ - inflate_mode mode; /* current inflate mode */ - int lastblock; /* true if processing last block */ - int wrap; /* true if the window has wrapped */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned extra; /* extra bits needed */ - unsigned long length; /* literal or length of data to copy */ - unsigned long offset; /* distance back to copy string from */ - unsigned long copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - code here; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; -#include "inffix9.h" - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - mode = TYPE; - lastblock = 0; - wrap = 0; - window = state->window; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = window; - left = WSIZE; - lencode = Z_NULL; - distcode = Z_NULL; - - /* Inflate until end of block marked as last */ - for (;;) - switch (mode) { - case TYPE: - /* determine and dispatch block type */ - if (lastblock) { - BYTEBITS(); - mode = DONE; - break; - } - NEEDBITS(3); - lastblock = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - lastblock ? " (last)" : "")); - mode = STORED; - break; - case 1: /* fixed block */ - lencode = lenfix; - lenbits = 9; - distcode = distfix; - distbits = 5; - Tracev((stderr, "inflate: fixed codes block%s\n", - lastblock ? " (last)" : "")); - mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - lastblock ? " (last)" : "")); - mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - mode = BAD; - break; - } - length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %lu\n", - length)); - INITBITS(); - - /* copy stored block from input to output */ - while (length != 0) { - copy = length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); - if (state->nlen > 286) { - strm->msg = (char *)"too many length symbols"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - lencode = (code const FAR *)(state->next); - lenbits = 7; - ret = inflate_table9(CODES, state->lens, 19, &(state->next), - &(lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - here = lencode[BITS(lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.val < 16) { - NEEDBITS(here.bits); - DROPBITS(here.bits); - state->lens[state->have++] = here.val; - } - else { - if (here.val == 16) { - NEEDBITS(here.bits + 2); - DROPBITS(here.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (here.val == 17) { - NEEDBITS(here.bits + 3); - DROPBITS(here.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(here.bits + 7); - DROPBITS(here.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (mode == BAD) break; - - /* check for end-of-block code (better have one) */ - if (state->lens[256] == 0) { - strm->msg = (char *)"invalid code -- missing end-of-block"; - mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftree9.h - concerning the ENOUGH constants, which depend on those values */ - state->next = state->codes; - lencode = (code const FAR *)(state->next); - lenbits = 9; - ret = inflate_table9(LENS, state->lens, state->nlen, - &(state->next), &(lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - mode = BAD; - break; - } - distcode = (code const FAR *)(state->next); - distbits = 6; - ret = inflate_table9(DISTS, state->lens + state->nlen, - state->ndist, &(state->next), &(distbits), - state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - mode = LEN; - - case LEN: - /* get a literal, length, or end-of-block code */ - for (;;) { - here = lencode[BITS(lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.op && (here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - length = (unsigned)here.val; - - /* process literal */ - if (here.op == 0) { - Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", here.val)); - ROOM(); - *put++ = (unsigned char)(length); - left--; - mode = LEN; - break; - } - - /* process end of block */ - if (here.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - mode = TYPE; - break; - } - - /* invalid code */ - if (here.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - extra = (unsigned)(here.op) & 31; - if (extra != 0) { - NEEDBITS(extra); - length += BITS(extra); - DROPBITS(extra); - } - Tracevv((stderr, "inflate: length %lu\n", length)); - - /* get distance code */ - for (;;) { - here = distcode[BITS(distbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if ((here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - if (here.op & 64) { - strm->msg = (char *)"invalid distance code"; - mode = BAD; - break; - } - offset = (unsigned)here.val; - - /* get distance extra bits, if any */ - extra = (unsigned)(here.op) & 15; - if (extra != 0) { - NEEDBITS(extra); - offset += BITS(extra); - DROPBITS(extra); - } - if (offset > WSIZE - (wrap ? 0: left)) { - strm->msg = (char *)"invalid distance too far back"; - mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %lu\n", offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = WSIZE - offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - offset; - copy = left; - } - if (copy > length) copy = length; - length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < WSIZE) { - if (out(out_desc, window, (unsigned)(WSIZE - left))) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; -} - -int ZEXPORT inflateBack9End(strm) -z_stream FAR *strm; -{ - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} diff --git a/deps/zlib/contrib/infback9/infback9.h b/deps/zlib/contrib/infback9/infback9.h deleted file mode 100644 index 1073c0a38e6c2c..00000000000000 --- a/deps/zlib/contrib/infback9/infback9.h +++ /dev/null @@ -1,37 +0,0 @@ -/* infback9.h -- header for using inflateBack9 functions - * Copyright (C) 2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * This header file and associated patches provide a decoder for PKWare's - * undocumented deflate64 compression method (method 9). Use with infback9.c, - * inftree9.h, inftree9.c, and inffix9.h. These patches are not supported. - * This should be compiled with zlib, since it uses zutil.h and zutil.o. - * This code has not yet been tested on 16-bit architectures. See the - * comments in zlib.h for inflateBack() usage. These functions are used - * identically, except that there is no windowBits parameter, and a 64K - * window must be provided. Also if int's are 16 bits, then a zero for - * the third parameter of the "out" function actually means 65536UL. - * zlib.h must be included before this header file. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -ZEXTERN int ZEXPORT inflateBack9 OF((z_stream FAR *strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -ZEXTERN int ZEXPORT inflateBack9End OF((z_stream FAR *strm)); -ZEXTERN int ZEXPORT inflateBack9Init_ OF((z_stream FAR *strm, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define inflateBack9Init(strm, window) \ - inflateBack9Init_((strm), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -#ifdef __cplusplus -} -#endif diff --git a/deps/zlib/contrib/infback9/inffix9.h b/deps/zlib/contrib/infback9/inffix9.h deleted file mode 100644 index ee5671d2df63f4..00000000000000 --- a/deps/zlib/contrib/infback9/inffix9.h +++ /dev/null @@ -1,107 +0,0 @@ - /* inffix9.h -- table for decoding deflate64 fixed codes - * Generated automatically by makefixed9(). - */ - - /* WARNING: this file should *not* be used by applications. - It is part of the implementation of this library and is - subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{132,8,115},{130,7,31},{0,8,112}, - {0,8,48},{0,9,192},{128,7,10},{0,8,96},{0,8,32},{0,9,160}, - {0,8,0},{0,8,128},{0,8,64},{0,9,224},{128,7,6},{0,8,88}, - {0,8,24},{0,9,144},{131,7,59},{0,8,120},{0,8,56},{0,9,208}, - {129,7,17},{0,8,104},{0,8,40},{0,9,176},{0,8,8},{0,8,136}, - {0,8,72},{0,9,240},{128,7,4},{0,8,84},{0,8,20},{133,8,227}, - {131,7,43},{0,8,116},{0,8,52},{0,9,200},{129,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232}, - {128,7,8},{0,8,92},{0,8,28},{0,9,152},{132,7,83},{0,8,124}, - {0,8,60},{0,9,216},{130,7,23},{0,8,108},{0,8,44},{0,9,184}, - {0,8,12},{0,8,140},{0,8,76},{0,9,248},{128,7,3},{0,8,82}, - {0,8,18},{133,8,163},{131,7,35},{0,8,114},{0,8,50},{0,9,196}, - {129,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},{0,8,130}, - {0,8,66},{0,9,228},{128,7,7},{0,8,90},{0,8,26},{0,9,148}, - {132,7,67},{0,8,122},{0,8,58},{0,9,212},{130,7,19},{0,8,106}, - {0,8,42},{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244}, - {128,7,5},{0,8,86},{0,8,22},{65,8,0},{131,7,51},{0,8,118}, - {0,8,54},{0,9,204},{129,7,15},{0,8,102},{0,8,38},{0,9,172}, - {0,8,6},{0,8,134},{0,8,70},{0,9,236},{128,7,9},{0,8,94}, - {0,8,30},{0,9,156},{132,7,99},{0,8,126},{0,8,62},{0,9,220}, - {130,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{133,8,131}, - {130,7,31},{0,8,113},{0,8,49},{0,9,194},{128,7,10},{0,8,97}, - {0,8,33},{0,9,162},{0,8,1},{0,8,129},{0,8,65},{0,9,226}, - {128,7,6},{0,8,89},{0,8,25},{0,9,146},{131,7,59},{0,8,121}, - {0,8,57},{0,9,210},{129,7,17},{0,8,105},{0,8,41},{0,9,178}, - {0,8,9},{0,8,137},{0,8,73},{0,9,242},{128,7,4},{0,8,85}, - {0,8,21},{144,8,3},{131,7,43},{0,8,117},{0,8,53},{0,9,202}, - {129,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133}, - {0,8,69},{0,9,234},{128,7,8},{0,8,93},{0,8,29},{0,9,154}, - {132,7,83},{0,8,125},{0,8,61},{0,9,218},{130,7,23},{0,8,109}, - {0,8,45},{0,9,186},{0,8,13},{0,8,141},{0,8,77},{0,9,250}, - {128,7,3},{0,8,83},{0,8,19},{133,8,195},{131,7,35},{0,8,115}, - {0,8,51},{0,9,198},{129,7,11},{0,8,99},{0,8,35},{0,9,166}, - {0,8,3},{0,8,131},{0,8,67},{0,9,230},{128,7,7},{0,8,91}, - {0,8,27},{0,9,150},{132,7,67},{0,8,123},{0,8,59},{0,9,214}, - {130,7,19},{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139}, - {0,8,75},{0,9,246},{128,7,5},{0,8,87},{0,8,23},{77,8,0}, - {131,7,51},{0,8,119},{0,8,55},{0,9,206},{129,7,15},{0,8,103}, - {0,8,39},{0,9,174},{0,8,7},{0,8,135},{0,8,71},{0,9,238}, - {128,7,9},{0,8,95},{0,8,31},{0,9,158},{132,7,99},{0,8,127}, - {0,8,63},{0,9,222},{130,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80}, - {0,8,16},{132,8,115},{130,7,31},{0,8,112},{0,8,48},{0,9,193}, - {128,7,10},{0,8,96},{0,8,32},{0,9,161},{0,8,0},{0,8,128}, - {0,8,64},{0,9,225},{128,7,6},{0,8,88},{0,8,24},{0,9,145}, - {131,7,59},{0,8,120},{0,8,56},{0,9,209},{129,7,17},{0,8,104}, - {0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},{0,9,241}, - {128,7,4},{0,8,84},{0,8,20},{133,8,227},{131,7,43},{0,8,116}, - {0,8,52},{0,9,201},{129,7,13},{0,8,100},{0,8,36},{0,9,169}, - {0,8,4},{0,8,132},{0,8,68},{0,9,233},{128,7,8},{0,8,92}, - {0,8,28},{0,9,153},{132,7,83},{0,8,124},{0,8,60},{0,9,217}, - {130,7,23},{0,8,108},{0,8,44},{0,9,185},{0,8,12},{0,8,140}, - {0,8,76},{0,9,249},{128,7,3},{0,8,82},{0,8,18},{133,8,163}, - {131,7,35},{0,8,114},{0,8,50},{0,9,197},{129,7,11},{0,8,98}, - {0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {128,7,7},{0,8,90},{0,8,26},{0,9,149},{132,7,67},{0,8,122}, - {0,8,58},{0,9,213},{130,7,19},{0,8,106},{0,8,42},{0,9,181}, - {0,8,10},{0,8,138},{0,8,74},{0,9,245},{128,7,5},{0,8,86}, - {0,8,22},{65,8,0},{131,7,51},{0,8,118},{0,8,54},{0,9,205}, - {129,7,15},{0,8,102},{0,8,38},{0,9,173},{0,8,6},{0,8,134}, - {0,8,70},{0,9,237},{128,7,9},{0,8,94},{0,8,30},{0,9,157}, - {132,7,99},{0,8,126},{0,8,62},{0,9,221},{130,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253}, - {96,7,0},{0,8,81},{0,8,17},{133,8,131},{130,7,31},{0,8,113}, - {0,8,49},{0,9,195},{128,7,10},{0,8,97},{0,8,33},{0,9,163}, - {0,8,1},{0,8,129},{0,8,65},{0,9,227},{128,7,6},{0,8,89}, - {0,8,25},{0,9,147},{131,7,59},{0,8,121},{0,8,57},{0,9,211}, - {129,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},{0,8,137}, - {0,8,73},{0,9,243},{128,7,4},{0,8,85},{0,8,21},{144,8,3}, - {131,7,43},{0,8,117},{0,8,53},{0,9,203},{129,7,13},{0,8,101}, - {0,8,37},{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235}, - {128,7,8},{0,8,93},{0,8,29},{0,9,155},{132,7,83},{0,8,125}, - {0,8,61},{0,9,219},{130,7,23},{0,8,109},{0,8,45},{0,9,187}, - {0,8,13},{0,8,141},{0,8,77},{0,9,251},{128,7,3},{0,8,83}, - {0,8,19},{133,8,195},{131,7,35},{0,8,115},{0,8,51},{0,9,199}, - {129,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{128,7,7},{0,8,91},{0,8,27},{0,9,151}, - {132,7,67},{0,8,123},{0,8,59},{0,9,215},{130,7,19},{0,8,107}, - {0,8,43},{0,9,183},{0,8,11},{0,8,139},{0,8,75},{0,9,247}, - {128,7,5},{0,8,87},{0,8,23},{77,8,0},{131,7,51},{0,8,119}, - {0,8,55},{0,9,207},{129,7,15},{0,8,103},{0,8,39},{0,9,175}, - {0,8,7},{0,8,135},{0,8,71},{0,9,239},{128,7,9},{0,8,95}, - {0,8,31},{0,9,159},{132,7,99},{0,8,127},{0,8,63},{0,9,223}, - {130,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143}, - {0,8,79},{0,9,255} - }; - - static const code distfix[32] = { - {128,5,1},{135,5,257},{131,5,17},{139,5,4097},{129,5,5}, - {137,5,1025},{133,5,65},{141,5,16385},{128,5,3},{136,5,513}, - {132,5,33},{140,5,8193},{130,5,9},{138,5,2049},{134,5,129}, - {142,5,32769},{128,5,2},{135,5,385},{131,5,25},{139,5,6145}, - {129,5,7},{137,5,1537},{133,5,97},{141,5,24577},{128,5,4}, - {136,5,769},{132,5,49},{140,5,12289},{130,5,13},{138,5,3073}, - {134,5,193},{142,5,49153} - }; diff --git a/deps/zlib/contrib/infback9/inflate9.h b/deps/zlib/contrib/infback9/inflate9.h deleted file mode 100644 index ee9a79394b6dc9..00000000000000 --- a/deps/zlib/contrib/infback9/inflate9.h +++ /dev/null @@ -1,47 +0,0 @@ -/* inflate9.h -- internal inflate state definition - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Possible inflate modes between inflate() calls */ -typedef enum { - TYPE, /* i: waiting for type bits, including last-flag bit */ - STORED, /* i: waiting for stored size (length and complement) */ - TABLE, /* i: waiting for dynamic block table lengths */ - LEN, /* i: waiting for length/lit code */ - DONE, /* finished check, done -- remain here until reset */ - BAD /* got a data error -- remain here until reset */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to the BAD mode -- not shown for clarity) - - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or DONE - STORED -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LEN or TYPE - */ - -/* state maintained between inflate() calls. Approximately 7K bytes. */ -struct inflate_state { - /* sliding window */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ -}; diff --git a/deps/zlib/contrib/infback9/inftree9.c b/deps/zlib/contrib/infback9/inftree9.c deleted file mode 100644 index 5f4a76798d8847..00000000000000 --- a/deps/zlib/contrib/infback9/inftree9.c +++ /dev/null @@ -1,324 +0,0 @@ -/* inftree9.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2017 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftree9.h" - -#define MAXBITS 15 - -const char inflate9_copyright[] = - " inflate9 1.2.11 Copyright 1995-2017 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int inflate_table9(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* 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, 3, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, - 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132, - 133, 133, 133, 133, 144, 77, 202}; - static const unsigned short dbase[32] = { /* Distance codes 0..31 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, 32769, 49153}; - static const unsigned short dext[32] = { /* Distance codes 0..31 extra */ - 128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132, - 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, - 139, 139, 140, 140, 141, 141, 142, 142}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) return -1; /* no codes! */ - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftree9.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += 1U << curr; - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - curr = root; - this.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = this; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} diff --git a/deps/zlib/contrib/infback9/inftree9.h b/deps/zlib/contrib/infback9/inftree9.h deleted file mode 100644 index 5ab21f0c6d1120..00000000000000 --- a/deps/zlib/contrib/infback9/inftree9.h +++ /dev/null @@ -1,61 +0,0 @@ -/* inftree9.h -- header to use inftree9.c - * Copyright (C) 1995-2008 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 100eeeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of the dynamic table. The maximum number of code structures is - 1446, which is the sum of 852 for literal/length codes and 594 for distance - codes. These values were found by exhaustive searches using the program - examples/enough.c found in the zlib distribtution. The arguments to that - program are the number of symbols, the initial root table size, and the - maximum bit length of a code. "enough 286 9 15" for literal/length codes - returns returns 852, and "enough 32 6 15" for distance codes returns 594. - The initial root table size (9 or 6) is found in the fifth argument of the - inflate_table() calls in infback9.c. If the root table size is changed, - then these maximum sizes would be need to be recalculated and updated. */ -#define ENOUGH_LENS 852 -#define ENOUGH_DISTS 594 -#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) - -/* Type of code to build for inflate_table9() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -extern int inflate_table9 OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); diff --git a/deps/zlib/contrib/inflate86/inffas86.c b/deps/zlib/contrib/inflate86/inffas86.c deleted file mode 100644 index 7292f67b753795..00000000000000 --- a/deps/zlib/contrib/inflate86/inffas86.c +++ /dev/null @@ -1,1157 +0,0 @@ -/* inffas86.c is a hand tuned assembler version of - * - * inffast.c -- fast decoding - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also - * slightly quicker on x86 systems because, instead of using rep movsb to copy - * data, it uses rep movsw, which moves data in 2-byte chunks instead of single - * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates - * from http://fedora.linux.duke.edu/fc1_x86_64 - * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with - * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, - * when decompressing mozilla-source-1.3.tar.gz. - * - * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from - * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at - * the moment. I have successfully compiled and tested this code with gcc2.96, - * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S - * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX - * enabled. I will attempt to merge the MMX code into this version. Newer - * versions of this and inffast.S can be found at - * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* Mark Adler's comments from inffast.c: */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - struct inffast_ar { -/* 64 32 x86 x86_64 */ -/* ar offset register */ -/* 0 0 */ void *esp; /* esp save */ -/* 8 4 */ void *ebp; /* ebp save */ -/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ -/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ -/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ -/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ -/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ -/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ -/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ -/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ -/* 80 40 */ unsigned long hold; /* edx rdx local strm->hold */ -/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ -/* 92 48 */ unsigned wsize; /* window size */ -/* 96 52 */ unsigned write; /* window write index */ -/*100 56 */ unsigned lmask; /* r12 mask for lcode */ -/*104 60 */ unsigned dmask; /* r13 mask for dcode */ -/*108 64 */ unsigned len; /* r14 match length */ -/*112 68 */ unsigned dist; /* r15 match distance */ -/*116 72 */ unsigned status; /* set when state chng*/ - } ar; - -#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) -#define PAD_AVAIL_IN 6 -#define PAD_AVAIL_OUT 258 -#else -#define PAD_AVAIL_IN 5 -#define PAD_AVAIL_OUT 257 -#endif - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - ar.in = strm->next_in; - ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); - ar.out = strm->next_out; - ar.beg = ar.out - (start - strm->avail_out); - ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); - ar.wsize = state->wsize; - ar.write = state->wnext; - ar.window = state->window; - ar.hold = state->hold; - ar.bits = state->bits; - ar.lcode = state->lencode; - ar.dcode = state->distcode; - ar.lmask = (1U << state->lenbits) - 1; - ar.dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - /* align in on 1/2 hold size boundary */ - while (((unsigned long)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { - ar.hold += (unsigned long)*ar.in++ << ar.bits; - ar.bits += 8; - } - -#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) - __asm__ __volatile__ ( -" leaq %0, %%rax\n" -" movq %%rbp, 8(%%rax)\n" /* save regs rbp and rsp */ -" movq %%rsp, (%%rax)\n" -" movq %%rax, %%rsp\n" /* make rsp point to &ar */ -" movq 16(%%rsp), %%rsi\n" /* rsi = in */ -" movq 32(%%rsp), %%rdi\n" /* rdi = out */ -" movq 24(%%rsp), %%r9\n" /* r9 = last */ -" movq 48(%%rsp), %%r10\n" /* r10 = end */ -" movq 64(%%rsp), %%rbp\n" /* rbp = lcode */ -" movq 72(%%rsp), %%r11\n" /* r11 = dcode */ -" movq 80(%%rsp), %%rdx\n" /* rdx = hold */ -" movl 88(%%rsp), %%ebx\n" /* ebx = bits */ -" movl 100(%%rsp), %%r12d\n" /* r12d = lmask */ -" movl 104(%%rsp), %%r13d\n" /* r13d = dmask */ - /* r14d = len */ - /* r15d = dist */ -" cld\n" -" cmpq %%rdi, %%r10\n" -" je .L_one_time\n" /* if only one decode left */ -" cmpq %%rsi, %%r9\n" -" je .L_one_time\n" -" jmp .L_do_loop\n" - -".L_one_time:\n" -" movq %%r12, %%r8\n" /* r8 = lmask */ -" cmpb $32, %%bl\n" -" ja .L_get_length_code_one_time\n" - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ -" jmp .L_get_length_code_one_time\n" - -".align 32,0x90\n" -".L_while_test:\n" -" cmpq %%rdi, %%r10\n" -" jbe .L_break_loop\n" -" cmpq %%rsi, %%r9\n" -" jbe .L_break_loop\n" - -".L_do_loop:\n" -" movq %%r12, %%r8\n" /* r8 = lmask */ -" cmpb $32, %%bl\n" -" ja .L_get_length_code\n" /* if (32 < bits) */ - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ - -".L_get_length_code:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" movq %%r12, %%r8\n" /* r8 = lmask */ -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" - -".L_get_length_code_one_time:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -".L_dolen:\n" -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_length_base:\n" -" movl %%eax, %%r14d\n" /* len = this */ -" shrl $16, %%r14d\n" /* len = this.val */ -" movb %%al, %%cl\n" - -" testb $16, %%al\n" -" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_decode_distance\n" /* if (!op) */ - -".L_add_bits_to_len:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrq %%cl, %%rdx\n" -" addl %%eax, %%r14d\n" /* len += hold & mask[op] */ - -".L_decode_distance:\n" -" movq %%r13, %%r8\n" /* r8 = dmask */ -" cmpb $32, %%bl\n" -" ja .L_get_distance_code\n" /* if (32 < bits) */ - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ - -".L_get_distance_code:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%r11,%%r8,4), %%eax\n" /* eax = dcode[hold & dmask] */ - -".L_dodist:\n" -" movl %%eax, %%r15d\n" /* dist = this */ -" shrl $16, %%r15d\n" /* dist = this.val */ -" movb %%ah, %%cl\n" -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ -" movb %%al, %%cl\n" /* cl = this.op */ - -" testb $16, %%al\n" /* if ((op & 16) == 0) */ -" jz .L_test_for_second_level_dist\n" -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_check_dist_one\n" - -".L_add_bits_to_dist:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" /* (1 << op) - 1 */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrq %%cl, %%rdx\n" -" addl %%eax, %%r15d\n" /* dist += hold & ((1 << op) - 1) */ - -".L_check_window:\n" -" movq %%rsi, %%r8\n" /* save in so from can use it's reg */ -" movq %%rdi, %%rax\n" -" subq 40(%%rsp), %%rax\n" /* nbytes = out - beg */ - -" cmpl %%r15d, %%eax\n" -" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ - -" movl %%r14d, %%ecx\n" /* ecx = len */ -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ - -" sarl %%ecx\n" -" jnc .L_copy_two\n" /* if len % 2 == 0 */ - -" rep movsw\n" -" movb (%%rsi), %%al\n" -" movb %%al, (%%rdi)\n" -" incq %%rdi\n" - -" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ -" jmp .L_while_test\n" - -".L_copy_two:\n" -" rep movsw\n" -" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_check_dist_one:\n" -" cmpl $1, %%r15d\n" /* if dist 1, is a memset */ -" jne .L_check_window\n" -" cmpq %%rdi, 40(%%rsp)\n" /* if out == beg, outside window */ -" je .L_check_window\n" - -" movl %%r14d, %%ecx\n" /* ecx = len */ -" movb -1(%%rdi), %%al\n" -" movb %%al, %%ah\n" - -" sarl %%ecx\n" -" jnc .L_set_two\n" -" movb %%al, (%%rdi)\n" -" incq %%rdi\n" - -".L_set_two:\n" -" rep stosw\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_second_level_length:\n" -" testb $64, %%al\n" -" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%r14d, %%eax\n" /* eax += len */ -" movl (%%rbp,%%rax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ -" jmp .L_dolen\n" - -".align 32,0x90\n" -".L_test_for_second_level_dist:\n" -" testb $64, %%al\n" -" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%r15d, %%eax\n" /* eax += dist */ -" movl (%%r11,%%rax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ -" jmp .L_dodist\n" - -".align 32,0x90\n" -".L_clip_window:\n" -" movl %%eax, %%ecx\n" /* ecx = nbytes */ -" movl 92(%%rsp), %%eax\n" /* eax = wsize, prepare for dist cmp */ -" negl %%ecx\n" /* nbytes = -nbytes */ - -" cmpl %%r15d, %%eax\n" -" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ - -" addl %%r15d, %%ecx\n" /* nbytes = dist - nbytes */ -" cmpl $0, 96(%%rsp)\n" -" jne .L_wrap_around_window\n" /* if (write != 0) */ - -" movq 56(%%rsp), %%rsi\n" /* from = window */ -" subl %%ecx, %%eax\n" /* eax -= nbytes */ -" addq %%rax, %%rsi\n" /* from += wsize - nbytes */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%r14d\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* eax -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = &out[ -dist ] */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_wrap_around_window:\n" -" movl 96(%%rsp), %%eax\n" /* eax = write */ -" cmpl %%eax, %%ecx\n" -" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ - -" movl 92(%%rsp), %%esi\n" /* from = wsize */ -" addq 56(%%rsp), %%rsi\n" /* from += window */ -" addq %%rax, %%rsi\n" /* from += write */ -" subq %%rcx, %%rsi\n" /* from -= nbytes */ -" subl %%eax, %%ecx\n" /* nbytes -= write */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq 56(%%rsp), %%rsi\n" /* from = window */ -" movl 96(%%rsp), %%ecx\n" /* nbytes = write */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_contiguous_in_window:\n" -" movq 56(%%rsp), %%rsi\n" /* rsi = window */ -" addq %%rax, %%rsi\n" -" subq %%rcx, %%rsi\n" /* from += write - nbytes */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ -" jmp .L_do_copy\n" /* if (nbytes >= len) */ - -".align 32,0x90\n" -".L_do_copy:\n" -" movl %%eax, %%ecx\n" /* ecx = len */ -" rep movsb\n" - -" movq %%r8, %%rsi\n" /* move in back to %esi, toss from */ -" jmp .L_while_test\n" - -".L_test_for_end_of_block:\n" -" testb $32, %%al\n" -" jz .L_invalid_literal_length_code\n" -" movl $1, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_literal_length_code:\n" -" movl $2, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_code:\n" -" movl $3, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_too_far:\n" -" movl $4, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_break_loop:\n" -" movl $0, 116(%%rsp)\n" - -".L_break_loop_with_status:\n" -/* put in, out, bits, and hold back into ar and pop esp */ -" movq %%rsi, 16(%%rsp)\n" /* in */ -" movq %%rdi, 32(%%rsp)\n" /* out */ -" movl %%ebx, 88(%%rsp)\n" /* bits */ -" movq %%rdx, 80(%%rsp)\n" /* hold */ -" movq (%%rsp), %%rax\n" /* restore rbp and rsp */ -" movq 8(%%rsp), %%rbp\n" -" movq %%rax, %%rsp\n" - : - : "m" (ar) - : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", - "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" - ); -#elif ( defined( __GNUC__ ) || defined( __ICC ) ) && defined( __i386 ) - __asm__ __volatile__ ( -" leal %0, %%eax\n" -" movl %%esp, (%%eax)\n" /* save esp, ebp */ -" movl %%ebp, 4(%%eax)\n" -" movl %%eax, %%esp\n" -" movl 8(%%esp), %%esi\n" /* esi = in */ -" movl 16(%%esp), %%edi\n" /* edi = out */ -" movl 40(%%esp), %%edx\n" /* edx = hold */ -" movl 44(%%esp), %%ebx\n" /* ebx = bits */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ - -" cld\n" -" jmp .L_do_loop\n" - -".align 32,0x90\n" -".L_while_test:\n" -" cmpl %%edi, 24(%%esp)\n" /* out < end */ -" jbe .L_break_loop\n" -" cmpl %%esi, 12(%%esp)\n" /* in < last */ -" jbe .L_break_loop\n" - -".L_do_loop:\n" -" cmpb $15, %%bl\n" -" ja .L_get_length_code\n" /* if (15 < bits) */ - -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ - -".L_get_length_code:\n" -" movl 56(%%esp), %%eax\n" /* eax = lmask */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -".L_dolen:\n" -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrl %%cl, %%edx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_length_base:\n" -" movl %%eax, %%ecx\n" /* len = this */ -" shrl $16, %%ecx\n" /* len = this.val */ -" movl %%ecx, 64(%%esp)\n" /* save len */ -" movb %%al, %%cl\n" - -" testb $16, %%al\n" -" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_decode_distance\n" /* if (!op) */ -" cmpb %%cl, %%bl\n" -" jae .L_add_bits_to_len\n" /* if (op <= bits) */ - -" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ -" movb %%ch, %%cl\n" /* move op back to ecx */ - -".L_add_bits_to_len:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrl %%cl, %%edx\n" -" addl %%eax, 64(%%esp)\n" /* len += hold & mask[op] */ - -".L_decode_distance:\n" -" cmpb $15, %%bl\n" -" ja .L_get_distance_code\n" /* if (15 < bits) */ - -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ - -".L_get_distance_code:\n" -" movl 60(%%esp), %%eax\n" /* eax = dmask */ -" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" movl (%%ecx,%%eax,4), %%eax\n"/* eax = dcode[hold & dmask] */ - -".L_dodist:\n" -" movl %%eax, %%ebp\n" /* dist = this */ -" shrl $16, %%ebp\n" /* dist = this.val */ -" movb %%ah, %%cl\n" -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrl %%cl, %%edx\n" /* hold >>= this.bits */ -" movb %%al, %%cl\n" /* cl = this.op */ - -" testb $16, %%al\n" /* if ((op & 16) == 0) */ -" jz .L_test_for_second_level_dist\n" -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_check_dist_one\n" -" cmpb %%cl, %%bl\n" -" jae .L_add_bits_to_dist\n" /* if (op <= bits) 97.6% */ - -" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ -" movb %%ch, %%cl\n" /* move op back to ecx */ - -".L_add_bits_to_dist:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" /* (1 << op) - 1 */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrl %%cl, %%edx\n" -" addl %%eax, %%ebp\n" /* dist += hold & ((1 << op) - 1) */ - -".L_check_window:\n" -" movl %%esi, 8(%%esp)\n" /* save in so from can use it's reg */ -" movl %%edi, %%eax\n" -" subl 20(%%esp), %%eax\n" /* nbytes = out - beg */ - -" cmpl %%ebp, %%eax\n" -" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ - -" movl 64(%%esp), %%ecx\n" /* ecx = len */ -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ - -" sarl %%ecx\n" -" jnc .L_copy_two\n" /* if len % 2 == 0 */ - -" rep movsw\n" -" movb (%%esi), %%al\n" -" movb %%al, (%%edi)\n" -" incl %%edi\n" - -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".L_copy_two:\n" -" rep movsw\n" -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_check_dist_one:\n" -" cmpl $1, %%ebp\n" /* if dist 1, is a memset */ -" jne .L_check_window\n" -" cmpl %%edi, 20(%%esp)\n" -" je .L_check_window\n" /* out == beg, if outside window */ - -" movl 64(%%esp), %%ecx\n" /* ecx = len */ -" movb -1(%%edi), %%al\n" -" movb %%al, %%ah\n" - -" sarl %%ecx\n" -" jnc .L_set_two\n" -" movb %%al, (%%edi)\n" -" incl %%edi\n" - -".L_set_two:\n" -" rep stosw\n" -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_second_level_length:\n" -" testb $64, %%al\n" -" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl 64(%%esp), %%eax\n" /* eax += len */ -" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ -" jmp .L_dolen\n" - -".align 32,0x90\n" -".L_test_for_second_level_dist:\n" -" testb $64, %%al\n" -" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%ebp, %%eax\n" /* eax += dist */ -" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ -" movl (%%ecx,%%eax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ -" jmp .L_dodist\n" - -".align 32,0x90\n" -".L_clip_window:\n" -" movl %%eax, %%ecx\n" -" movl 48(%%esp), %%eax\n" /* eax = wsize */ -" negl %%ecx\n" /* nbytes = -nbytes */ -" movl 28(%%esp), %%esi\n" /* from = window */ - -" cmpl %%ebp, %%eax\n" -" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ - -" addl %%ebp, %%ecx\n" /* nbytes = dist - nbytes */ -" cmpl $0, 52(%%esp)\n" -" jne .L_wrap_around_window\n" /* if (write != 0) */ - -" subl %%ecx, %%eax\n" -" addl %%eax, %%esi\n" /* from += wsize - nbytes */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_wrap_around_window:\n" -" movl 52(%%esp), %%eax\n" /* eax = write */ -" cmpl %%eax, %%ecx\n" -" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ - -" addl 48(%%esp), %%esi\n" /* from += wsize */ -" addl %%eax, %%esi\n" /* from += write */ -" subl %%ecx, %%esi\n" /* from -= nbytes */ -" subl %%eax, %%ecx\n" /* nbytes -= write */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl 28(%%esp), %%esi\n" /* from = window */ -" movl 52(%%esp), %%ecx\n" /* nbytes = write */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_contiguous_in_window:\n" -" addl %%eax, %%esi\n" -" subl %%ecx, %%esi\n" /* from += write - nbytes */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" /* if (nbytes >= len) */ - -".align 32,0x90\n" -".L_do_copy:\n" -" movl %%eax, %%ecx\n" -" rep movsb\n" - -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".L_test_for_end_of_block:\n" -" testb $32, %%al\n" -" jz .L_invalid_literal_length_code\n" -" movl $1, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_literal_length_code:\n" -" movl $2, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_code:\n" -" movl $3, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_too_far:\n" -" movl 8(%%esp), %%esi\n" -" movl $4, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_break_loop:\n" -" movl $0, 72(%%esp)\n" - -".L_break_loop_with_status:\n" -/* put in, out, bits, and hold back into ar and pop esp */ -" movl %%esi, 8(%%esp)\n" /* save in */ -" movl %%edi, 16(%%esp)\n" /* save out */ -" movl %%ebx, 44(%%esp)\n" /* save bits */ -" movl %%edx, 40(%%esp)\n" /* save hold */ -" movl 4(%%esp), %%ebp\n" /* restore esp, ebp */ -" movl (%%esp), %%esp\n" - : - : "m" (ar) - : "memory", "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi" - ); -#elif defined( _MSC_VER ) && ! defined( _M_AMD64 ) - __asm { - lea eax, ar - mov [eax], esp /* save esp, ebp */ - mov [eax+4], ebp - mov esp, eax - mov esi, [esp+8] /* esi = in */ - mov edi, [esp+16] /* edi = out */ - mov edx, [esp+40] /* edx = hold */ - mov ebx, [esp+44] /* ebx = bits */ - mov ebp, [esp+32] /* ebp = lcode */ - - cld - jmp L_do_loop - -ALIGN 4 -L_while_test: - cmp [esp+24], edi - jbe L_break_loop - cmp [esp+12], esi - jbe L_break_loop - -L_do_loop: - cmp bl, 15 - ja L_get_length_code /* if (15 < bits) */ - - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - -L_get_length_code: - mov eax, [esp+56] /* eax = lmask */ - and eax, edx /* eax &= hold */ - mov eax, [ebp+eax*4] /* eax = lcode[hold & lmask] */ - -L_dolen: - mov cl, ah /* cl = this.bits */ - sub bl, ah /* bits -= this.bits */ - shr edx, cl /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base /* if (op != 0) 45.7% */ - - shr eax, 16 /* output this.val char */ - stosb - jmp L_while_test - -ALIGN 4 -L_test_for_length_base: - mov ecx, eax /* len = this */ - shr ecx, 16 /* len = this.val */ - mov [esp+64], ecx /* save len */ - mov cl, al - - test al, 16 - jz L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ - and cl, 15 /* op &= 15 */ - jz L_decode_distance /* if (!op) */ - cmp bl, cl - jae L_add_bits_to_len /* if (op <= bits) */ - - mov ch, cl /* stash op in ch, freeing cl */ - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - mov cl, ch /* move op back to ecx */ - -L_add_bits_to_len: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - shr edx, cl - add [esp+64], eax /* len += hold & mask[op] */ - -L_decode_distance: - cmp bl, 15 - ja L_get_distance_code /* if (15 < bits) */ - - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - -L_get_distance_code: - mov eax, [esp+60] /* eax = dmask */ - mov ecx, [esp+36] /* ecx = dcode */ - and eax, edx /* eax &= hold */ - mov eax, [ecx+eax*4]/* eax = dcode[hold & dmask] */ - -L_dodist: - mov ebp, eax /* dist = this */ - shr ebp, 16 /* dist = this.val */ - mov cl, ah - sub bl, ah /* bits -= this.bits */ - shr edx, cl /* hold >>= this.bits */ - mov cl, al /* cl = this.op */ - - test al, 16 /* if ((op & 16) == 0) */ - jz L_test_for_second_level_dist - and cl, 15 /* op &= 15 */ - jz L_check_dist_one - cmp bl, cl - jae L_add_bits_to_dist /* if (op <= bits) 97.6% */ - - mov ch, cl /* stash op in ch, freeing cl */ - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - mov cl, ch /* move op back to ecx */ - -L_add_bits_to_dist: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax /* (1 << op) - 1 */ - and eax, edx /* eax &= hold */ - shr edx, cl - add ebp, eax /* dist += hold & ((1 << op) - 1) */ - -L_check_window: - mov [esp+8], esi /* save in so from can use it's reg */ - mov eax, edi - sub eax, [esp+20] /* nbytes = out - beg */ - - cmp eax, ebp - jb L_clip_window /* if (dist > nbytes) 4.2% */ - - mov ecx, [esp+64] /* ecx = len */ - mov esi, edi - sub esi, ebp /* from = out - dist */ - - sar ecx, 1 - jnc L_copy_two - - rep movsw - mov al, [esi] - mov [edi], al - inc edi - - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -L_copy_two: - rep movsw - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp ebp, 1 /* if dist 1, is a memset */ - jne L_check_window - cmp [esp+20], edi - je L_check_window /* out == beg, if outside window */ - - mov ecx, [esp+64] /* ecx = len */ - mov al, [edi-1] - mov ah, al - - sar ecx, 1 - jnc L_set_two - mov [edi], al /* memset out with from[-1] */ - inc edi - -L_set_two: - rep stosw - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - test al, 64 - jnz L_test_for_end_of_block /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - add eax, [esp+64] /* eax += len */ - mov eax, [ebp+eax*4] /* eax = lcode[val+(hold&mask[op])]*/ - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - test al, 64 - jnz L_invalid_distance_code /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - add eax, ebp /* eax += dist */ - mov ecx, [esp+36] /* ecx = dcode */ - mov eax, [ecx+eax*4] /* eax = dcode[val+(hold&mask[op])]*/ - jmp L_dodist - -ALIGN 4 -L_clip_window: - mov ecx, eax - mov eax, [esp+48] /* eax = wsize */ - neg ecx /* nbytes = -nbytes */ - mov esi, [esp+28] /* from = window */ - - cmp eax, ebp - jb L_invalid_distance_too_far /* if (dist > wsize) */ - - add ecx, ebp /* nbytes = dist - nbytes */ - cmp dword ptr [esp+52], 0 - jne L_wrap_around_window /* if (write != 0) */ - - sub eax, ecx - add esi, eax /* from += wsize - nbytes */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_wrap_around_window: - mov eax, [esp+52] /* eax = write */ - cmp ecx, eax - jbe L_contiguous_in_window /* if (write >= nbytes) */ - - add esi, [esp+48] /* from += wsize */ - add esi, eax /* from += write */ - sub esi, ecx /* from -= nbytes */ - sub ecx, eax /* nbytes -= write */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, [esp+28] /* from = window */ - mov ecx, [esp+52] /* nbytes = write */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_contiguous_in_window: - add esi, eax - sub esi, ecx /* from += write - nbytes */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_do_copy: - mov ecx, eax - rep movsb - - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -L_test_for_end_of_block: - test al, 32 - jz L_invalid_literal_length_code - mov dword ptr [esp+72], 1 - jmp L_break_loop_with_status - -L_invalid_literal_length_code: - mov dword ptr [esp+72], 2 - jmp L_break_loop_with_status - -L_invalid_distance_code: - mov dword ptr [esp+72], 3 - jmp L_break_loop_with_status - -L_invalid_distance_too_far: - mov esi, [esp+4] - mov dword ptr [esp+72], 4 - jmp L_break_loop_with_status - -L_break_loop: - mov dword ptr [esp+72], 0 - -L_break_loop_with_status: -/* put in, out, bits, and hold back into ar and pop esp */ - mov [esp+8], esi /* save in */ - mov [esp+16], edi /* save out */ - mov [esp+44], ebx /* save bits */ - mov [esp+40], edx /* save hold */ - mov ebp, [esp+4] /* restore esp, ebp */ - mov esp, [esp] - } -#else -#error "x86 architecture not defined" -#endif - - if (ar.status > 1) { - if (ar.status == 2) - strm->msg = "invalid literal/length code"; - else if (ar.status == 3) - strm->msg = "invalid distance code"; - else - strm->msg = "invalid distance too far back"; - state->mode = BAD; - } - else if ( ar.status == 1 ) { - state->mode = TYPE; - } - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - ar.len = ar.bits >> 3; - ar.in -= ar.len; - ar.bits -= ar.len << 3; - ar.hold &= (1U << ar.bits) - 1; - - /* update state and return */ - strm->next_in = ar.in; - strm->next_out = ar.out; - strm->avail_in = (unsigned)(ar.in < ar.last ? - PAD_AVAIL_IN + (ar.last - ar.in) : - PAD_AVAIL_IN - (ar.in - ar.last)); - strm->avail_out = (unsigned)(ar.out < ar.end ? - PAD_AVAIL_OUT + (ar.end - ar.out) : - PAD_AVAIL_OUT - (ar.out - ar.end)); - state->hold = ar.hold; - state->bits = ar.bits; - return; -} - diff --git a/deps/zlib/contrib/inflate86/inffast.S b/deps/zlib/contrib/inflate86/inffast.S deleted file mode 100644 index 2245a2905bdf53..00000000000000 --- a/deps/zlib/contrib/inflate86/inffast.S +++ /dev/null @@ -1,1368 +0,0 @@ -/* - * inffast.S is a hand tuned assembler version of: - * - * inffast.c -- fast decoding - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * This version (Jan-23-2003) of inflate_fast was coded and tested under - * GNU/Linux on a pentium 3, using the gcc-3.2 compiler distribution. On that - * machine, I found that gzip style archives decompressed about 20% faster than - * the gcc-3.2 -O3 -fomit-frame-pointer compiled version. Your results will - * depend on how large of a buffer is used for z_stream.next_in & next_out - * (8K-32K worked best for my 256K cpu cache) and how much overhead there is in - * stream processing I/O and crc32/addler32. In my case, this routine used - * 70% of the cpu time and crc32 used 20%. - * - * I am confident that this version will work in the general case, but I have - * not tested a wide variety of datasets or a wide variety of platforms. - * - * Jan-24-2003 -- Added -DUSE_MMX define for slightly faster inflating. - * It should be a runtime flag instead of compile time flag... - * - * Jan-26-2003 -- Added runtime check for MMX support with cpuid instruction. - * With -DUSE_MMX, only MMX code is compiled. With -DNO_MMX, only non-MMX code - * is compiled. Without either option, runtime detection is enabled. Runtime - * detection should work on all modern cpus and the recomended algorithm (flip - * ID bit on eflags and then use the cpuid instruction) is used in many - * multimedia applications. Tested under win2k with gcc-2.95 and gas-2.12 - * distributed with cygwin3. Compiling with gcc-2.95 -c inffast.S -o - * inffast.obj generates a COFF object which can then be linked with MSVC++ - * compiled code. Tested under FreeBSD 4.7 with gcc-2.95. - * - * Jan-28-2003 -- Tested Athlon XP... MMX mode is slower than no MMX (and - * slower than compiler generated code). Adjusted cpuid check to use the MMX - * code only for Pentiums < P4 until I have more data on the P4. Speed - * improvment is only about 15% on the Athlon when compared with code generated - * with MSVC++. Not sure yet, but I think the P4 will also be slower using the - * MMX mode because many of it's x86 ALU instructions execute in .5 cycles and - * have less latency than MMX ops. Added code to buffer the last 11 bytes of - * the input stream since the MMX code grabs bits in chunks of 32, which - * differs from the inffast.c algorithm. I don't think there would have been - * read overruns where a page boundary was crossed (a segfault), but there - * could have been overruns when next_in ends on unaligned memory (unintialized - * memory read). - * - * Mar-13-2003 -- P4 MMX is slightly slower than P4 NO_MMX. I created a C - * version of the non-MMX code so that it doesn't depend on zstrm and zstate - * structure offsets which are hard coded in this file. This was last tested - * with zlib-1.2.0 which is currently in beta testing, newer versions of this - * and inffas86.c can be found at http://www.eetbeetee.com/zlib/ and - * http://www.charm.net/~christop/zlib/ - */ - - -/* - * if you have underscore linking problems (_inflate_fast undefined), try - * using -DGAS_COFF - */ -#if ! defined( GAS_COFF ) && ! defined( GAS_ELF ) - -#if defined( WIN32 ) || defined( __CYGWIN__ ) -#define GAS_COFF /* windows object format */ -#else -#define GAS_ELF -#endif - -#endif /* ! GAS_COFF && ! GAS_ELF */ - - -#if defined( GAS_COFF ) - -/* coff externals have underscores */ -#define inflate_fast _inflate_fast -#define inflate_fast_use_mmx _inflate_fast_use_mmx - -#endif /* GAS_COFF */ - - -.file "inffast.S" - -.globl inflate_fast - -.text -.align 4,0 -.L_invalid_literal_length_code_msg: -.string "invalid literal/length code" - -.align 4,0 -.L_invalid_distance_code_msg: -.string "invalid distance code" - -.align 4,0 -.L_invalid_distance_too_far_msg: -.string "invalid distance too far back" - -#if ! defined( NO_MMX ) -.align 4,0 -.L_mask: /* mask[N] = ( 1 << N ) - 1 */ -.long 0 -.long 1 -.long 3 -.long 7 -.long 15 -.long 31 -.long 63 -.long 127 -.long 255 -.long 511 -.long 1023 -.long 2047 -.long 4095 -.long 8191 -.long 16383 -.long 32767 -.long 65535 -.long 131071 -.long 262143 -.long 524287 -.long 1048575 -.long 2097151 -.long 4194303 -.long 8388607 -.long 16777215 -.long 33554431 -.long 67108863 -.long 134217727 -.long 268435455 -.long 536870911 -.long 1073741823 -.long 2147483647 -.long 4294967295 -#endif /* NO_MMX */ - -.text - -/* - * struct z_stream offsets, in zlib.h - */ -#define next_in_strm 0 /* strm->next_in */ -#define avail_in_strm 4 /* strm->avail_in */ -#define next_out_strm 12 /* strm->next_out */ -#define avail_out_strm 16 /* strm->avail_out */ -#define msg_strm 24 /* strm->msg */ -#define state_strm 28 /* strm->state */ - -/* - * struct inflate_state offsets, in inflate.h - */ -#define mode_state 0 /* state->mode */ -#define wsize_state 32 /* state->wsize */ -#define write_state 40 /* state->write */ -#define window_state 44 /* state->window */ -#define hold_state 48 /* state->hold */ -#define bits_state 52 /* state->bits */ -#define lencode_state 68 /* state->lencode */ -#define distcode_state 72 /* state->distcode */ -#define lenbits_state 76 /* state->lenbits */ -#define distbits_state 80 /* state->distbits */ - -/* - * inflate_fast's activation record - */ -#define local_var_size 64 /* how much local space for vars */ -#define strm_sp 88 /* first arg: z_stream * (local_var_size + 24) */ -#define start_sp 92 /* second arg: unsigned int (local_var_size + 28) */ - -/* - * offsets for local vars on stack - */ -#define out 60 /* unsigned char* */ -#define window 56 /* unsigned char* */ -#define wsize 52 /* unsigned int */ -#define write 48 /* unsigned int */ -#define in 44 /* unsigned char* */ -#define beg 40 /* unsigned char* */ -#define buf 28 /* char[ 12 ] */ -#define len 24 /* unsigned int */ -#define last 20 /* unsigned char* */ -#define end 16 /* unsigned char* */ -#define dcode 12 /* code* */ -#define lcode 8 /* code* */ -#define dmask 4 /* unsigned int */ -#define lmask 0 /* unsigned int */ - -/* - * typedef enum inflate_mode consts, in inflate.h - */ -#define INFLATE_MODE_TYPE 11 /* state->mode flags enum-ed in inflate.h */ -#define INFLATE_MODE_BAD 26 - - -#if ! defined( USE_MMX ) && ! defined( NO_MMX ) - -#define RUN_TIME_MMX - -#define CHECK_MMX 1 -#define DO_USE_MMX 2 -#define DONT_USE_MMX 3 - -.globl inflate_fast_use_mmx - -.data - -.align 4,0 -inflate_fast_use_mmx: /* integer flag for run time control 1=check,2=mmx,3=no */ -.long CHECK_MMX - -#if defined( GAS_ELF ) -/* elf info */ -.type inflate_fast_use_mmx,@object -.size inflate_fast_use_mmx,4 -#endif - -#endif /* RUN_TIME_MMX */ - -#if defined( GAS_COFF ) -/* coff info: scl 2 = extern, type 32 = function */ -.def inflate_fast; .scl 2; .type 32; .endef -#endif - -.text - -.align 32,0x90 -inflate_fast: - pushl %edi - pushl %esi - pushl %ebp - pushl %ebx - pushf /* save eflags (strm_sp, state_sp assumes this is 32 bits) */ - subl $local_var_size, %esp - cld - -#define strm_r %esi -#define state_r %edi - - movl strm_sp(%esp), strm_r - movl state_strm(strm_r), state_r - - /* in = strm->next_in; - * out = strm->next_out; - * last = in + strm->avail_in - 11; - * beg = out - (start - strm->avail_out); - * end = out + (strm->avail_out - 257); - */ - movl avail_in_strm(strm_r), %edx - movl next_in_strm(strm_r), %eax - - addl %eax, %edx /* avail_in += next_in */ - subl $11, %edx /* avail_in -= 11 */ - - movl %eax, in(%esp) - movl %edx, last(%esp) - - movl start_sp(%esp), %ebp - movl avail_out_strm(strm_r), %ecx - movl next_out_strm(strm_r), %ebx - - subl %ecx, %ebp /* start -= avail_out */ - negl %ebp /* start = -start */ - addl %ebx, %ebp /* start += next_out */ - - subl $257, %ecx /* avail_out -= 257 */ - addl %ebx, %ecx /* avail_out += out */ - - movl %ebx, out(%esp) - movl %ebp, beg(%esp) - movl %ecx, end(%esp) - - /* wsize = state->wsize; - * write = state->write; - * window = state->window; - * hold = state->hold; - * bits = state->bits; - * lcode = state->lencode; - * dcode = state->distcode; - * lmask = ( 1 << state->lenbits ) - 1; - * dmask = ( 1 << state->distbits ) - 1; - */ - - movl lencode_state(state_r), %eax - movl distcode_state(state_r), %ecx - - movl %eax, lcode(%esp) - movl %ecx, dcode(%esp) - - movl $1, %eax - movl lenbits_state(state_r), %ecx - shll %cl, %eax - decl %eax - movl %eax, lmask(%esp) - - movl $1, %eax - movl distbits_state(state_r), %ecx - shll %cl, %eax - decl %eax - movl %eax, dmask(%esp) - - movl wsize_state(state_r), %eax - movl write_state(state_r), %ecx - movl window_state(state_r), %edx - - movl %eax, wsize(%esp) - movl %ecx, write(%esp) - movl %edx, window(%esp) - - movl hold_state(state_r), %ebp - movl bits_state(state_r), %ebx - -#undef strm_r -#undef state_r - -#define in_r %esi -#define from_r %esi -#define out_r %edi - - movl in(%esp), in_r - movl last(%esp), %ecx - cmpl in_r, %ecx - ja .L_align_long /* if in < last */ - - addl $11, %ecx /* ecx = &in[ avail_in ] */ - subl in_r, %ecx /* ecx = avail_in */ - movl $12, %eax - subl %ecx, %eax /* eax = 12 - avail_in */ - leal buf(%esp), %edi - rep movsb /* memcpy( buf, in, avail_in ) */ - movl %eax, %ecx - xorl %eax, %eax - rep stosb /* memset( &buf[ avail_in ], 0, 12 - avail_in ) */ - leal buf(%esp), in_r /* in = buf */ - movl in_r, last(%esp) /* last = in, do just one iteration */ - jmp .L_is_aligned - - /* align in_r on long boundary */ -.L_align_long: - testl $3, in_r - jz .L_is_aligned - xorl %eax, %eax - movb (in_r), %al - incl in_r - movl %ebx, %ecx - addl $8, %ebx - shll %cl, %eax - orl %eax, %ebp - jmp .L_align_long - -.L_is_aligned: - movl out(%esp), out_r - -#if defined( NO_MMX ) - jmp .L_do_loop -#endif - -#if defined( USE_MMX ) - jmp .L_init_mmx -#endif - -/*** Runtime MMX check ***/ - -#if defined( RUN_TIME_MMX ) -.L_check_mmx: - cmpl $DO_USE_MMX, inflate_fast_use_mmx - je .L_init_mmx - ja .L_do_loop /* > 2 */ - - pushl %eax - pushl %ebx - pushl %ecx - pushl %edx - pushf - movl (%esp), %eax /* copy eflags to eax */ - xorl $0x200000, (%esp) /* try toggling ID bit of eflags (bit 21) - * to see if cpu supports cpuid... - * ID bit method not supported by NexGen but - * bios may load a cpuid instruction and - * cpuid may be disabled on Cyrix 5-6x86 */ - popf - pushf - popl %edx /* copy new eflags to edx */ - xorl %eax, %edx /* test if ID bit is flipped */ - jz .L_dont_use_mmx /* not flipped if zero */ - xorl %eax, %eax - cpuid - cmpl $0x756e6547, %ebx /* check for GenuineIntel in ebx,ecx,edx */ - jne .L_dont_use_mmx - cmpl $0x6c65746e, %ecx - jne .L_dont_use_mmx - cmpl $0x49656e69, %edx - jne .L_dont_use_mmx - movl $1, %eax - cpuid /* get cpu features */ - shrl $8, %eax - andl $15, %eax - cmpl $6, %eax /* check for Pentium family, is 0xf for P4 */ - jne .L_dont_use_mmx - testl $0x800000, %edx /* test if MMX feature is set (bit 23) */ - jnz .L_use_mmx - jmp .L_dont_use_mmx -.L_use_mmx: - movl $DO_USE_MMX, inflate_fast_use_mmx - jmp .L_check_mmx_pop -.L_dont_use_mmx: - movl $DONT_USE_MMX, inflate_fast_use_mmx -.L_check_mmx_pop: - popl %edx - popl %ecx - popl %ebx - popl %eax - jmp .L_check_mmx -#endif - - -/*** Non-MMX code ***/ - -#if defined ( NO_MMX ) || defined( RUN_TIME_MMX ) - -#define hold_r %ebp -#define bits_r %bl -#define bitslong_r %ebx - -.align 32,0x90 -.L_while_test: - /* while (in < last && out < end) - */ - cmpl out_r, end(%esp) - jbe .L_break_loop /* if (out >= end) */ - - cmpl in_r, last(%esp) - jbe .L_break_loop - -.L_do_loop: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out - * - * do { - * if (bits < 15) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * this = lcode[hold & lmask] - */ - cmpb $15, bits_r - ja .L_get_length_code /* if (15 < bits) */ - - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - -.L_get_length_code: - movl lmask(%esp), %edx /* edx = lmask */ - movl lcode(%esp), %ecx /* ecx = lcode */ - andl hold_r, %edx /* edx &= hold */ - movl (%ecx,%edx,4), %eax /* eax = lcode[hold & lmask] */ - -.L_dolen: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out - * - * dolen: - * bits -= this.bits; - * hold >>= this.bits - */ - movb %ah, %cl /* cl = this.bits */ - subb %ah, bits_r /* bits -= this.bits */ - shrl %cl, hold_r /* hold >>= this.bits */ - - /* check if op is a literal - * if (op == 0) { - * PUP(out) = this.val; - * } - */ - testb %al, %al - jnz .L_test_for_length_base /* if (op != 0) 45.7% */ - - shrl $16, %eax /* output this.val char */ - stosb - jmp .L_while_test - -.L_test_for_length_base: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = len - * - * else if (op & 16) { - * len = this.val - * op &= 15 - * if (op) { - * if (op > bits) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * len += hold & mask[op]; - * bits -= op; - * hold >>= op; - * } - */ -#define len_r %edx - movl %eax, len_r /* len = this */ - shrl $16, len_r /* len = this.val */ - movb %al, %cl - - testb $16, %al - jz .L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ - andb $15, %cl /* op &= 15 */ - jz .L_save_len /* if (!op) */ - cmpb %cl, bits_r - jae .L_add_bits_to_len /* if (op <= bits) */ - - movb %cl, %ch /* stash op in ch, freeing cl */ - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - movb %ch, %cl /* move op back to ecx */ - -.L_add_bits_to_len: - movl $1, %eax - shll %cl, %eax - decl %eax - subb %cl, bits_r - andl hold_r, %eax /* eax &= hold */ - shrl %cl, hold_r - addl %eax, len_r /* len += hold & mask[op] */ - -.L_save_len: - movl len_r, len(%esp) /* save len */ -#undef len_r - -.L_decode_distance: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * - * if (bits < 15) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * this = dcode[hold & dmask]; - * dodist: - * bits -= this.bits; - * hold >>= this.bits; - * op = this.op; - */ - - cmpb $15, bits_r - ja .L_get_distance_code /* if (15 < bits) */ - - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - -.L_get_distance_code: - movl dmask(%esp), %edx /* edx = dmask */ - movl dcode(%esp), %ecx /* ecx = dcode */ - andl hold_r, %edx /* edx &= hold */ - movl (%ecx,%edx,4), %eax /* eax = dcode[hold & dmask] */ - -#define dist_r %edx -.L_dodist: - movl %eax, dist_r /* dist = this */ - shrl $16, dist_r /* dist = this.val */ - movb %ah, %cl - subb %ah, bits_r /* bits -= this.bits */ - shrl %cl, hold_r /* hold >>= this.bits */ - - /* if (op & 16) { - * dist = this.val - * op &= 15 - * if (op > bits) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * dist += hold & mask[op]; - * bits -= op; - * hold >>= op; - */ - movb %al, %cl /* cl = this.op */ - - testb $16, %al /* if ((op & 16) == 0) */ - jz .L_test_for_second_level_dist - andb $15, %cl /* op &= 15 */ - jz .L_check_dist_one - cmpb %cl, bits_r - jae .L_add_bits_to_dist /* if (op <= bits) 97.6% */ - - movb %cl, %ch /* stash op in ch, freeing cl */ - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - movb %ch, %cl /* move op back to ecx */ - -.L_add_bits_to_dist: - movl $1, %eax - shll %cl, %eax - decl %eax /* (1 << op) - 1 */ - subb %cl, bits_r - andl hold_r, %eax /* eax &= hold */ - shrl %cl, hold_r - addl %eax, dist_r /* dist += hold & ((1 << op) - 1) */ - jmp .L_check_window - -.L_check_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes - * - * nbytes = out - beg; - * if (dist <= nbytes) { - * from = out - dist; - * do { - * PUP(out) = PUP(from); - * } while (--len > 0) { - * } - */ - - movl in_r, in(%esp) /* save in so from can use it's reg */ - movl out_r, %eax - subl beg(%esp), %eax /* nbytes = out - beg */ - - cmpl dist_r, %eax - jb .L_clip_window /* if (dist > nbytes) 4.2% */ - - movl len(%esp), %ecx - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - - subl $3, %ecx - movb (from_r), %al - movb %al, (out_r) - movb 1(from_r), %al - movb 2(from_r), %dl - addl $3, from_r - movb %al, 1(out_r) - movb %dl, 2(out_r) - addl $3, out_r - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - jmp .L_while_test - -.align 16,0x90 -.L_check_dist_one: - cmpl $1, dist_r - jne .L_check_window - cmpl out_r, beg(%esp) - je .L_check_window - - decl out_r - movl len(%esp), %ecx - movb (out_r), %al - subl $3, %ecx - - movb %al, 1(out_r) - movb %al, 2(out_r) - movb %al, 3(out_r) - addl $4, out_r - rep stosb - - jmp .L_while_test - -.align 16,0x90 -.L_test_for_second_level_length: - /* else if ((op & 64) == 0) { - * this = lcode[this.val + (hold & mask[op])]; - * } - */ - testb $64, %al - jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ - - movl $1, %eax - shll %cl, %eax - decl %eax - andl hold_r, %eax /* eax &= hold */ - addl %edx, %eax /* eax += this.val */ - movl lcode(%esp), %edx /* edx = lcode */ - movl (%edx,%eax,4), %eax /* eax = lcode[val + (hold&mask[op])] */ - jmp .L_dolen - -.align 16,0x90 -.L_test_for_second_level_dist: - /* else if ((op & 64) == 0) { - * this = dcode[this.val + (hold & mask[op])]; - * } - */ - testb $64, %al - jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ - - movl $1, %eax - shll %cl, %eax - decl %eax - andl hold_r, %eax /* eax &= hold */ - addl %edx, %eax /* eax += this.val */ - movl dcode(%esp), %edx /* edx = dcode */ - movl (%edx,%eax,4), %eax /* eax = dcode[val + (hold&mask[op])] */ - jmp .L_dodist - -.align 16,0x90 -.L_clip_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes - * - * else { - * if (dist > wsize) { - * invalid distance - * } - * from = window; - * nbytes = dist - nbytes; - * if (write == 0) { - * from += wsize - nbytes; - */ -#define nbytes_r %ecx - movl %eax, nbytes_r - movl wsize(%esp), %eax /* prepare for dist compare */ - negl nbytes_r /* nbytes = -nbytes */ - movl window(%esp), from_r /* from = window */ - - cmpl dist_r, %eax - jb .L_invalid_distance_too_far /* if (dist > wsize) */ - - addl dist_r, nbytes_r /* nbytes = dist - nbytes */ - cmpl $0, write(%esp) - jne .L_wrap_around_window /* if (write != 0) */ - - subl nbytes_r, %eax - addl %eax, from_r /* from += wsize - nbytes */ - - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = len - * - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = out - dist; - * } - * } - */ -#define len_r %eax - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - -.L_wrap_around_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = write, %eax = len - * - * else if (write < nbytes) { - * from += wsize + write - nbytes; - * nbytes -= write; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = window; - * nbytes = write; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while(--nbytes); - * from = out - dist; - * } - * } - * } - */ -#define write_r %eax - movl write(%esp), write_r - cmpl write_r, nbytes_r - jbe .L_contiguous_in_window /* if (write >= nbytes) */ - - addl wsize(%esp), from_r - addl write_r, from_r - subl nbytes_r, from_r /* from += wsize + write - nbytes */ - subl write_r, nbytes_r /* nbytes -= write */ -#undef write_r - - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl window(%esp), from_r /* from = window */ - movl write(%esp), nbytes_r /* nbytes = write */ - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - -.L_contiguous_in_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = write, %eax = len - * - * else { - * from += write - nbytes; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = out - dist; - * } - * } - */ -#define write_r %eax - addl write_r, from_r - subl nbytes_r, from_r /* from += write - nbytes */ -#undef write_r - - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - -.L_do_copy1: - /* regs: %esi = from, %esi = in, %ebp = hold, %bl = bits, %edi = out - * %eax = len - * - * while (len > 0) { - * PUP(out) = PUP(from); - * len--; - * } - * } - * } while (in < last && out < end); - */ -#undef nbytes_r -#define in_r %esi - movl len_r, %ecx - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - jmp .L_while_test - -#undef len_r -#undef dist_r - -#endif /* NO_MMX || RUN_TIME_MMX */ - - -/*** MMX code ***/ - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -.align 32,0x90 -.L_init_mmx: - emms - -#undef bits_r -#undef bitslong_r -#define bitslong_r %ebp -#define hold_mm %mm0 - movd %ebp, hold_mm - movl %ebx, bitslong_r - -#define used_mm %mm1 -#define dmask2_mm %mm2 -#define lmask2_mm %mm3 -#define lmask_mm %mm4 -#define dmask_mm %mm5 -#define tmp_mm %mm6 - - movd lmask(%esp), lmask_mm - movq lmask_mm, lmask2_mm - movd dmask(%esp), dmask_mm - movq dmask_mm, dmask2_mm - pxor used_mm, used_mm - movl lcode(%esp), %ebx /* ebx = lcode */ - jmp .L_do_loop_mmx - -.align 32,0x90 -.L_while_test_mmx: - /* while (in < last && out < end) - */ - cmpl out_r, end(%esp) - jbe .L_break_loop /* if (out >= end) */ - - cmpl in_r, last(%esp) - jbe .L_break_loop - -.L_do_loop_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - - cmpl $32, bitslong_r - ja .L_get_length_code_mmx /* if (32 < bits) */ - - movd bitslong_r, tmp_mm - movd (in_r), %mm7 - addl $4, in_r - psllq tmp_mm, %mm7 - addl $32, bitslong_r - por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ - -.L_get_length_code_mmx: - pand hold_mm, lmask_mm - movd lmask_mm, %eax - movq lmask2_mm, lmask_mm - movl (%ebx,%eax,4), %eax /* eax = lcode[hold & lmask] */ - -.L_dolen_mmx: - movzbl %ah, %ecx /* ecx = this.bits */ - movd %ecx, used_mm - subl %ecx, bitslong_r /* bits -= this.bits */ - - testb %al, %al - jnz .L_test_for_length_base_mmx /* if (op != 0) 45.7% */ - - shrl $16, %eax /* output this.val char */ - stosb - jmp .L_while_test_mmx - -.L_test_for_length_base_mmx: -#define len_r %edx - movl %eax, len_r /* len = this */ - shrl $16, len_r /* len = this.val */ - - testb $16, %al - jz .L_test_for_second_level_length_mmx /* if ((op & 16) == 0) 8% */ - andl $15, %eax /* op &= 15 */ - jz .L_decode_distance_mmx /* if (!op) */ - - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd %eax, used_mm - movd hold_mm, %ecx - subl %eax, bitslong_r - andl .L_mask(,%eax,4), %ecx - addl %ecx, len_r /* len += hold & mask[op] */ - -.L_decode_distance_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - - cmpl $32, bitslong_r - ja .L_get_dist_code_mmx /* if (32 < bits) */ - - movd bitslong_r, tmp_mm - movd (in_r), %mm7 - addl $4, in_r - psllq tmp_mm, %mm7 - addl $32, bitslong_r - por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ - -.L_get_dist_code_mmx: - movl dcode(%esp), %ebx /* ebx = dcode */ - pand hold_mm, dmask_mm - movd dmask_mm, %eax - movq dmask2_mm, dmask_mm - movl (%ebx,%eax,4), %eax /* eax = dcode[hold & lmask] */ - -.L_dodist_mmx: -#define dist_r %ebx - movzbl %ah, %ecx /* ecx = this.bits */ - movl %eax, dist_r - shrl $16, dist_r /* dist = this.val */ - subl %ecx, bitslong_r /* bits -= this.bits */ - movd %ecx, used_mm - - testb $16, %al /* if ((op & 16) == 0) */ - jz .L_test_for_second_level_dist_mmx - andl $15, %eax /* op &= 15 */ - jz .L_check_dist_one_mmx - -.L_add_bits_to_dist_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd %eax, used_mm /* save bit length of current op */ - movd hold_mm, %ecx /* get the next bits on input stream */ - subl %eax, bitslong_r /* bits -= op bits */ - andl .L_mask(,%eax,4), %ecx /* ecx = hold & mask[op] */ - addl %ecx, dist_r /* dist += hold & mask[op] */ - -.L_check_window_mmx: - movl in_r, in(%esp) /* save in so from can use it's reg */ - movl out_r, %eax - subl beg(%esp), %eax /* nbytes = out - beg */ - - cmpl dist_r, %eax - jb .L_clip_window_mmx /* if (dist > nbytes) 4.2% */ - - movl len_r, %ecx - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - - subl $3, %ecx - movb (from_r), %al - movb %al, (out_r) - movb 1(from_r), %al - movb 2(from_r), %dl - addl $3, from_r - movb %al, 1(out_r) - movb %dl, 2(out_r) - addl $3, out_r - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -.align 16,0x90 -.L_check_dist_one_mmx: - cmpl $1, dist_r - jne .L_check_window_mmx - cmpl out_r, beg(%esp) - je .L_check_window_mmx - - decl out_r - movl len_r, %ecx - movb (out_r), %al - subl $3, %ecx - - movb %al, 1(out_r) - movb %al, 2(out_r) - movb %al, 3(out_r) - addl $4, out_r - rep stosb - - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -.align 16,0x90 -.L_test_for_second_level_length_mmx: - testb $64, %al - jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ - - andl $15, %eax - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ecx - andl .L_mask(,%eax,4), %ecx - addl len_r, %ecx - movl (%ebx,%ecx,4), %eax /* eax = lcode[hold & lmask] */ - jmp .L_dolen_mmx - -.align 16,0x90 -.L_test_for_second_level_dist_mmx: - testb $64, %al - jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ - - andl $15, %eax - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ecx - andl .L_mask(,%eax,4), %ecx - movl dcode(%esp), %eax /* ecx = dcode */ - addl dist_r, %ecx - movl (%eax,%ecx,4), %eax /* eax = lcode[hold & lmask] */ - jmp .L_dodist_mmx - -.align 16,0x90 -.L_clip_window_mmx: -#define nbytes_r %ecx - movl %eax, nbytes_r - movl wsize(%esp), %eax /* prepare for dist compare */ - negl nbytes_r /* nbytes = -nbytes */ - movl window(%esp), from_r /* from = window */ - - cmpl dist_r, %eax - jb .L_invalid_distance_too_far /* if (dist > wsize) */ - - addl dist_r, nbytes_r /* nbytes = dist - nbytes */ - cmpl $0, write(%esp) - jne .L_wrap_around_window_mmx /* if (write != 0) */ - - subl nbytes_r, %eax - addl %eax, from_r /* from += wsize - nbytes */ - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - -.L_wrap_around_window_mmx: -#define write_r %eax - movl write(%esp), write_r - cmpl write_r, nbytes_r - jbe .L_contiguous_in_window_mmx /* if (write >= nbytes) */ - - addl wsize(%esp), from_r - addl write_r, from_r - subl nbytes_r, from_r /* from += wsize + write - nbytes */ - subl write_r, nbytes_r /* nbytes -= write */ -#undef write_r - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl window(%esp), from_r /* from = window */ - movl write(%esp), nbytes_r /* nbytes = write */ - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - -.L_contiguous_in_window_mmx: -#define write_r %eax - addl write_r, from_r - subl nbytes_r, from_r /* from += write - nbytes */ -#undef write_r - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - -.L_do_copy1_mmx: -#undef nbytes_r -#define in_r %esi - movl len_r, %ecx - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -#undef hold_r -#undef bitslong_r - -#endif /* USE_MMX || RUN_TIME_MMX */ - - -/*** USE_MMX, NO_MMX, and RUNTIME_MMX from here on ***/ - -.L_invalid_distance_code: - /* else { - * strm->msg = "invalid distance code"; - * state->mode = BAD; - * } - */ - movl $.L_invalid_distance_code_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_test_for_end_of_block: - /* else if (op & 32) { - * state->mode = TYPE; - * break; - * } - */ - testb $32, %al - jz .L_invalid_literal_length_code /* if ((op & 32) == 0) */ - - movl $0, %ecx - movl $INFLATE_MODE_TYPE, %edx - jmp .L_update_stream_state - -.L_invalid_literal_length_code: - /* else { - * strm->msg = "invalid literal/length code"; - * state->mode = BAD; - * } - */ - movl $.L_invalid_literal_length_code_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_invalid_distance_too_far: - /* strm->msg = "invalid distance too far back"; - * state->mode = BAD; - */ - movl in(%esp), in_r /* from_r has in's reg, put in back */ - movl $.L_invalid_distance_too_far_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_update_stream_state: - /* set strm->msg = %ecx, strm->state->mode = %edx */ - movl strm_sp(%esp), %eax - testl %ecx, %ecx /* if (msg != NULL) */ - jz .L_skip_msg - movl %ecx, msg_strm(%eax) /* strm->msg = msg */ -.L_skip_msg: - movl state_strm(%eax), %eax /* state = strm->state */ - movl %edx, mode_state(%eax) /* state->mode = edx (BAD | TYPE) */ - jmp .L_break_loop - -.align 32,0x90 -.L_break_loop: - -/* - * Regs: - * - * bits = %ebp when mmx, and in %ebx when non-mmx - * hold = %hold_mm when mmx, and in %ebp when non-mmx - * in = %esi - * out = %edi - */ - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -#if defined( RUN_TIME_MMX ) - - cmpl $DO_USE_MMX, inflate_fast_use_mmx - jne .L_update_next_in - -#endif /* RUN_TIME_MMX */ - - movl %ebp, %ebx - -.L_update_next_in: - -#endif - -#define strm_r %eax -#define state_r %edx - - /* len = bits >> 3; - * in -= len; - * bits -= len << 3; - * hold &= (1U << bits) - 1; - * state->hold = hold; - * state->bits = bits; - * strm->next_in = in; - * strm->next_out = out; - */ - movl strm_sp(%esp), strm_r - movl %ebx, %ecx - movl state_strm(strm_r), state_r - shrl $3, %ecx - subl %ecx, in_r - shll $3, %ecx - subl %ecx, %ebx - movl out_r, next_out_strm(strm_r) - movl %ebx, bits_state(state_r) - movl %ebx, %ecx - - leal buf(%esp), %ebx - cmpl %ebx, last(%esp) - jne .L_buf_not_used /* if buf != last */ - - subl %ebx, in_r /* in -= buf */ - movl next_in_strm(strm_r), %ebx - movl %ebx, last(%esp) /* last = strm->next_in */ - addl %ebx, in_r /* in += strm->next_in */ - movl avail_in_strm(strm_r), %ebx - subl $11, %ebx - addl %ebx, last(%esp) /* last = &strm->next_in[ avail_in - 11 ] */ - -.L_buf_not_used: - movl in_r, next_in_strm(strm_r) - - movl $1, %ebx - shll %cl, %ebx - decl %ebx - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -#if defined( RUN_TIME_MMX ) - - cmpl $DO_USE_MMX, inflate_fast_use_mmx - jne .L_update_hold - -#endif /* RUN_TIME_MMX */ - - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ebp - - emms - -.L_update_hold: - -#endif /* USE_MMX || RUN_TIME_MMX */ - - andl %ebx, %ebp - movl %ebp, hold_state(state_r) - -#define last_r %ebx - - /* strm->avail_in = in < last ? 11 + (last - in) : 11 - (in - last) */ - movl last(%esp), last_r - cmpl in_r, last_r - jbe .L_last_is_smaller /* if (in >= last) */ - - subl in_r, last_r /* last -= in */ - addl $11, last_r /* last += 11 */ - movl last_r, avail_in_strm(strm_r) - jmp .L_fixup_out -.L_last_is_smaller: - subl last_r, in_r /* in -= last */ - negl in_r /* in = -in */ - addl $11, in_r /* in += 11 */ - movl in_r, avail_in_strm(strm_r) - -#undef last_r -#define end_r %ebx - -.L_fixup_out: - /* strm->avail_out = out < end ? 257 + (end - out) : 257 - (out - end)*/ - movl end(%esp), end_r - cmpl out_r, end_r - jbe .L_end_is_smaller /* if (out >= end) */ - - subl out_r, end_r /* end -= out */ - addl $257, end_r /* end += 257 */ - movl end_r, avail_out_strm(strm_r) - jmp .L_done -.L_end_is_smaller: - subl end_r, out_r /* out -= end */ - negl out_r /* out = -out */ - addl $257, out_r /* out += 257 */ - movl out_r, avail_out_strm(strm_r) - -#undef end_r -#undef strm_r -#undef state_r - -.L_done: - addl $local_var_size, %esp - popf - popl %ebx - popl %ebp - popl %esi - popl %edi - ret - -#if defined( GAS_ELF ) -/* elf info */ -.type inflate_fast,@function -.size inflate_fast,.-inflate_fast -#endif diff --git a/deps/zlib/contrib/iostream/test.cpp b/deps/zlib/contrib/iostream/test.cpp deleted file mode 100644 index 7d265b3b5c0e01..00000000000000 --- a/deps/zlib/contrib/iostream/test.cpp +++ /dev/null @@ -1,24 +0,0 @@ - -#include "zfstream.h" - -int main() { - - // Construct a stream object with this filebuffer. Anything sent - // to this stream will go to standard out. - gzofstream os( 1, ios::out ); - - // This text is getting compressed and sent to stdout. - // To prove this, run 'test | zcat'. - os << "Hello, Mommy" << endl; - - os << setcompressionlevel( Z_NO_COMPRESSION ); - os << "hello, hello, hi, ho!" << endl; - - setcompressionlevel( os, Z_DEFAULT_COMPRESSION ) - << "I'm compressing again" << endl; - - os.close(); - - return 0; - -} diff --git a/deps/zlib/contrib/iostream/zfstream.cpp b/deps/zlib/contrib/iostream/zfstream.cpp deleted file mode 100644 index d0cd85faaf5b22..00000000000000 --- a/deps/zlib/contrib/iostream/zfstream.cpp +++ /dev/null @@ -1,329 +0,0 @@ - -#include "zfstream.h" - -gzfilebuf::gzfilebuf() : - file(NULL), - mode(0), - own_file_descriptor(0) -{ } - -gzfilebuf::~gzfilebuf() { - - sync(); - if ( own_file_descriptor ) - close(); - -} - -gzfilebuf *gzfilebuf::open( const char *name, - int io_mode ) { - - if ( is_open() ) - return NULL; - - char char_mode[10]; - char *p = char_mode; - - if ( io_mode & ios::in ) { - mode = ios::in; - *p++ = 'r'; - } else if ( io_mode & ios::app ) { - mode = ios::app; - *p++ = 'a'; - } else { - mode = ios::out; - *p++ = 'w'; - } - - if ( io_mode & ios::binary ) { - mode |= ios::binary; - *p++ = 'b'; - } - - // Hard code the compression level - if ( io_mode & (ios::out|ios::app )) { - *p++ = '9'; - } - - // Put the end-of-string indicator - *p = '\0'; - - if ( (file = gzopen(name, char_mode)) == NULL ) - return NULL; - - own_file_descriptor = 1; - - return this; - -} - -gzfilebuf *gzfilebuf::attach( int file_descriptor, - int io_mode ) { - - if ( is_open() ) - return NULL; - - char char_mode[10]; - char *p = char_mode; - - if ( io_mode & ios::in ) { - mode = ios::in; - *p++ = 'r'; - } else if ( io_mode & ios::app ) { - mode = ios::app; - *p++ = 'a'; - } else { - mode = ios::out; - *p++ = 'w'; - } - - if ( io_mode & ios::binary ) { - mode |= ios::binary; - *p++ = 'b'; - } - - // Hard code the compression level - if ( io_mode & (ios::out|ios::app )) { - *p++ = '9'; - } - - // Put the end-of-string indicator - *p = '\0'; - - if ( (file = gzdopen(file_descriptor, char_mode)) == NULL ) - return NULL; - - own_file_descriptor = 0; - - return this; - -} - -gzfilebuf *gzfilebuf::close() { - - if ( is_open() ) { - - sync(); - gzclose( file ); - file = NULL; - - } - - return this; - -} - -int gzfilebuf::setcompressionlevel( int comp_level ) { - - return gzsetparams(file, comp_level, -2); - -} - -int gzfilebuf::setcompressionstrategy( int comp_strategy ) { - - return gzsetparams(file, -2, comp_strategy); - -} - - -streampos gzfilebuf::seekoff( streamoff off, ios::seek_dir dir, int which ) { - - return streampos(EOF); - -} - -int gzfilebuf::underflow() { - - // If the file hasn't been opened for reading, error. - if ( !is_open() || !(mode & ios::in) ) - return EOF; - - // if a buffer doesn't exists, allocate one. - if ( !base() ) { - - if ( (allocate()) == EOF ) - return EOF; - setp(0,0); - - } else { - - if ( in_avail() ) - return (unsigned char) *gptr(); - - if ( out_waiting() ) { - if ( flushbuf() == EOF ) - return EOF; - } - - } - - // Attempt to fill the buffer. - - int result = fillbuf(); - if ( result == EOF ) { - // disable get area - setg(0,0,0); - return EOF; - } - - return (unsigned char) *gptr(); - -} - -int gzfilebuf::overflow( int c ) { - - if ( !is_open() || !(mode & ios::out) ) - return EOF; - - if ( !base() ) { - if ( allocate() == EOF ) - return EOF; - setg(0,0,0); - } else { - if (in_avail()) { - return EOF; - } - if (out_waiting()) { - if (flushbuf() == EOF) - return EOF; - } - } - - int bl = blen(); - setp( base(), base() + bl); - - if ( c != EOF ) { - - *pptr() = c; - pbump(1); - - } - - return 0; - -} - -int gzfilebuf::sync() { - - if ( !is_open() ) - return EOF; - - if ( out_waiting() ) - return flushbuf(); - - return 0; - -} - -int gzfilebuf::flushbuf() { - - int n; - char *q; - - q = pbase(); - n = pptr() - q; - - if ( gzwrite( file, q, n) < n ) - return EOF; - - setp(0,0); - - return 0; - -} - -int gzfilebuf::fillbuf() { - - int required; - char *p; - - p = base(); - - required = blen(); - - int t = gzread( file, p, required ); - - if ( t <= 0) return EOF; - - setg( base(), base(), base()+t); - - return t; - -} - -gzfilestream_common::gzfilestream_common() : - ios( gzfilestream_common::rdbuf() ) -{ } - -gzfilestream_common::~gzfilestream_common() -{ } - -void gzfilestream_common::attach( int fd, int io_mode ) { - - if ( !buffer.attach( fd, io_mode) ) - clear( ios::failbit | ios::badbit ); - else - clear(); - -} - -void gzfilestream_common::open( const char *name, int io_mode ) { - - if ( !buffer.open( name, io_mode ) ) - clear( ios::failbit | ios::badbit ); - else - clear(); - -} - -void gzfilestream_common::close() { - - if ( !buffer.close() ) - clear( ios::failbit | ios::badbit ); - -} - -gzfilebuf *gzfilestream_common::rdbuf() -{ - return &buffer; -} - -gzifstream::gzifstream() : - ios( gzfilestream_common::rdbuf() ) -{ - clear( ios::badbit ); -} - -gzifstream::gzifstream( const char *name, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::open( name, io_mode ); -} - -gzifstream::gzifstream( int fd, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::attach( fd, io_mode ); -} - -gzifstream::~gzifstream() { } - -gzofstream::gzofstream() : - ios( gzfilestream_common::rdbuf() ) -{ - clear( ios::badbit ); -} - -gzofstream::gzofstream( const char *name, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::open( name, io_mode ); -} - -gzofstream::gzofstream( int fd, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::attach( fd, io_mode ); -} - -gzofstream::~gzofstream() { } diff --git a/deps/zlib/contrib/iostream/zfstream.h b/deps/zlib/contrib/iostream/zfstream.h deleted file mode 100644 index ed79098a3adaf5..00000000000000 --- a/deps/zlib/contrib/iostream/zfstream.h +++ /dev/null @@ -1,128 +0,0 @@ - -#ifndef zfstream_h -#define zfstream_h - -#include -#include "zlib.h" - -class gzfilebuf : public streambuf { - -public: - - gzfilebuf( ); - virtual ~gzfilebuf(); - - gzfilebuf *open( const char *name, int io_mode ); - gzfilebuf *attach( int file_descriptor, int io_mode ); - gzfilebuf *close(); - - int setcompressionlevel( int comp_level ); - int setcompressionstrategy( int comp_strategy ); - - inline int is_open() const { return (file !=NULL); } - - virtual streampos seekoff( streamoff, ios::seek_dir, int ); - - virtual int sync(); - -protected: - - virtual int underflow(); - virtual int overflow( int = EOF ); - -private: - - gzFile file; - short mode; - short own_file_descriptor; - - int flushbuf(); - int fillbuf(); - -}; - -class gzfilestream_common : virtual public ios { - - friend class gzifstream; - friend class gzofstream; - friend gzofstream &setcompressionlevel( gzofstream &, int ); - friend gzofstream &setcompressionstrategy( gzofstream &, int ); - -public: - virtual ~gzfilestream_common(); - - void attach( int fd, int io_mode ); - void open( const char *name, int io_mode ); - void close(); - -protected: - gzfilestream_common(); - -private: - gzfilebuf *rdbuf(); - - gzfilebuf buffer; - -}; - -class gzifstream : public gzfilestream_common, public istream { - -public: - - gzifstream(); - gzifstream( const char *name, int io_mode = ios::in ); - gzifstream( int fd, int io_mode = ios::in ); - - virtual ~gzifstream(); - -}; - -class gzofstream : public gzfilestream_common, public ostream { - -public: - - gzofstream(); - gzofstream( const char *name, int io_mode = ios::out ); - gzofstream( int fd, int io_mode = ios::out ); - - virtual ~gzofstream(); - -}; - -template class gzomanip { - friend gzofstream &operator<<(gzofstream &, const gzomanip &); -public: - gzomanip(gzofstream &(*f)(gzofstream &, T), T v) : func(f), val(v) { } -private: - gzofstream &(*func)(gzofstream &, T); - T val; -}; - -template gzofstream &operator<<(gzofstream &s, const gzomanip &m) -{ - return (*m.func)(s, m.val); -} - -inline gzofstream &setcompressionlevel( gzofstream &s, int l ) -{ - (s.rdbuf())->setcompressionlevel(l); - return s; -} - -inline gzofstream &setcompressionstrategy( gzofstream &s, int l ) -{ - (s.rdbuf())->setcompressionstrategy(l); - return s; -} - -inline gzomanip setcompressionlevel(int l) -{ - return gzomanip(&setcompressionlevel,l); -} - -inline gzomanip setcompressionstrategy(int l) -{ - return gzomanip(&setcompressionstrategy,l); -} - -#endif diff --git a/deps/zlib/contrib/iostream2/zstream.h b/deps/zlib/contrib/iostream2/zstream.h deleted file mode 100644 index 43d2332b79b70b..00000000000000 --- a/deps/zlib/contrib/iostream2/zstream.h +++ /dev/null @@ -1,307 +0,0 @@ -/* - * - * Copyright (c) 1997 - * Christian Michelsen Research AS - * Advanced Computing - * Fantoftvegen 38, 5036 BERGEN, Norway - * http://www.cmr.no - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Christian Michelsen Research AS makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#ifndef ZSTREAM__H -#define ZSTREAM__H - -/* - * zstream.h - C++ interface to the 'zlib' general purpose compression library - * $Id: zstream.h 1.1 1997-06-25 12:00:56+02 tyge Exp tyge $ - */ - -#include -#include -#include -#include "zlib.h" - -#if defined(_WIN32) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -class zstringlen { -public: - zstringlen(class izstream&); - zstringlen(class ozstream&, const char*); - size_t value() const { return val.word; } -private: - struct Val { unsigned char byte; size_t word; } val; -}; - -// ----------------------------- izstream ----------------------------- - -class izstream -{ - public: - izstream() : m_fp(0) {} - izstream(FILE* fp) : m_fp(0) { open(fp); } - izstream(const char* name) : m_fp(0) { open(name); } - ~izstream() { close(); } - - /* Opens a gzip (.gz) file for reading. - * open() can be used to read a file which is not in gzip format; - * in this case read() will directly read from the file without - * decompression. errno can be checked to distinguish two error - * cases (if errno is zero, the zlib error is Z_MEM_ERROR). - */ - void open(const char* name) { - if (m_fp) close(); - m_fp = ::gzopen(name, "rb"); - } - - void open(FILE* fp) { - SET_BINARY_MODE(fp); - if (m_fp) close(); - m_fp = ::gzdopen(fileno(fp), "rb"); - } - - /* Flushes all pending input if necessary, closes the compressed file - * and deallocates all the (de)compression state. The return value is - * the zlib error number (see function error() below). - */ - int close() { - int r = ::gzclose(m_fp); - m_fp = 0; return r; - } - - /* Binary read the given number of bytes from the compressed file. - */ - int read(void* buf, size_t len) { - return ::gzread(m_fp, buf, len); - } - - /* Returns the error message for the last error which occurred on the - * given compressed file. errnum is set to zlib error number. If an - * error occurred in the file system and not in the compression library, - * errnum is set to Z_ERRNO and the application may consult errno - * to get the exact error code. - */ - const char* error(int* errnum) { - return ::gzerror(m_fp, errnum); - } - - gzFile fp() { return m_fp; } - - private: - gzFile m_fp; -}; - -/* - * Binary read the given (array of) object(s) from the compressed file. - * If the input file was not in gzip format, read() copies the objects number - * of bytes into the buffer. - * returns the number of uncompressed bytes actually read - * (0 for end of file, -1 for error). - */ -template -inline int read(izstream& zs, T* x, Items items) { - return ::gzread(zs.fp(), x, items*sizeof(T)); -} - -/* - * Binary input with the '>' operator. - */ -template -inline izstream& operator>(izstream& zs, T& x) { - ::gzread(zs.fp(), &x, sizeof(T)); - return zs; -} - - -inline zstringlen::zstringlen(izstream& zs) { - zs > val.byte; - if (val.byte == 255) zs > val.word; - else val.word = val.byte; -} - -/* - * Read length of string + the string with the '>' operator. - */ -inline izstream& operator>(izstream& zs, char* x) { - zstringlen len(zs); - ::gzread(zs.fp(), x, len.value()); - x[len.value()] = '\0'; - return zs; -} - -inline char* read_string(izstream& zs) { - zstringlen len(zs); - char* x = new char[len.value()+1]; - ::gzread(zs.fp(), x, len.value()); - x[len.value()] = '\0'; - return x; -} - -// ----------------------------- ozstream ----------------------------- - -class ozstream -{ - public: - ozstream() : m_fp(0), m_os(0) { - } - ozstream(FILE* fp, int level = Z_DEFAULT_COMPRESSION) - : m_fp(0), m_os(0) { - open(fp, level); - } - ozstream(const char* name, int level = Z_DEFAULT_COMPRESSION) - : m_fp(0), m_os(0) { - open(name, level); - } - ~ozstream() { - close(); - } - - /* Opens a gzip (.gz) file for writing. - * The compression level parameter should be in 0..9 - * errno can be checked to distinguish two error cases - * (if errno is zero, the zlib error is Z_MEM_ERROR). - */ - void open(const char* name, int level = Z_DEFAULT_COMPRESSION) { - char mode[4] = "wb\0"; - if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; - if (m_fp) close(); - m_fp = ::gzopen(name, mode); - } - - /* open from a FILE pointer. - */ - void open(FILE* fp, int level = Z_DEFAULT_COMPRESSION) { - SET_BINARY_MODE(fp); - char mode[4] = "wb\0"; - if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; - if (m_fp) close(); - m_fp = ::gzdopen(fileno(fp), mode); - } - - /* Flushes all pending output if necessary, closes the compressed file - * and deallocates all the (de)compression state. The return value is - * the zlib error number (see function error() below). - */ - int close() { - if (m_os) { - ::gzwrite(m_fp, m_os->str(), m_os->pcount()); - delete[] m_os->str(); delete m_os; m_os = 0; - } - int r = ::gzclose(m_fp); m_fp = 0; return r; - } - - /* Binary write the given number of bytes into the compressed file. - */ - int write(const void* buf, size_t len) { - return ::gzwrite(m_fp, (voidp) buf, len); - } - - /* Flushes all pending output into the compressed file. The parameter - * _flush is as in the deflate() function. The return value is the zlib - * error number (see function gzerror below). flush() returns Z_OK if - * the flush_ parameter is Z_FINISH and all output could be flushed. - * flush() should be called only when strictly necessary because it can - * degrade compression. - */ - int flush(int _flush) { - os_flush(); - return ::gzflush(m_fp, _flush); - } - - /* Returns the error message for the last error which occurred on the - * given compressed file. errnum is set to zlib error number. If an - * error occurred in the file system and not in the compression library, - * errnum is set to Z_ERRNO and the application may consult errno - * to get the exact error code. - */ - const char* error(int* errnum) { - return ::gzerror(m_fp, errnum); - } - - gzFile fp() { return m_fp; } - - ostream& os() { - if (m_os == 0) m_os = new ostrstream; - return *m_os; - } - - void os_flush() { - if (m_os && m_os->pcount()>0) { - ostrstream* oss = new ostrstream; - oss->fill(m_os->fill()); - oss->flags(m_os->flags()); - oss->precision(m_os->precision()); - oss->width(m_os->width()); - ::gzwrite(m_fp, m_os->str(), m_os->pcount()); - delete[] m_os->str(); delete m_os; m_os = oss; - } - } - - private: - gzFile m_fp; - ostrstream* m_os; -}; - -/* - * Binary write the given (array of) object(s) into the compressed file. - * returns the number of uncompressed bytes actually written - * (0 in case of error). - */ -template -inline int write(ozstream& zs, const T* x, Items items) { - return ::gzwrite(zs.fp(), (voidp) x, items*sizeof(T)); -} - -/* - * Binary output with the '<' operator. - */ -template -inline ozstream& operator<(ozstream& zs, const T& x) { - ::gzwrite(zs.fp(), (voidp) &x, sizeof(T)); - return zs; -} - -inline zstringlen::zstringlen(ozstream& zs, const char* x) { - val.byte = 255; val.word = ::strlen(x); - if (val.word < 255) zs < (val.byte = val.word); - else zs < val; -} - -/* - * Write length of string + the string with the '<' operator. - */ -inline ozstream& operator<(ozstream& zs, const char* x) { - zstringlen len(zs, x); - ::gzwrite(zs.fp(), (voidp) x, len.value()); - return zs; -} - -#ifdef _MSC_VER -inline ozstream& operator<(ozstream& zs, char* const& x) { - return zs < (const char*) x; -} -#endif - -/* - * Ascii write with the << operator; - */ -template -inline ostream& operator<<(ozstream& zs, const T& x) { - zs.os_flush(); - return zs.os() << x; -} - -#endif diff --git a/deps/zlib/contrib/iostream2/zstream_test.cpp b/deps/zlib/contrib/iostream2/zstream_test.cpp deleted file mode 100644 index 6273f62d62a8fa..00000000000000 --- a/deps/zlib/contrib/iostream2/zstream_test.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "zstream.h" -#include -#include -#include - -void main() { - char h[256] = "Hello"; - char* g = "Goodbye"; - ozstream out("temp.gz"); - out < "This works well" < h < g; - out.close(); - - izstream in("temp.gz"); // read it back - char *x = read_string(in), *y = new char[256], z[256]; - in > y > z; - in.close(); - cout << x << endl << y << endl << z << endl; - - out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results - out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl; - out << z << endl << y << endl << x << endl; - out << 1.1234567890123456789 << endl; - - delete[] x; delete[] y; -} diff --git a/deps/zlib/contrib/iostream3/README b/deps/zlib/contrib/iostream3/README deleted file mode 100644 index f7b319ab91a7c7..00000000000000 --- a/deps/zlib/contrib/iostream3/README +++ /dev/null @@ -1,35 +0,0 @@ -These classes provide a C++ stream interface to the zlib library. It allows you -to do things like: - - gzofstream outf("blah.gz"); - outf << "These go into the gzip file " << 123 << endl; - -It does this by deriving a specialized stream buffer for gzipped files, which is -the way Stroustrup would have done it. :-> - -The gzifstream and gzofstream classes were originally written by Kevin Ruland -and made available in the zlib contrib/iostream directory. The older version still -compiles under gcc 2.xx, but not under gcc 3.xx, which sparked the development of -this version. - -The new classes are as standard-compliant as possible, closely following the -approach of the standard library's fstream classes. It compiles under gcc versions -3.2 and 3.3, but not under gcc 2.xx. This is mainly due to changes in the standard -library naming scheme. The new version of gzifstream/gzofstream/gzfilebuf differs -from the previous one in the following respects: -- added showmanyc -- added setbuf, with support for unbuffered output via setbuf(0,0) -- a few bug fixes of stream behavior -- gzipped output file opened with default compression level instead of maximum level -- setcompressionlevel()/strategy() members replaced by single setcompression() - -The code is provided "as is", with the permission to use, copy, modify, distribute -and sell it for any purpose without fee. - -Ludwig Schwardt - - -DSP Lab -Electrical & Electronic Engineering Department -University of Stellenbosch -South Africa diff --git a/deps/zlib/contrib/iostream3/TODO b/deps/zlib/contrib/iostream3/TODO deleted file mode 100644 index 7032f97be0469e..00000000000000 --- a/deps/zlib/contrib/iostream3/TODO +++ /dev/null @@ -1,17 +0,0 @@ -Possible upgrades to gzfilebuf: - -- The ability to do putback (e.g. putbackfail) - -- The ability to seek (zlib supports this, but could be slow/tricky) - -- Simultaneous read/write access (does it make sense?) - -- Support for ios_base::ate open mode - -- Locale support? - -- Check public interface to see which calls give problems - (due to dependence on library internals) - -- Override operator<<(ostream&, gzfilebuf*) to allow direct copying - of stream buffer to stream ( i.e. os << is.rdbuf(); ) diff --git a/deps/zlib/contrib/iostream3/test.cc b/deps/zlib/contrib/iostream3/test.cc deleted file mode 100644 index 94235334f25cd5..00000000000000 --- a/deps/zlib/contrib/iostream3/test.cc +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Test program for gzifstream and gzofstream - * - * by Ludwig Schwardt - * original version by Kevin Ruland - */ - -#include "zfstream.h" -#include // for cout - -int main() { - - gzofstream outf; - gzifstream inf; - char buf[80]; - - outf.open("test1.txt.gz"); - outf << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - outf.close(); - std::cout << "Wrote the following message to 'test1.txt.gz' (check with zcat or zless):\n" - << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - - std::cout << "\nReading 'test1.txt.gz' (buffered) produces:\n"; - inf.open("test1.txt.gz"); - while (inf.getline(buf,80,'\n')) { - std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; - } - inf.close(); - - outf.rdbuf()->pubsetbuf(0,0); - outf.open("test2.txt.gz"); - outf << setcompression(Z_NO_COMPRESSION) - << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - outf.close(); - std::cout << "\nWrote the same message to 'test2.txt.gz' in uncompressed form"; - - std::cout << "\nReading 'test2.txt.gz' (unbuffered) produces:\n"; - inf.rdbuf()->pubsetbuf(0,0); - inf.open("test2.txt.gz"); - while (inf.getline(buf,80,'\n')) { - std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; - } - inf.close(); - - return 0; - -} diff --git a/deps/zlib/contrib/iostream3/zfstream.cc b/deps/zlib/contrib/iostream3/zfstream.cc deleted file mode 100644 index 94eb933444a967..00000000000000 --- a/deps/zlib/contrib/iostream3/zfstream.cc +++ /dev/null @@ -1,479 +0,0 @@ -/* - * A C++ I/O streams interface to the zlib gz* functions - * - * by Ludwig Schwardt - * original version by Kevin Ruland - * - * This version is standard-compliant and compatible with gcc 3.x. - */ - -#include "zfstream.h" -#include // for strcpy, strcat, strlen (mode strings) -#include // for BUFSIZ - -// Internal buffer sizes (default and "unbuffered" versions) -#define BIGBUFSIZE BUFSIZ -#define SMALLBUFSIZE 1 - -/*****************************************************************************/ - -// Default constructor -gzfilebuf::gzfilebuf() -: file(NULL), io_mode(std::ios_base::openmode(0)), own_fd(false), - buffer(NULL), buffer_size(BIGBUFSIZE), own_buffer(true) -{ - // No buffers to start with - this->disable_buffer(); -} - -// Destructor -gzfilebuf::~gzfilebuf() -{ - // Sync output buffer and close only if responsible for file - // (i.e. attached streams should be left open at this stage) - this->sync(); - if (own_fd) - this->close(); - // Make sure internal buffer is deallocated - this->disable_buffer(); -} - -// Set compression level and strategy -int -gzfilebuf::setcompression(int comp_level, - int comp_strategy) -{ - return gzsetparams(file, comp_level, comp_strategy); -} - -// Open gzipped file -gzfilebuf* -gzfilebuf::open(const char *name, - std::ios_base::openmode mode) -{ - // Fail if file already open - if (this->is_open()) - return NULL; - // Don't support simultaneous read/write access (yet) - if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) - return NULL; - - // Build mode string for gzopen and check it [27.8.1.3.2] - char char_mode[6] = "\0\0\0\0\0"; - if (!this->open_mode(mode, char_mode)) - return NULL; - - // Attempt to open file - if ((file = gzopen(name, char_mode)) == NULL) - return NULL; - - // On success, allocate internal buffer and set flags - this->enable_buffer(); - io_mode = mode; - own_fd = true; - return this; -} - -// Attach to gzipped file -gzfilebuf* -gzfilebuf::attach(int fd, - std::ios_base::openmode mode) -{ - // Fail if file already open - if (this->is_open()) - return NULL; - // Don't support simultaneous read/write access (yet) - if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) - return NULL; - - // Build mode string for gzdopen and check it [27.8.1.3.2] - char char_mode[6] = "\0\0\0\0\0"; - if (!this->open_mode(mode, char_mode)) - return NULL; - - // Attempt to attach to file - if ((file = gzdopen(fd, char_mode)) == NULL) - return NULL; - - // On success, allocate internal buffer and set flags - this->enable_buffer(); - io_mode = mode; - own_fd = false; - return this; -} - -// Close gzipped file -gzfilebuf* -gzfilebuf::close() -{ - // Fail immediately if no file is open - if (!this->is_open()) - return NULL; - // Assume success - gzfilebuf* retval = this; - // Attempt to sync and close gzipped file - if (this->sync() == -1) - retval = NULL; - if (gzclose(file) < 0) - retval = NULL; - // File is now gone anyway (postcondition [27.8.1.3.8]) - file = NULL; - own_fd = false; - // Destroy internal buffer if it exists - this->disable_buffer(); - return retval; -} - -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -// Convert int open mode to mode string -bool -gzfilebuf::open_mode(std::ios_base::openmode mode, - char* c_mode) const -{ - bool testb = mode & std::ios_base::binary; - bool testi = mode & std::ios_base::in; - bool testo = mode & std::ios_base::out; - bool testt = mode & std::ios_base::trunc; - bool testa = mode & std::ios_base::app; - - // Check for valid flag combinations - see [27.8.1.3.2] (Table 92) - // Original zfstream hardcoded the compression level to maximum here... - // Double the time for less than 1% size improvement seems - // excessive though - keeping it at the default level - // To change back, just append "9" to the next three mode strings - if (!testi && testo && !testt && !testa) - strcpy(c_mode, "w"); - if (!testi && testo && !testt && testa) - strcpy(c_mode, "a"); - if (!testi && testo && testt && !testa) - strcpy(c_mode, "w"); - if (testi && !testo && !testt && !testa) - strcpy(c_mode, "r"); - // No read/write mode yet -// if (testi && testo && !testt && !testa) -// strcpy(c_mode, "r+"); -// if (testi && testo && testt && !testa) -// strcpy(c_mode, "w+"); - - // Mode string should be empty for invalid combination of flags - if (strlen(c_mode) == 0) - return false; - if (testb) - strcat(c_mode, "b"); - return true; -} - -// Determine number of characters in internal get buffer -std::streamsize -gzfilebuf::showmanyc() -{ - // Calls to underflow will fail if file not opened for reading - if (!this->is_open() || !(io_mode & std::ios_base::in)) - return -1; - // Make sure get area is in use - if (this->gptr() && (this->gptr() < this->egptr())) - return std::streamsize(this->egptr() - this->gptr()); - else - return 0; -} - -// Fill get area from gzipped file -gzfilebuf::int_type -gzfilebuf::underflow() -{ - // If something is left in the get area by chance, return it - // (this shouldn't normally happen, as underflow is only supposed - // to be called when gptr >= egptr, but it serves as error check) - if (this->gptr() && (this->gptr() < this->egptr())) - return traits_type::to_int_type(*(this->gptr())); - - // If the file hasn't been opened for reading, produce error - if (!this->is_open() || !(io_mode & std::ios_base::in)) - return traits_type::eof(); - - // Attempt to fill internal buffer from gzipped file - // (buffer must be guaranteed to exist...) - int bytes_read = gzread(file, buffer, buffer_size); - // Indicates error or EOF - if (bytes_read <= 0) - { - // Reset get area - this->setg(buffer, buffer, buffer); - return traits_type::eof(); - } - // Make all bytes read from file available as get area - this->setg(buffer, buffer, buffer + bytes_read); - - // Return next character in get area - return traits_type::to_int_type(*(this->gptr())); -} - -// Write put area to gzipped file -gzfilebuf::int_type -gzfilebuf::overflow(int_type c) -{ - // Determine whether put area is in use - if (this->pbase()) - { - // Double-check pointer range - if (this->pptr() > this->epptr() || this->pptr() < this->pbase()) - return traits_type::eof(); - // Add extra character to buffer if not EOF - if (!traits_type::eq_int_type(c, traits_type::eof())) - { - *(this->pptr()) = traits_type::to_char_type(c); - this->pbump(1); - } - // Number of characters to write to file - int bytes_to_write = this->pptr() - this->pbase(); - // Overflow doesn't fail if nothing is to be written - if (bytes_to_write > 0) - { - // If the file hasn't been opened for writing, produce error - if (!this->is_open() || !(io_mode & std::ios_base::out)) - return traits_type::eof(); - // If gzipped file won't accept all bytes written to it, fail - if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write) - return traits_type::eof(); - // Reset next pointer to point to pbase on success - this->pbump(-bytes_to_write); - } - } - // Write extra character to file if not EOF - else if (!traits_type::eq_int_type(c, traits_type::eof())) - { - // If the file hasn't been opened for writing, produce error - if (!this->is_open() || !(io_mode & std::ios_base::out)) - return traits_type::eof(); - // Impromptu char buffer (allows "unbuffered" output) - char_type last_char = traits_type::to_char_type(c); - // If gzipped file won't accept this character, fail - if (gzwrite(file, &last_char, 1) != 1) - return traits_type::eof(); - } - - // If you got here, you have succeeded (even if c was EOF) - // The return value should therefore be non-EOF - if (traits_type::eq_int_type(c, traits_type::eof())) - return traits_type::not_eof(c); - else - return c; -} - -// Assign new buffer -std::streambuf* -gzfilebuf::setbuf(char_type* p, - std::streamsize n) -{ - // First make sure stuff is sync'ed, for safety - if (this->sync() == -1) - return NULL; - // If buffering is turned off on purpose via setbuf(0,0), still allocate one... - // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at - // least a buffer of size 1 (very inefficient though, therefore make it bigger?) - // This follows from [27.5.2.4.3]/12 (gptr needs to point at something, it seems) - if (!p || !n) - { - // Replace existing buffer (if any) with small internal buffer - this->disable_buffer(); - buffer = NULL; - buffer_size = 0; - own_buffer = true; - this->enable_buffer(); - } - else - { - // Replace existing buffer (if any) with external buffer - this->disable_buffer(); - buffer = p; - buffer_size = n; - own_buffer = false; - this->enable_buffer(); - } - return this; -} - -// Write put area to gzipped file (i.e. ensures that put area is empty) -int -gzfilebuf::sync() -{ - return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0; -} - -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -// Allocate internal buffer -void -gzfilebuf::enable_buffer() -{ - // If internal buffer required, allocate one - if (own_buffer && !buffer) - { - // Check for buffered vs. "unbuffered" - if (buffer_size > 0) - { - // Allocate internal buffer - buffer = new char_type[buffer_size]; - // Get area starts empty and will be expanded by underflow as need arises - this->setg(buffer, buffer, buffer); - // Setup entire internal buffer as put area. - // The one-past-end pointer actually points to the last element of the buffer, - // so that overflow(c) can safely add the extra character c to the sequence. - // These pointers remain in place for the duration of the buffer - this->setp(buffer, buffer + buffer_size - 1); - } - else - { - // Even in "unbuffered" case, (small?) get buffer is still required - buffer_size = SMALLBUFSIZE; - buffer = new char_type[buffer_size]; - this->setg(buffer, buffer, buffer); - // "Unbuffered" means no put buffer - this->setp(0, 0); - } - } - else - { - // If buffer already allocated, reset buffer pointers just to make sure no - // stale chars are lying around - this->setg(buffer, buffer, buffer); - this->setp(buffer, buffer + buffer_size - 1); - } -} - -// Destroy internal buffer -void -gzfilebuf::disable_buffer() -{ - // If internal buffer exists, deallocate it - if (own_buffer && buffer) - { - // Preserve unbuffered status by zeroing size - if (!this->pbase()) - buffer_size = 0; - delete[] buffer; - buffer = NULL; - this->setg(0, 0, 0); - this->setp(0, 0); - } - else - { - // Reset buffer pointers to initial state if external buffer exists - this->setg(buffer, buffer, buffer); - if (buffer) - this->setp(buffer, buffer + buffer_size - 1); - else - this->setp(0, 0); - } -} - -/*****************************************************************************/ - -// Default constructor initializes stream buffer -gzifstream::gzifstream() -: std::istream(NULL), sb() -{ this->init(&sb); } - -// Initialize stream buffer and open file -gzifstream::gzifstream(const char* name, - std::ios_base::openmode mode) -: std::istream(NULL), sb() -{ - this->init(&sb); - this->open(name, mode); -} - -// Initialize stream buffer and attach to file -gzifstream::gzifstream(int fd, - std::ios_base::openmode mode) -: std::istream(NULL), sb() -{ - this->init(&sb); - this->attach(fd, mode); -} - -// Open file and go into fail() state if unsuccessful -void -gzifstream::open(const char* name, - std::ios_base::openmode mode) -{ - if (!sb.open(name, mode | std::ios_base::in)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Attach to file and go into fail() state if unsuccessful -void -gzifstream::attach(int fd, - std::ios_base::openmode mode) -{ - if (!sb.attach(fd, mode | std::ios_base::in)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Close file -void -gzifstream::close() -{ - if (!sb.close()) - this->setstate(std::ios_base::failbit); -} - -/*****************************************************************************/ - -// Default constructor initializes stream buffer -gzofstream::gzofstream() -: std::ostream(NULL), sb() -{ this->init(&sb); } - -// Initialize stream buffer and open file -gzofstream::gzofstream(const char* name, - std::ios_base::openmode mode) -: std::ostream(NULL), sb() -{ - this->init(&sb); - this->open(name, mode); -} - -// Initialize stream buffer and attach to file -gzofstream::gzofstream(int fd, - std::ios_base::openmode mode) -: std::ostream(NULL), sb() -{ - this->init(&sb); - this->attach(fd, mode); -} - -// Open file and go into fail() state if unsuccessful -void -gzofstream::open(const char* name, - std::ios_base::openmode mode) -{ - if (!sb.open(name, mode | std::ios_base::out)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Attach to file and go into fail() state if unsuccessful -void -gzofstream::attach(int fd, - std::ios_base::openmode mode) -{ - if (!sb.attach(fd, mode | std::ios_base::out)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Close file -void -gzofstream::close() -{ - if (!sb.close()) - this->setstate(std::ios_base::failbit); -} diff --git a/deps/zlib/contrib/iostream3/zfstream.h b/deps/zlib/contrib/iostream3/zfstream.h deleted file mode 100644 index 8574479ae1e7cd..00000000000000 --- a/deps/zlib/contrib/iostream3/zfstream.h +++ /dev/null @@ -1,466 +0,0 @@ -/* - * A C++ I/O streams interface to the zlib gz* functions - * - * by Ludwig Schwardt - * original version by Kevin Ruland - * - * This version is standard-compliant and compatible with gcc 3.x. - */ - -#ifndef ZFSTREAM_H -#define ZFSTREAM_H - -#include // not iostream, since we don't need cin/cout -#include -#include "zlib.h" - -/*****************************************************************************/ - -/** - * @brief Gzipped file stream buffer class. - * - * This class implements basic_filebuf for gzipped files. It doesn't yet support - * seeking (allowed by zlib but slow/limited), putback and read/write access - * (tricky). Otherwise, it attempts to be a drop-in replacement for the standard - * file streambuf. -*/ -class gzfilebuf : public std::streambuf -{ -public: - // Default constructor. - gzfilebuf(); - - // Destructor. - virtual - ~gzfilebuf(); - - /** - * @brief Set compression level and strategy on the fly. - * @param comp_level Compression level (see zlib.h for allowed values) - * @param comp_strategy Compression strategy (see zlib.h for allowed values) - * @return Z_OK on success, Z_STREAM_ERROR otherwise. - * - * Unfortunately, these parameters cannot be modified separately, as the - * previous zfstream version assumed. Since the strategy is seldom changed, - * it can default and setcompression(level) then becomes like the old - * setcompressionlevel(level). - */ - int - setcompression(int comp_level, - int comp_strategy = Z_DEFAULT_STRATEGY); - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() const { return (file != NULL); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - open(const char* name, - std::ios_base::openmode mode); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - attach(int fd, - std::ios_base::openmode mode); - - /** - * @brief Close gzipped file. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - close(); - -protected: - /** - * @brief Convert ios open mode int to mode string used by zlib. - * @return True if valid mode flag combination. - */ - bool - open_mode(std::ios_base::openmode mode, - char* c_mode) const; - - /** - * @brief Number of characters available in stream buffer. - * @return Number of characters. - * - * This indicates number of characters in get area of stream buffer. - * These characters can be read without accessing the gzipped file. - */ - virtual std::streamsize - showmanyc(); - - /** - * @brief Fill get area from gzipped file. - * @return First character in get area on success, EOF on error. - * - * This actually reads characters from gzipped file to stream - * buffer. Always buffered. - */ - virtual int_type - underflow(); - - /** - * @brief Write put area to gzipped file. - * @param c Extra character to add to buffer contents. - * @return Non-EOF on success, EOF on error. - * - * This actually writes characters in stream buffer to - * gzipped file. With unbuffered output this is done one - * character at a time. - */ - virtual int_type - overflow(int_type c = traits_type::eof()); - - /** - * @brief Installs external stream buffer. - * @param p Pointer to char buffer. - * @param n Size of external buffer. - * @return @c this on success, NULL on failure. - * - * Call setbuf(0,0) to enable unbuffered output. - */ - virtual std::streambuf* - setbuf(char_type* p, - std::streamsize n); - - /** - * @brief Flush stream buffer to file. - * @return 0 on success, -1 on error. - * - * This calls underflow(EOF) to do the job. - */ - virtual int - sync(); - -// -// Some future enhancements -// -// virtual int_type uflow(); -// virtual int_type pbackfail(int_type c = traits_type::eof()); -// virtual pos_type -// seekoff(off_type off, -// std::ios_base::seekdir way, -// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); -// virtual pos_type -// seekpos(pos_type sp, -// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); - -private: - /** - * @brief Allocate internal buffer. - * - * This function is safe to call multiple times. It will ensure - * that a proper internal buffer exists if it is required. If the - * buffer already exists or is external, the buffer pointers will be - * reset to their original state. - */ - void - enable_buffer(); - - /** - * @brief Destroy internal buffer. - * - * This function is safe to call multiple times. It will ensure - * that the internal buffer is deallocated if it exists. In any - * case, it will also reset the buffer pointers. - */ - void - disable_buffer(); - - /** - * Underlying file pointer. - */ - gzFile file; - - /** - * Mode in which file was opened. - */ - std::ios_base::openmode io_mode; - - /** - * @brief True if this object owns file descriptor. - * - * This makes the class responsible for closing the file - * upon destruction. - */ - bool own_fd; - - /** - * @brief Stream buffer. - * - * For simplicity this remains allocated on the free store for the - * entire life span of the gzfilebuf object, unless replaced by setbuf. - */ - char_type* buffer; - - /** - * @brief Stream buffer size. - * - * Defaults to system default buffer size (typically 8192 bytes). - * Modified by setbuf. - */ - std::streamsize buffer_size; - - /** - * @brief True if this object owns stream buffer. - * - * This makes the class responsible for deleting the buffer - * upon destruction. - */ - bool own_buffer; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file input stream class. - * - * This class implements ifstream for gzipped files. Seeking and putback - * is not supported yet. -*/ -class gzifstream : public std::istream -{ -public: - // Default constructor - gzifstream(); - - /** - * @brief Construct stream on gzipped file to be opened. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::in). - */ - explicit - gzifstream(const char* name, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Construct stream on already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::in). - */ - explicit - gzifstream(int fd, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * Obtain underlying stream buffer. - */ - gzfilebuf* - rdbuf() const - { return const_cast(&sb); } - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() { return sb.is_open(); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::in). - * - * Stream will be in state good() if file opens successfully; - * otherwise in state fail(). This differs from the behavior of - * ifstream, which never sets the state to good() and therefore - * won't allow you to reuse the stream for a second file unless - * you manually clear() the state. The choice is a matter of - * convenience. - */ - void - open(const char* name, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::in). - * - * Stream will be in state good() if attach succeeded; otherwise - * in state fail(). - */ - void - attach(int fd, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Close gzipped file. - * - * Stream will be in state fail() if close failed. - */ - void - close(); - -private: - /** - * Underlying stream buffer. - */ - gzfilebuf sb; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file output stream class. - * - * This class implements ofstream for gzipped files. Seeking and putback - * is not supported yet. -*/ -class gzofstream : public std::ostream -{ -public: - // Default constructor - gzofstream(); - - /** - * @brief Construct stream on gzipped file to be opened. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::out). - */ - explicit - gzofstream(const char* name, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Construct stream on already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::out). - */ - explicit - gzofstream(int fd, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * Obtain underlying stream buffer. - */ - gzfilebuf* - rdbuf() const - { return const_cast(&sb); } - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() { return sb.is_open(); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::out). - * - * Stream will be in state good() if file opens successfully; - * otherwise in state fail(). This differs from the behavior of - * ofstream, which never sets the state to good() and therefore - * won't allow you to reuse the stream for a second file unless - * you manually clear() the state. The choice is a matter of - * convenience. - */ - void - open(const char* name, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::out). - * - * Stream will be in state good() if attach succeeded; otherwise - * in state fail(). - */ - void - attach(int fd, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Close gzipped file. - * - * Stream will be in state fail() if close failed. - */ - void - close(); - -private: - /** - * Underlying stream buffer. - */ - gzfilebuf sb; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file output stream manipulator class. - * - * This class defines a two-argument manipulator for gzofstream. It is used - * as base for the setcompression(int,int) manipulator. -*/ -template - class gzomanip2 - { - public: - // Allows insertor to peek at internals - template - friend gzofstream& - operator<<(gzofstream&, - const gzomanip2&); - - // Constructor - gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2), - T1 v1, - T2 v2); - private: - // Underlying manipulator function - gzofstream& - (*func)(gzofstream&, T1, T2); - - // Arguments for manipulator function - T1 val1; - T2 val2; - }; - -/*****************************************************************************/ - -// Manipulator function thunks through to stream buffer -inline gzofstream& -setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY) -{ - (gzs.rdbuf())->setcompression(l, s); - return gzs; -} - -// Manipulator constructor stores arguments -template - inline - gzomanip2::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2), - T1 v1, - T2 v2) - : func(f), val1(v1), val2(v2) - { } - -// Insertor applies underlying manipulator function to stream -template - inline gzofstream& - operator<<(gzofstream& s, const gzomanip2& m) - { return (*m.func)(s, m.val1, m.val2); } - -// Insert this onto stream to simplify setting of compression level -inline gzomanip2 -setcompression(int l, int s = Z_DEFAULT_STRATEGY) -{ return gzomanip2(&setcompression, l, s); } - -#endif // ZFSTREAM_H diff --git a/deps/zlib/contrib/masmx64/bld_ml64.bat b/deps/zlib/contrib/masmx64/bld_ml64.bat deleted file mode 100644 index f74bcef5b48d39..00000000000000 --- a/deps/zlib/contrib/masmx64/bld_ml64.bat +++ /dev/null @@ -1,2 +0,0 @@ -ml64.exe /Flinffasx64 /c /Zi inffasx64.asm -ml64.exe /Flgvmat64 /c /Zi gvmat64.asm diff --git a/deps/zlib/contrib/masmx64/gvmat64.asm b/deps/zlib/contrib/masmx64/gvmat64.asm deleted file mode 100644 index c1817f1be96d96..00000000000000 --- a/deps/zlib/contrib/masmx64/gvmat64.asm +++ /dev/null @@ -1,553 +0,0 @@ -;uInt longest_match_x64( -; deflate_state *s, -; IPos cur_match); /* current match */ - -; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64 -; (AMD64 on Athlon 64, Opteron, Phenom -; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) -; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; -; File written by Gilles Vollant, by converting to assembly the longest_match -; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. -; -; and by taking inspiration on asm686 with masm, optimised assembly code -; from Brian Raiter, written 1998 -; -; This software is provided 'as-is', without any express or implied -; warranty. In no event will the authors be held liable for any damages -; arising from the use of this software. -; -; Permission is granted to anyone to use this software for any purpose, -; including commercial applications, and to alter it and redistribute it -; freely, subject to the following restrictions: -; -; 1. The origin of this software must not be misrepresented; you must not -; claim that you wrote the original software. If you use this software -; in a product, an acknowledgment in the product documentation would be -; appreciated but is not required. -; 2. Altered source versions must be plainly marked as such, and must not be -; misrepresented as being the original software -; 3. This notice may not be removed or altered from any source distribution. -; -; -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; to compile this file for infozip Zip, I use option: -; ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm -; -; to compile this file for zLib, I use option: -; ml64.exe /Flgvmat64 /c /Zi gvmat64.asm -; Be carrefull to adapt zlib1222add below to your version of zLib -; (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change -; value of zlib1222add later) -; -; This file compile with Microsoft Macro Assembler (x64) for AMD64 -; -; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK -; -; (you can get Windows WDK with ml64 for AMD64 from -; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) -; - - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; /* current match */ -.code -longest_match PROC - - -;LocalVarsSize equ 88 - LocalVarsSize equ 72 - -; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 -; free register : r14,r15 -; register can be saved : rsp - - chainlenwmask equ rsp + 8 - LocalVarsSize ; high word: current chain len - ; low word: s->wmask -;window equ rsp + xx - LocalVarsSize ; local copy of s->window ; stored in r10 -;windowbestlen equ rsp + xx - LocalVarsSize ; s->window + bestlen , use r10+r11 -;scanstart equ rsp + xx - LocalVarsSize ; first two bytes of string ; stored in r12w -;scanend equ rsp + xx - LocalVarsSize ; last two bytes of string use ebx -;scanalign equ rsp + xx - LocalVarsSize ; dword-misalignment of string r13 -;bestlen equ rsp + xx - LocalVarsSize ; size of best match so far -> r11d -;scan equ rsp + xx - LocalVarsSize ; ptr to string wanting match -> r9 -IFDEF INFOZIP -ELSE - nicematch equ (rsp + 16 - LocalVarsSize) ; a good enough match size -ENDIF - -save_rdi equ rsp + 24 - LocalVarsSize -save_rsi equ rsp + 32 - LocalVarsSize -save_rbx equ rsp + 40 - LocalVarsSize -save_rbp equ rsp + 48 - LocalVarsSize -save_r12 equ rsp + 56 - LocalVarsSize -save_r13 equ rsp + 64 - LocalVarsSize -;save_r14 equ rsp + 72 - LocalVarsSize -;save_r15 equ rsp + 80 - LocalVarsSize - - -; summary of register usage -; scanend ebx -; scanendw bx -; chainlenwmask edx -; curmatch rsi -; curmatchd esi -; windowbestlen r8 -; scanalign r9 -; scanalignd r9d -; window r10 -; bestlen r11 -; bestlend r11d -; scanstart r12d -; scanstartw r12w -; scan r13 -; nicematch r14d -; limit r15 -; limitd r15d -; prev rcx - -; all the +4 offsets are due to the addition of pending_buf_size (in zlib -; in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, remove the +4). -; Note : these value are good with a 8 bytes boundary pack structure - - - MAX_MATCH equ 258 - MIN_MATCH equ 3 - MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) - - -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - - -IFDEF INFOZIP - -_DATA SEGMENT -COMM window_size:DWORD -; WMask ; 7fff -COMM window:BYTE:010040H -COMM prev:WORD:08000H -; MatchLen : unused -; PrevMatch : unused -COMM strstart:DWORD -COMM match_start:DWORD -; Lookahead : ignore -COMM prev_length:DWORD ; PrevLen -COMM max_chain_length:DWORD -COMM good_match:DWORD -COMM nice_match:DWORD -prev_ad equ OFFSET prev -window_ad equ OFFSET window -nicematch equ nice_match -_DATA ENDS -WMask equ 07fffh - -ELSE - - IFNDEF zlib1222add - zlib1222add equ 8 - ENDIF -dsWSize equ 56+zlib1222add+(zlib1222add/2) -dsWMask equ 64+zlib1222add+(zlib1222add/2) -dsWindow equ 72+zlib1222add -dsPrev equ 88+zlib1222add -dsMatchLen equ 128+zlib1222add -dsPrevMatch equ 132+zlib1222add -dsStrStart equ 140+zlib1222add -dsMatchStart equ 144+zlib1222add -dsLookahead equ 148+zlib1222add -dsPrevLen equ 152+zlib1222add -dsMaxChainLen equ 156+zlib1222add -dsGoodMatch equ 172+zlib1222add -dsNiceMatch equ 176+zlib1222add - -window_size equ [ rcx + dsWSize] -WMask equ [ rcx + dsWMask] -window_ad equ [ rcx + dsWindow] -prev_ad equ [ rcx + dsPrev] -strstart equ [ rcx + dsStrStart] -match_start equ [ rcx + dsMatchStart] -Lookahead equ [ rcx + dsLookahead] ; 0ffffffffh on infozip -prev_length equ [ rcx + dsPrevLen] -max_chain_length equ [ rcx + dsMaxChainLen] -good_match equ [ rcx + dsGoodMatch] -nice_match equ [ rcx + dsNiceMatch] -ENDIF - -; parameter 1 in r8(deflate state s), param 2 in rdx (cur match) - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. - - - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - -;;; Retrieve the function arguments. r8d will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - -; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) - -; this clear high 32 bits of r8, which can be garbage in both r8 and rdx - - mov [save_rdi],rdi - mov [save_rsi],rsi - mov [save_rbx],rbx - mov [save_rbp],rbp -IFDEF INFOZIP - mov r8d,ecx -ELSE - mov r8d,edx -ENDIF - mov [save_r12],r12 - mov [save_r13],r13 -; mov [save_r14],r14 -; mov [save_r15],r15 - - -;;; uInt wmask = s->w_mask; -;;; unsigned chain_length = s->max_chain_length; -;;; if (s->prev_length >= s->good_match) { -;;; chain_length >>= 2; -;;; } - - mov edi, prev_length - mov esi, good_match - mov eax, WMask - mov ebx, max_chain_length - cmp edi, esi - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -;;; chainlen is decremented once beforehand so that the function can -;;; use the sign flag instead of the zero flag for the exit test. -;;; It is then shifted into the high word, to make room for the wmask -;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - -;;; on zlib only -;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - -IFDEF INFOZIP - mov [chainlenwmask], ebx -; on infozip nice_match = [nice_match] -ELSE - mov eax, nice_match - mov [chainlenwmask], ebx - mov r10d, Lookahead - cmp r10d, eax - cmovnl r10d, eax - mov [nicematch],r10d -ENDIF - -;;; register Bytef *scan = s->window + s->strstart; - mov r10, window_ad - mov ebp, strstart - lea r13, [r10 + rbp] - -;;; Determine how many bytes the scan ptr is off from being -;;; dword-aligned. - - mov r9,r13 - neg r13 - and r13,3 - -;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -;;; s->strstart - (IPos)MAX_DIST(s) : NIL; -IFDEF INFOZIP - mov eax,07efah ; MAX_DIST = (WSIZE-MIN_LOOKAHEAD) (0x8000-(3+8+1)) -ELSE - mov eax, window_size - sub eax, MIN_LOOKAHEAD -ENDIF - xor edi,edi - sub ebp, eax - - mov r11d, prev_length - - cmovng ebp,edi - -;;; int best_len = s->prev_length; - - -;;; Store the sum of s->window + best_len in esi locally, and in esi. - - lea rsi,[r10+r11] - -;;; register ush scan_start = *(ushf*)scan; -;;; register ush scan_end = *(ushf*)(scan+best_len-1); -;;; Posf *prev = s->prev; - - movzx r12d,word ptr [r9] - movzx ebx, word ptr [r9 + r11 - 1] - - mov rdi, prev_ad - -;;; Jump into the main loop. - - mov edx, [chainlenwmask] - - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop1: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry1: - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop2: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry2: - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop4: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry4: - - cmp bx,word ptr [rsi + r8 - 1] - jnz LookupLoop1 - jmp LookupLoopIsZero - - -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; r8d = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit - -LookupLoop: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry: - - cmp bx,word ptr [rsi + r8 - 1] - jnz LookupLoop1 -LookupLoopIsZero: - cmp r12w, word ptr [r10 + r8] - jnz LookupLoop1 - - -;;; Store the current value of chainlen. - mov [chainlenwmask], edx - -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). - - lea rsi,[r8+r10] - mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8) - lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8] - lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8] - - prefetcht1 [rsi+rdx] - prefetcht1 [rdi+rdx] - - -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust rdx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (rsi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. - - -LoopCmps: - mov rax, [rsi + rdx] - xor rax, [rdi + rdx] - jnz LeaveLoopCmps - - mov rax, [rsi + rdx + 8] - xor rax, [rdi + rdx + 8] - jnz LeaveLoopCmps8 - - - mov rax, [rsi + rdx + 8+8] - xor rax, [rdi + rdx + 8+8] - jnz LeaveLoopCmps16 - - add rdx,8+8+8 - - jnz short LoopCmps - jmp short LenMaximum -LeaveLoopCmps16: add rdx,8 -LeaveLoopCmps8: add rdx,8 -LeaveLoopCmps: - - test eax, 0000FFFFh - jnz LenLower - - test eax,0ffffffffh - - jnz LenLower32 - - add rdx,4 - shr rax,32 - or ax,ax - jnz LenLower - -LenLower32: - shr eax,16 - add rdx,2 -LenLower: sub al, 1 - adc rdx, 0 -;;; Calculate the length of the match. If it is longer than MAX_MATCH, -;;; then automatically accept it as the best possible match and leave. - - lea rax, [rdi + rdx] - sub rax, r9 - cmp eax, MAX_MATCH - jge LenMaximum - -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. -;/////////////////////////////////// - - cmp eax, r11d - jg LongerMatch - - lea rsi,[r10+r11] - - mov rdi, prev_ad - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); - -LongerMatch: - mov r11d, eax - mov match_start, r8d - cmp eax, [nicematch] - jge LeaveNow - - lea rsi,[r10+rax] - - movzx ebx, word ptr [r9 + rax - 1] - mov rdi, prev_ad - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; Accept the current string, with the maximum possible length. - -LenMaximum: - mov r11d,MAX_MATCH - mov match_start, r8d - -;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -;;; return s->lookahead; - -LeaveNow: -IFDEF INFOZIP - mov eax,r11d -ELSE - mov eax, Lookahead - cmp r11d, eax - cmovng eax, r11d -ENDIF - -;;; Restore the stack and return from whence we came. - - - mov rsi,[save_rsi] - mov rdi,[save_rdi] - mov rbx,[save_rbx] - mov rbp,[save_rbp] - mov r12,[save_r12] - mov r13,[save_r13] -; mov r14,[save_r14] -; mov r15,[save_r15] - - - ret 0 -; please don't remove this string ! -; Your can freely use gvmat64 in any free or commercial app -; but it is far better don't remove the string in the binary! - db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 -longest_match ENDP - -match_init PROC - ret 0 -match_init ENDP - - -END diff --git a/deps/zlib/contrib/masmx64/inffas8664.c b/deps/zlib/contrib/masmx64/inffas8664.c deleted file mode 100644 index aa861a33392ffc..00000000000000 --- a/deps/zlib/contrib/masmx64/inffas8664.c +++ /dev/null @@ -1,186 +0,0 @@ -/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding - * version for AMD64 on Windows using Microsoft C compiler - * - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * 2005 - Adaptation to Microsoft C Compiler for AMD64 by Gilles Vollant - * - * inffas8664.c call function inffas8664fnc in inffasx64.asm - * inffasx64.asm is automatically convert from AMD64 portion of inffas86.c - * - * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also - * slightly quicker on x86 systems because, instead of using rep movsb to copy - * data, it uses rep movsw, which moves data in 2-byte chunks instead of single - * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates - * from http://fedora.linux.duke.edu/fc1_x86_64 - * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with - * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, - * when decompressing mozilla-source-1.3.tar.gz. - * - * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from - * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at - * the moment. I have successfully compiled and tested this code with gcc2.96, - * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S - * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX - * enabled. I will attempt to merge the MMX code into this version. Newer - * versions of this and inffast.S can be found at - * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ - * - */ - -#include -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* Mark Adler's comments from inffast.c: */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ - - - - typedef struct inffast_ar { -/* 64 32 x86 x86_64 */ -/* ar offset register */ -/* 0 0 */ void *esp; /* esp save */ -/* 8 4 */ void *ebp; /* ebp save */ -/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ -/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ -/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ -/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ -/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ -/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ -/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ -/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ -/* 80 40 */ size_t /*unsigned long */hold; /* edx rdx local strm->hold */ -/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ -/* 92 48 */ unsigned wsize; /* window size */ -/* 96 52 */ unsigned write; /* window write index */ -/*100 56 */ unsigned lmask; /* r12 mask for lcode */ -/*104 60 */ unsigned dmask; /* r13 mask for dcode */ -/*108 64 */ unsigned len; /* r14 match length */ -/*112 68 */ unsigned dist; /* r15 match distance */ -/*116 72 */ unsigned status; /* set when state chng*/ - } type_ar; -#ifdef ASMINF - -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - type_ar ar; - void inffas8664fnc(struct inffast_ar * par); - - - -#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) -#define PAD_AVAIL_IN 6 -#define PAD_AVAIL_OUT 258 -#else -#define PAD_AVAIL_IN 5 -#define PAD_AVAIL_OUT 257 -#endif - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - - ar.in = strm->next_in; - ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); - ar.out = strm->next_out; - ar.beg = ar.out - (start - strm->avail_out); - ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); - ar.wsize = state->wsize; - ar.write = state->wnext; - ar.window = state->window; - ar.hold = state->hold; - ar.bits = state->bits; - ar.lcode = state->lencode; - ar.dcode = state->distcode; - ar.lmask = (1U << state->lenbits) - 1; - ar.dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - /* align in on 1/2 hold size boundary */ - while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { - ar.hold += (unsigned long)*ar.in++ << ar.bits; - ar.bits += 8; - } - - inffas8664fnc(&ar); - - if (ar.status > 1) { - if (ar.status == 2) - strm->msg = "invalid literal/length code"; - else if (ar.status == 3) - strm->msg = "invalid distance code"; - else - strm->msg = "invalid distance too far back"; - state->mode = BAD; - } - else if ( ar.status == 1 ) { - state->mode = TYPE; - } - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - ar.len = ar.bits >> 3; - ar.in -= ar.len; - ar.bits -= ar.len << 3; - ar.hold &= (1U << ar.bits) - 1; - - /* update state and return */ - strm->next_in = ar.in; - strm->next_out = ar.out; - strm->avail_in = (unsigned)(ar.in < ar.last ? - PAD_AVAIL_IN + (ar.last - ar.in) : - PAD_AVAIL_IN - (ar.in - ar.last)); - strm->avail_out = (unsigned)(ar.out < ar.end ? - PAD_AVAIL_OUT + (ar.end - ar.out) : - PAD_AVAIL_OUT - (ar.out - ar.end)); - state->hold = (unsigned long)ar.hold; - state->bits = ar.bits; - return; -} - -#endif diff --git a/deps/zlib/contrib/masmx64/inffasx64.asm b/deps/zlib/contrib/masmx64/inffasx64.asm deleted file mode 100644 index 41ec82392ed03d..00000000000000 --- a/deps/zlib/contrib/masmx64/inffasx64.asm +++ /dev/null @@ -1,396 +0,0 @@ -; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding -; version for AMD64 on Windows using Microsoft C compiler -; -; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c -; inffasx64.asm is called by inffas8664.c, which contain more info. - - -; to compile this file, I use option -; ml64.exe /Flinffasx64 /c /Zi inffasx64.asm -; with Microsoft Macro Assembler (x64) for AMD64 -; - -; This file compile with Microsoft Macro Assembler (x64) for AMD64 -; -; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK -; -; (you can get Windows WDK with ml64 for AMD64 from -; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) -; - - -.code -inffas8664fnc PROC - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch. - - - mov [rsp-8],rsi - mov [rsp-16],rdi - mov [rsp-24],r12 - mov [rsp-32],r13 - mov [rsp-40],r14 - mov [rsp-48],r15 - mov [rsp-56],rbx - - mov rax,rcx - - mov [rax+8], rbp ; /* save regs rbp and rsp */ - mov [rax], rsp - - mov rsp, rax ; /* make rsp point to &ar */ - - mov rsi, [rsp+16] ; /* rsi = in */ - mov rdi, [rsp+32] ; /* rdi = out */ - mov r9, [rsp+24] ; /* r9 = last */ - mov r10, [rsp+48] ; /* r10 = end */ - mov rbp, [rsp+64] ; /* rbp = lcode */ - mov r11, [rsp+72] ; /* r11 = dcode */ - mov rdx, [rsp+80] ; /* rdx = hold */ - mov ebx, [rsp+88] ; /* ebx = bits */ - mov r12d, [rsp+100] ; /* r12d = lmask */ - mov r13d, [rsp+104] ; /* r13d = dmask */ - ; /* r14d = len */ - ; /* r15d = dist */ - - - cld - cmp r10, rdi - je L_one_time ; /* if only one decode left */ - cmp r9, rsi - - jne L_do_loop - - -L_one_time: - mov r8, r12 ; /* r8 = lmask */ - cmp bl, 32 - ja L_get_length_code_one_time - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - jmp L_get_length_code_one_time - -ALIGN 4 -L_while_test: - cmp r10, rdi - jbe L_break_loop - cmp r9, rsi - jbe L_break_loop - -L_do_loop: - mov r8, r12 ; /* r8 = lmask */ - cmp bl, 32 - ja L_get_length_code ; /* if (32 < bits) */ - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - -L_get_length_code: - and r8, rdx ; /* r8 &= hold */ - mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ - - mov cl, ah ; /* cl = this.bits */ - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ - - mov r8, r12 ; /* r8 = lmask */ - shr eax, 16 ; /* output this.val char */ - stosb - -L_get_length_code_one_time: - and r8, rdx ; /* r8 &= hold */ - mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ - -L_dolen: - mov cl, ah ; /* cl = this.bits */ - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ - - shr eax, 16 ; /* output this.val char */ - stosb - jmp L_while_test - -ALIGN 4 -L_test_for_length_base: - mov r14d, eax ; /* len = this */ - shr r14d, 16 ; /* len = this.val */ - mov cl, al - - test al, 16 - jz L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */ - and cl, 15 ; /* op &= 15 */ - jz L_decode_distance ; /* if (!op) */ - -L_add_bits_to_len: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - shr rdx, cl - add r14d, eax ; /* len += hold & mask[op] */ - -L_decode_distance: - mov r8, r13 ; /* r8 = dmask */ - cmp bl, 32 - ja L_get_distance_code ; /* if (32 < bits) */ - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - -L_get_distance_code: - and r8, rdx ; /* r8 &= hold */ - mov eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */ - -L_dodist: - mov r15d, eax ; /* dist = this */ - shr r15d, 16 ; /* dist = this.val */ - mov cl, ah - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - mov cl, al ; /* cl = this.op */ - - test al, 16 ; /* if ((op & 16) == 0) */ - jz L_test_for_second_level_dist - and cl, 15 ; /* op &= 15 */ - jz L_check_dist_one - -L_add_bits_to_dist: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax ; /* (1 << op) - 1 */ - and eax, edx ; /* eax &= hold */ - shr rdx, cl - add r15d, eax ; /* dist += hold & ((1 << op) - 1) */ - -L_check_window: - mov r8, rsi ; /* save in so from can use it's reg */ - mov rax, rdi - sub rax, [rsp+40] ; /* nbytes = out - beg */ - - cmp eax, r15d - jb L_clip_window ; /* if (dist > nbytes) 4.2% */ - - mov ecx, r14d ; /* ecx = len */ - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - - sar ecx, 1 - jnc L_copy_two ; /* if len % 2 == 0 */ - - rep movsw - mov al, [rsi] - mov [rdi], al - inc rdi - - mov rsi, r8 ; /* move in back to %rsi, toss from */ - jmp L_while_test - -L_copy_two: - rep movsw - mov rsi, r8 ; /* move in back to %rsi, toss from */ - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp r15d, 1 ; /* if dist 1, is a memset */ - jne L_check_window - cmp [rsp+40], rdi ; /* if out == beg, outside window */ - je L_check_window - - mov ecx, r14d ; /* ecx = len */ - mov al, [rdi-1] - mov ah, al - - sar ecx, 1 - jnc L_set_two - mov [rdi], al - inc rdi - -L_set_two: - rep stosw - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - test al, 64 - jnz L_test_for_end_of_block ; /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - add eax, r14d ; /* eax += len */ - mov eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/ - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - test al, 64 - jnz L_invalid_distance_code ; /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - add eax, r15d ; /* eax += dist */ - mov eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/ - jmp L_dodist - -ALIGN 4 -L_clip_window: - mov ecx, eax ; /* ecx = nbytes */ - mov eax, [rsp+92] ; /* eax = wsize, prepare for dist cmp */ - neg ecx ; /* nbytes = -nbytes */ - - cmp eax, r15d - jb L_invalid_distance_too_far ; /* if (dist > wsize) */ - - add ecx, r15d ; /* nbytes = dist - nbytes */ - cmp dword ptr [rsp+96], 0 - jne L_wrap_around_window ; /* if (write != 0) */ - - mov rsi, [rsp+56] ; /* from = window */ - sub eax, ecx ; /* eax -= nbytes */ - add rsi, rax ; /* from += wsize - nbytes */ - - mov eax, r14d ; /* eax = len */ - cmp r14d, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* eax -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = &out[ -dist ] */ - jmp L_do_copy - -ALIGN 4 -L_wrap_around_window: - mov eax, [rsp+96] ; /* eax = write */ - cmp ecx, eax - jbe L_contiguous_in_window ; /* if (write >= nbytes) */ - - mov esi, [rsp+92] ; /* from = wsize */ - add rsi, [rsp+56] ; /* from += window */ - add rsi, rax ; /* from += write */ - sub rsi, rcx ; /* from -= nbytes */ - sub ecx, eax ; /* nbytes -= write */ - - mov eax, r14d ; /* eax = len */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, [rsp+56] ; /* from = window */ - mov ecx, [rsp+96] ; /* nbytes = write */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_contiguous_in_window: - mov rsi, [rsp+56] ; /* rsi = window */ - add rsi, rax - sub rsi, rcx ; /* from += write - nbytes */ - - mov eax, r14d ; /* eax = len */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - jmp L_do_copy ; /* if (nbytes >= len) */ - -ALIGN 4 -L_do_copy: - mov ecx, eax ; /* ecx = len */ - rep movsb - - mov rsi, r8 ; /* move in back to %esi, toss from */ - jmp L_while_test - -L_test_for_end_of_block: - test al, 32 - jz L_invalid_literal_length_code - mov dword ptr [rsp+116], 1 - jmp L_break_loop_with_status - -L_invalid_literal_length_code: - mov dword ptr [rsp+116], 2 - jmp L_break_loop_with_status - -L_invalid_distance_code: - mov dword ptr [rsp+116], 3 - jmp L_break_loop_with_status - -L_invalid_distance_too_far: - mov dword ptr [rsp+116], 4 - jmp L_break_loop_with_status - -L_break_loop: - mov dword ptr [rsp+116], 0 - -L_break_loop_with_status: -; /* put in, out, bits, and hold back into ar and pop esp */ - mov [rsp+16], rsi ; /* in */ - mov [rsp+32], rdi ; /* out */ - mov [rsp+88], ebx ; /* bits */ - mov [rsp+80], rdx ; /* hold */ - - mov rax, [rsp] ; /* restore rbp and rsp */ - mov rbp, [rsp+8] - mov rsp, rax - - - - mov rsi,[rsp-8] - mov rdi,[rsp-16] - mov r12,[rsp-24] - mov r13,[rsp-32] - mov r14,[rsp-40] - mov r15,[rsp-48] - mov rbx,[rsp-56] - - ret 0 -; : -; : "m" (ar) -; : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", -; "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" -; ); - -inffas8664fnc ENDP -;_TEXT ENDS -END diff --git a/deps/zlib/contrib/masmx64/readme.txt b/deps/zlib/contrib/masmx64/readme.txt deleted file mode 100644 index 652571c7a52546..00000000000000 --- a/deps/zlib/contrib/masmx64/readme.txt +++ /dev/null @@ -1,31 +0,0 @@ -Summary -------- -This directory contains ASM implementations of the functions -longest_match() and inflate_fast(), for 64 bits x86 (both AMD64 and Intel EM64t), -for use with Microsoft Macro Assembler (x64) for AMD64 and Microsoft C++ 64 bits. - -gvmat64.asm is written by Gilles Vollant (2005), by using Brian Raiter 686/32 bits - assembly optimized version from Jean-loup Gailly original longest_match function - -inffasx64.asm and inffas8664.c were written by Chris Anderson, by optimizing - original function from Mark Adler - -Use instructions ----------------- -Assemble the .asm files using MASM and put the object files into the zlib source -directory. You can also get object files here: - - http://www.winimage.com/zLibDll/zlib124_masm_obj.zip - -define ASMV and ASMINF in your project. Include inffas8664.c in your source tree, -and inffasx64.obj and gvmat64.obj as object to link. - - -Build instructions ------------------- -run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe) - -ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK - -You can get Windows 2003 server DDK with ml64 and cl for AMD64 from - http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) diff --git a/deps/zlib/contrib/masmx86/bld_ml32.bat b/deps/zlib/contrib/masmx86/bld_ml32.bat deleted file mode 100644 index fcf5755e46aed8..00000000000000 --- a/deps/zlib/contrib/masmx86/bld_ml32.bat +++ /dev/null @@ -1,2 +0,0 @@ -ml /coff /Zi /c /Flmatch686.lst match686.asm -ml /coff /Zi /c /Flinffas32.lst inffas32.asm diff --git a/deps/zlib/contrib/masmx86/inffas32.asm b/deps/zlib/contrib/masmx86/inffas32.asm deleted file mode 100644 index cb37a81e4eea5a..00000000000000 --- a/deps/zlib/contrib/masmx86/inffas32.asm +++ /dev/null @@ -1,1080 +0,0 @@ -;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding -; * -; * inffas32.asm is derivated from inffas86.c, with translation of assembly code -; * -; * Copyright (C) 1995-2003 Mark Adler -; * For conditions of distribution and use, see copyright notice in zlib.h -; * -; * Copyright (C) 2003 Chris Anderson -; * Please use the copyright conditions above. -; * -; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from -; * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at -; * the moment. I have successfully compiled and tested this code with gcc2.96, -; * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S -; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX -; * enabled. I will attempt to merge the MMX code into this version. Newer -; * versions of this and inffast.S can be found at -; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ -; * -; * 2005 : modification by Gilles Vollant -; */ -; For Visual C++ 4.x and higher and ML 6.x and higher -; ml.exe is in directory \MASM611C of Win95 DDK -; ml.exe is also distributed in http://www.masm32.com/masmdl.htm -; and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/ -; -; -; compile with command line option -; ml /coff /Zi /c /Flinffas32.lst inffas32.asm - -; if you define NO_GZIP (see inflate.h), compile with -; ml /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm - - -; zlib122sup is 0 fort zlib 1.2.2.1 and lower -; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head -; in inflate_state in inflate.h) -zlib1222sup equ 8 - - -IFDEF GUNZIP - INFLATE_MODE_TYPE equ 11 - INFLATE_MODE_BAD equ 26 -ELSE - IFNDEF NO_GUNZIP - INFLATE_MODE_TYPE equ 11 - INFLATE_MODE_BAD equ 26 - ELSE - INFLATE_MODE_TYPE equ 3 - INFLATE_MODE_BAD equ 17 - ENDIF -ENDIF - - -; 75 "inffast.S" -;FILE "inffast.S" - -;;;GLOBAL _inflate_fast - -;;;SECTION .text - - - - .586p - .mmx - - name inflate_fast_x86 - .MODEL FLAT - -_DATA segment -inflate_fast_use_mmx: - dd 1 - - -_TEXT segment - - - -ALIGN 4 - db 'Fast decoding Code from Chris Anderson' - db 0 - -ALIGN 4 -invalid_literal_length_code_msg: - db 'invalid literal/length code' - db 0 - -ALIGN 4 -invalid_distance_code_msg: - db 'invalid distance code' - db 0 - -ALIGN 4 -invalid_distance_too_far_msg: - db 'invalid distance too far back' - db 0 - - -ALIGN 4 -inflate_fast_mask: -dd 0 -dd 1 -dd 3 -dd 7 -dd 15 -dd 31 -dd 63 -dd 127 -dd 255 -dd 511 -dd 1023 -dd 2047 -dd 4095 -dd 8191 -dd 16383 -dd 32767 -dd 65535 -dd 131071 -dd 262143 -dd 524287 -dd 1048575 -dd 2097151 -dd 4194303 -dd 8388607 -dd 16777215 -dd 33554431 -dd 67108863 -dd 134217727 -dd 268435455 -dd 536870911 -dd 1073741823 -dd 2147483647 -dd 4294967295 - - -mode_state equ 0 ;/* state->mode */ -wsize_state equ (32+zlib1222sup) ;/* state->wsize */ -write_state equ (36+4+zlib1222sup) ;/* state->write */ -window_state equ (40+4+zlib1222sup) ;/* state->window */ -hold_state equ (44+4+zlib1222sup) ;/* state->hold */ -bits_state equ (48+4+zlib1222sup) ;/* state->bits */ -lencode_state equ (64+4+zlib1222sup) ;/* state->lencode */ -distcode_state equ (68+4+zlib1222sup) ;/* state->distcode */ -lenbits_state equ (72+4+zlib1222sup) ;/* state->lenbits */ -distbits_state equ (76+4+zlib1222sup) ;/* state->distbits */ - - -;;SECTION .text -; 205 "inffast.S" -;GLOBAL inflate_fast_use_mmx - -;SECTION .data - - -; GLOBAL inflate_fast_use_mmx:object -;.size inflate_fast_use_mmx, 4 -; 226 "inffast.S" -;SECTION .text - -ALIGN 4 -_inflate_fast proc near -.FPO (16, 4, 0, 0, 1, 0) - push edi - push esi - push ebp - push ebx - pushfd - sub esp,64 - cld - - - - - mov esi, [esp+88] - mov edi, [esi+28] - - - - - - - - mov edx, [esi+4] - mov eax, [esi+0] - - add edx,eax - sub edx,11 - - mov [esp+44],eax - mov [esp+20],edx - - mov ebp, [esp+92] - mov ecx, [esi+16] - mov ebx, [esi+12] - - sub ebp,ecx - neg ebp - add ebp,ebx - - sub ecx,257 - add ecx,ebx - - mov [esp+60],ebx - mov [esp+40],ebp - mov [esp+16],ecx -; 285 "inffast.S" - mov eax, [edi+lencode_state] - mov ecx, [edi+distcode_state] - - mov [esp+8],eax - mov [esp+12],ecx - - mov eax,1 - mov ecx, [edi+lenbits_state] - shl eax,cl - dec eax - mov [esp+0],eax - - mov eax,1 - mov ecx, [edi+distbits_state] - shl eax,cl - dec eax - mov [esp+4],eax - - mov eax, [edi+wsize_state] - mov ecx, [edi+write_state] - mov edx, [edi+window_state] - - mov [esp+52],eax - mov [esp+48],ecx - mov [esp+56],edx - - mov ebp, [edi+hold_state] - mov ebx, [edi+bits_state] -; 321 "inffast.S" - mov esi, [esp+44] - mov ecx, [esp+20] - cmp ecx,esi - ja L_align_long - - add ecx,11 - sub ecx,esi - mov eax,12 - sub eax,ecx - lea edi, [esp+28] - rep movsb - mov ecx,eax - xor eax,eax - rep stosb - lea esi, [esp+28] - mov [esp+20],esi - jmp L_is_aligned - - -L_align_long: - test esi,3 - jz L_is_aligned - xor eax,eax - mov al, [esi] - inc esi - mov ecx,ebx - add ebx,8 - shl eax,cl - or ebp,eax - jmp L_align_long - -L_is_aligned: - mov edi, [esp+60] -; 366 "inffast.S" -L_check_mmx: - cmp dword ptr [inflate_fast_use_mmx],2 - je L_init_mmx - ja L_do_loop - - push eax - push ebx - push ecx - push edx - pushfd - mov eax, [esp] - xor dword ptr [esp],0200000h - - - - - popfd - pushfd - pop edx - xor edx,eax - jz L_dont_use_mmx - xor eax,eax - cpuid - cmp ebx,0756e6547h - jne L_dont_use_mmx - cmp ecx,06c65746eh - jne L_dont_use_mmx - cmp edx,049656e69h - jne L_dont_use_mmx - mov eax,1 - cpuid - shr eax,8 - and eax,15 - cmp eax,6 - jne L_dont_use_mmx - test edx,0800000h - jnz L_use_mmx - jmp L_dont_use_mmx -L_use_mmx: - mov dword ptr [inflate_fast_use_mmx],2 - jmp L_check_mmx_pop -L_dont_use_mmx: - mov dword ptr [inflate_fast_use_mmx],3 -L_check_mmx_pop: - pop edx - pop ecx - pop ebx - pop eax - jmp L_check_mmx -; 426 "inffast.S" -ALIGN 4 -L_do_loop: -; 437 "inffast.S" - cmp bl,15 - ja L_get_length_code - - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - -L_get_length_code: - mov edx, [esp+0] - mov ecx, [esp+8] - and edx,ebp - mov eax, [ecx+edx*4] - -L_dolen: - - - - - - - mov cl,ah - sub bl,ah - shr ebp,cl - - - - - - - test al,al - jnz L_test_for_length_base - - shr eax,16 - stosb - -L_while_test: - - - cmp [esp+16],edi - jbe L_break_loop - - cmp [esp+20],esi - ja L_do_loop - jmp L_break_loop - -L_test_for_length_base: -; 502 "inffast.S" - mov edx,eax - shr edx,16 - mov cl,al - - test al,16 - jz L_test_for_second_level_length - and cl,15 - jz L_save_len - cmp bl,cl - jae L_add_bits_to_len - - mov ch,cl - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - mov cl,ch - -L_add_bits_to_len: - mov eax,1 - shl eax,cl - dec eax - sub bl,cl - and eax,ebp - shr ebp,cl - add edx,eax - -L_save_len: - mov [esp+24],edx - - -L_decode_distance: -; 549 "inffast.S" - cmp bl,15 - ja L_get_distance_code - - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - -L_get_distance_code: - mov edx, [esp+4] - mov ecx, [esp+12] - and edx,ebp - mov eax, [ecx+edx*4] - - -L_dodist: - mov edx,eax - shr edx,16 - mov cl,ah - sub bl,ah - shr ebp,cl -; 584 "inffast.S" - mov cl,al - - test al,16 - jz L_test_for_second_level_dist - and cl,15 - jz L_check_dist_one - cmp bl,cl - jae L_add_bits_to_dist - - mov ch,cl - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - mov cl,ch - -L_add_bits_to_dist: - mov eax,1 - shl eax,cl - dec eax - sub bl,cl - and eax,ebp - shr ebp,cl - add edx,eax - jmp L_check_window - -L_check_window: -; 625 "inffast.S" - mov [esp+44],esi - mov eax,edi - sub eax, [esp+40] - - cmp eax,edx - jb L_clip_window - - mov ecx, [esp+24] - mov esi,edi - sub esi,edx - - sub ecx,3 - mov al, [esi] - mov [edi],al - mov al, [esi+1] - mov dl, [esi+2] - add esi,3 - mov [edi+1],al - mov [edi+2],dl - add edi,3 - rep movsb - - mov esi, [esp+44] - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp edx,1 - jne L_check_window - cmp [esp+40],edi - je L_check_window - - dec edi - mov ecx, [esp+24] - mov al, [edi] - sub ecx,3 - - mov [edi+1],al - mov [edi+2],al - mov [edi+3],al - add edi,4 - rep stosb - - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - - - - - test al,64 - jnz L_test_for_end_of_block - - mov eax,1 - shl eax,cl - dec eax - and eax,ebp - add eax,edx - mov edx, [esp+8] - mov eax, [edx+eax*4] - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - - - - - test al,64 - jnz L_invalid_distance_code - - mov eax,1 - shl eax,cl - dec eax - and eax,ebp - add eax,edx - mov edx, [esp+12] - mov eax, [edx+eax*4] - jmp L_dodist - -ALIGN 4 -L_clip_window: -; 721 "inffast.S" - mov ecx,eax - mov eax, [esp+52] - neg ecx - mov esi, [esp+56] - - cmp eax,edx - jb L_invalid_distance_too_far - - add ecx,edx - cmp dword ptr [esp+48],0 - jne L_wrap_around_window - - sub eax,ecx - add esi,eax -; 749 "inffast.S" - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - -L_wrap_around_window: -; 793 "inffast.S" - mov eax, [esp+48] - cmp ecx,eax - jbe L_contiguous_in_window - - add esi, [esp+52] - add esi,eax - sub esi,ecx - sub ecx,eax - - - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi, [esp+56] - mov ecx, [esp+48] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - -L_contiguous_in_window: -; 836 "inffast.S" - add esi,eax - sub esi,ecx - - - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - -L_do_copy1: -; 862 "inffast.S" - mov ecx,eax - rep movsb - - mov esi, [esp+44] - jmp L_while_test -; 878 "inffast.S" -ALIGN 4 -L_init_mmx: - emms - - - - - - movd mm0,ebp - mov ebp,ebx -; 896 "inffast.S" - movd mm4,dword ptr [esp+0] - movq mm3,mm4 - movd mm5,dword ptr [esp+4] - movq mm2,mm5 - pxor mm1,mm1 - mov ebx, [esp+8] - jmp L_do_loop_mmx - -ALIGN 4 -L_do_loop_mmx: - psrlq mm0,mm1 - - cmp ebp,32 - ja L_get_length_code_mmx - - movd mm6,ebp - movd mm7,dword ptr [esi] - add esi,4 - psllq mm7,mm6 - add ebp,32 - por mm0,mm7 - -L_get_length_code_mmx: - pand mm4,mm0 - movd eax,mm4 - movq mm4,mm3 - mov eax, [ebx+eax*4] - -L_dolen_mmx: - movzx ecx,ah - movd mm1,ecx - sub ebp,ecx - - test al,al - jnz L_test_for_length_base_mmx - - shr eax,16 - stosb - -L_while_test_mmx: - - - cmp [esp+16],edi - jbe L_break_loop - - cmp [esp+20],esi - ja L_do_loop_mmx - jmp L_break_loop - -L_test_for_length_base_mmx: - - mov edx,eax - shr edx,16 - - test al,16 - jz L_test_for_second_level_length_mmx - and eax,15 - jz L_decode_distance_mmx - - psrlq mm0,mm1 - movd mm1,eax - movd ecx,mm0 - sub ebp,eax - and ecx, [inflate_fast_mask+eax*4] - add edx,ecx - -L_decode_distance_mmx: - psrlq mm0,mm1 - - cmp ebp,32 - ja L_get_dist_code_mmx - - movd mm6,ebp - movd mm7,dword ptr [esi] - add esi,4 - psllq mm7,mm6 - add ebp,32 - por mm0,mm7 - -L_get_dist_code_mmx: - mov ebx, [esp+12] - pand mm5,mm0 - movd eax,mm5 - movq mm5,mm2 - mov eax, [ebx+eax*4] - -L_dodist_mmx: - - movzx ecx,ah - mov ebx,eax - shr ebx,16 - sub ebp,ecx - movd mm1,ecx - - test al,16 - jz L_test_for_second_level_dist_mmx - and eax,15 - jz L_check_dist_one_mmx - -L_add_bits_to_dist_mmx: - psrlq mm0,mm1 - movd mm1,eax - movd ecx,mm0 - sub ebp,eax - and ecx, [inflate_fast_mask+eax*4] - add ebx,ecx - -L_check_window_mmx: - mov [esp+44],esi - mov eax,edi - sub eax, [esp+40] - - cmp eax,ebx - jb L_clip_window_mmx - - mov ecx,edx - mov esi,edi - sub esi,ebx - - sub ecx,3 - mov al, [esi] - mov [edi],al - mov al, [esi+1] - mov dl, [esi+2] - add esi,3 - mov [edi+1],al - mov [edi+2],dl - add edi,3 - rep movsb - - mov esi, [esp+44] - mov ebx, [esp+8] - jmp L_while_test_mmx - -ALIGN 4 -L_check_dist_one_mmx: - cmp ebx,1 - jne L_check_window_mmx - cmp [esp+40],edi - je L_check_window_mmx - - dec edi - mov ecx,edx - mov al, [edi] - sub ecx,3 - - mov [edi+1],al - mov [edi+2],al - mov [edi+3],al - add edi,4 - rep stosb - - mov ebx, [esp+8] - jmp L_while_test_mmx - -ALIGN 4 -L_test_for_second_level_length_mmx: - test al,64 - jnz L_test_for_end_of_block - - and eax,15 - psrlq mm0,mm1 - movd ecx,mm0 - and ecx, [inflate_fast_mask+eax*4] - add ecx,edx - mov eax, [ebx+ecx*4] - jmp L_dolen_mmx - -ALIGN 4 -L_test_for_second_level_dist_mmx: - test al,64 - jnz L_invalid_distance_code - - and eax,15 - psrlq mm0,mm1 - movd ecx,mm0 - and ecx, [inflate_fast_mask+eax*4] - mov eax, [esp+12] - add ecx,ebx - mov eax, [eax+ecx*4] - jmp L_dodist_mmx - -ALIGN 4 -L_clip_window_mmx: - - mov ecx,eax - mov eax, [esp+52] - neg ecx - mov esi, [esp+56] - - cmp eax,ebx - jb L_invalid_distance_too_far - - add ecx,ebx - cmp dword ptr [esp+48],0 - jne L_wrap_around_window_mmx - - sub eax,ecx - add esi,eax - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - -L_wrap_around_window_mmx: - - mov eax, [esp+48] - cmp ecx,eax - jbe L_contiguous_in_window_mmx - - add esi, [esp+52] - add esi,eax - sub esi,ecx - sub ecx,eax - - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi, [esp+56] - mov ecx, [esp+48] - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - -L_contiguous_in_window_mmx: - - add esi,eax - sub esi,ecx - - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - -L_do_copy1_mmx: - - - mov ecx,edx - rep movsb - - mov esi, [esp+44] - mov ebx, [esp+8] - jmp L_while_test_mmx -; 1174 "inffast.S" -L_invalid_distance_code: - - - - - - mov ecx, invalid_distance_code_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_test_for_end_of_block: - - - - - - test al,32 - jz L_invalid_literal_length_code - - mov ecx,0 - mov edx,INFLATE_MODE_TYPE - jmp L_update_stream_state - -L_invalid_literal_length_code: - - - - - - mov ecx, invalid_literal_length_code_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_invalid_distance_too_far: - - - - mov esi, [esp+44] - mov ecx, invalid_distance_too_far_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_update_stream_state: - - mov eax, [esp+88] - test ecx,ecx - jz L_skip_msg - mov [eax+24],ecx -L_skip_msg: - mov eax, [eax+28] - mov [eax+mode_state],edx - jmp L_break_loop - -ALIGN 4 -L_break_loop: -; 1243 "inffast.S" - cmp dword ptr [inflate_fast_use_mmx],2 - jne L_update_next_in - - - - mov ebx,ebp - -L_update_next_in: -; 1266 "inffast.S" - mov eax, [esp+88] - mov ecx,ebx - mov edx, [eax+28] - shr ecx,3 - sub esi,ecx - shl ecx,3 - sub ebx,ecx - mov [eax+12],edi - mov [edx+bits_state],ebx - mov ecx,ebx - - lea ebx, [esp+28] - cmp [esp+20],ebx - jne L_buf_not_used - - sub esi,ebx - mov ebx, [eax+0] - mov [esp+20],ebx - add esi,ebx - mov ebx, [eax+4] - sub ebx,11 - add [esp+20],ebx - -L_buf_not_used: - mov [eax+0],esi - - mov ebx,1 - shl ebx,cl - dec ebx - - - - - - cmp dword ptr [inflate_fast_use_mmx],2 - jne L_update_hold - - - - psrlq mm0,mm1 - movd ebp,mm0 - - emms - -L_update_hold: - - - - and ebp,ebx - mov [edx+hold_state],ebp - - - - - mov ebx, [esp+20] - cmp ebx,esi - jbe L_last_is_smaller - - sub ebx,esi - add ebx,11 - mov [eax+4],ebx - jmp L_fixup_out -L_last_is_smaller: - sub esi,ebx - neg esi - add esi,11 - mov [eax+4],esi - - - - -L_fixup_out: - - mov ebx, [esp+16] - cmp ebx,edi - jbe L_end_is_smaller - - sub ebx,edi - add ebx,257 - mov [eax+16],ebx - jmp L_done -L_end_is_smaller: - sub edi,ebx - neg edi - add edi,257 - mov [eax+16],edi - - - - - -L_done: - add esp,64 - popfd - pop ebx - pop ebp - pop esi - pop edi - ret -_inflate_fast endp - -_TEXT ends -end diff --git a/deps/zlib/contrib/masmx86/match686.asm b/deps/zlib/contrib/masmx86/match686.asm deleted file mode 100644 index 69e0eed01dec79..00000000000000 --- a/deps/zlib/contrib/masmx86/match686.asm +++ /dev/null @@ -1,479 +0,0 @@ -; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86 -; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; File written by Gilles Vollant, by converting match686.S from Brian Raiter -; for MASM. This is as assembly version of longest_match -; from Jean-loup Gailly in deflate.c -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; For Visual C++ 4.x and higher and ML 6.x and higher -; ml.exe is distributed in -; http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 -; -; this file contain two implementation of longest_match -; -; this longest_match was written by Brian raiter (1998), optimized for Pentium Pro -; (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom) -; -; for using an assembly version of longest_match, you need define ASMV in project -; -; compile the asm file running -; ml /coff /Zi /c /Flmatch686.lst match686.asm -; and do not include match686.obj in your project -; -; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for -; Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor -; with autoselect (with cpu detection code) -; if you want support the old pentium optimization, you can still use these version -; -; this file is not optimized for old pentium, but it compatible with all x86 32 bits -; processor (starting 80386) -; -; -; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2 - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; /* current match */ - - NbStack equ 76 - cur_match equ dword ptr[esp+NbStack-0] - str_s equ dword ptr[esp+NbStack-4] -; 5 dword on top (ret,ebp,esi,edi,ebx) - adrret equ dword ptr[esp+NbStack-8] - pushebp equ dword ptr[esp+NbStack-12] - pushedi equ dword ptr[esp+NbStack-16] - pushesi equ dword ptr[esp+NbStack-20] - pushebx equ dword ptr[esp+NbStack-24] - - chain_length equ dword ptr [esp+NbStack-28] - limit equ dword ptr [esp+NbStack-32] - best_len equ dword ptr [esp+NbStack-36] - window equ dword ptr [esp+NbStack-40] - prev equ dword ptr [esp+NbStack-44] - scan_start equ word ptr [esp+NbStack-48] - wmask equ dword ptr [esp+NbStack-52] - match_start_ptr equ dword ptr [esp+NbStack-56] - nice_match equ dword ptr [esp+NbStack-60] - scan equ dword ptr [esp+NbStack-64] - - windowlen equ dword ptr [esp+NbStack-68] - match_start equ dword ptr [esp+NbStack-72] - strend equ dword ptr [esp+NbStack-76] - NbStackAdd equ (NbStack-24) - - .386p - - name gvmatch - .MODEL FLAT - - - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - - zlib1222add equ 8 - -; Note : these value are good with a 8 bytes boundary pack structure - dep_chain_length equ 74h+zlib1222add - dep_window equ 30h+zlib1222add - dep_strstart equ 64h+zlib1222add - dep_prev_length equ 70h+zlib1222add - dep_nice_match equ 88h+zlib1222add - dep_w_size equ 24h+zlib1222add - dep_prev equ 38h+zlib1222add - dep_w_mask equ 2ch+zlib1222add - dep_good_match equ 84h+zlib1222add - dep_match_start equ 68h+zlib1222add - dep_lookahead equ 6ch+zlib1222add - - -_TEXT segment - -IFDEF NOUNDERLINE - public longest_match - public match_init -ELSE - public _longest_match - public _match_init -ENDIF - - MAX_MATCH equ 258 - MIN_MATCH equ 3 - MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) - - - -MAX_MATCH equ 258 -MIN_MATCH equ 3 -MIN_LOOKAHEAD equ (MAX_MATCH + MIN_MATCH + 1) -MAX_MATCH_8_ equ ((MAX_MATCH + 7) AND 0FFF0h) - - -;;; stack frame offsets - -chainlenwmask equ esp + 0 ; high word: current chain len - ; low word: s->wmask -window equ esp + 4 ; local copy of s->window -windowbestlen equ esp + 8 ; s->window + bestlen -scanstart equ esp + 16 ; first two bytes of string -scanend equ esp + 12 ; last two bytes of string -scanalign equ esp + 20 ; dword-misalignment of string -nicematch equ esp + 24 ; a good enough match size -bestlen equ esp + 28 ; size of best match so far -scan equ esp + 32 ; ptr to string wanting match - -LocalVarsSize equ 36 -; saved ebx byte esp + 36 -; saved edi byte esp + 40 -; saved esi byte esp + 44 -; saved ebp byte esp + 48 -; return address byte esp + 52 -deflatestate equ esp + 56 ; the function arguments -curmatch equ esp + 60 - -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -dsWSize equ 36+zlib1222add -dsWMask equ 44+zlib1222add -dsWindow equ 48+zlib1222add -dsPrev equ 56+zlib1222add -dsMatchLen equ 88+zlib1222add -dsPrevMatch equ 92+zlib1222add -dsStrStart equ 100+zlib1222add -dsMatchStart equ 104+zlib1222add -dsLookahead equ 108+zlib1222add -dsPrevLen equ 112+zlib1222add -dsMaxChainLen equ 116+zlib1222add -dsGoodMatch equ 132+zlib1222add -dsNiceMatch equ 136+zlib1222add - - -;;; match686.asm -- Pentium-Pro-optimized version of longest_match() -;;; Written for zlib 1.1.2 -;;; Copyright (C) 1998 Brian Raiter -;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html -;;; -;; -;; This software is provided 'as-is', without any express or implied -;; warranty. In no event will the authors be held liable for any damages -;; arising from the use of this software. -;; -;; Permission is granted to anyone to use this software for any purpose, -;; including commercial applications, and to alter it and redistribute it -;; freely, subject to the following restrictions: -;; -;; 1. The origin of this software must not be misrepresented; you must not -;; claim that you wrote the original software. If you use this software -;; in a product, an acknowledgment in the product documentation would be -;; appreciated but is not required. -;; 2. Altered source versions must be plainly marked as such, and must not be -;; misrepresented as being the original software -;; 3. This notice may not be removed or altered from any source distribution. -;; - -;GLOBAL _longest_match, _match_init - - -;SECTION .text - -;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch) - -;_longest_match: - IFDEF NOUNDERLINE - longest_match proc near - ELSE - _longest_match proc near - ENDIF -.FPO (9, 4, 0, 0, 1, 0) - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - push ebp - push edi - push esi - push ebx - sub esp, LocalVarsSize - -;;; Retrieve the function arguments. ecx will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - - mov edx, [deflatestate] - mov ecx, [curmatch] - -;;; uInt wmask = s->w_mask; -;;; unsigned chain_length = s->max_chain_length; -;;; if (s->prev_length >= s->good_match) { -;;; chain_length >>= 2; -;;; } - - mov eax, [edx + dsPrevLen] - mov ebx, [edx + dsGoodMatch] - cmp eax, ebx - mov eax, [edx + dsWMask] - mov ebx, [edx + dsMaxChainLen] - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -;;; chainlen is decremented once beforehand so that the function can -;;; use the sign flag instead of the zero flag for the exit test. -;;; It is then shifted into the high word, to make room for the wmask -;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - mov [chainlenwmask], ebx - -;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - mov eax, [edx + dsNiceMatch] - mov ebx, [edx + dsLookahead] - cmp ebx, eax - jl LookaheadLess - mov ebx, eax -LookaheadLess: mov [nicematch], ebx - -;;; register Bytef *scan = s->window + s->strstart; - - mov esi, [edx + dsWindow] - mov [window], esi - mov ebp, [edx + dsStrStart] - lea edi, [esi + ebp] - mov [scan], edi - -;;; Determine how many bytes the scan ptr is off from being -;;; dword-aligned. - - mov eax, edi - neg eax - and eax, 3 - mov [scanalign], eax - -;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -;;; s->strstart - (IPos)MAX_DIST(s) : NIL; - - mov eax, [edx + dsWSize] - sub eax, MIN_LOOKAHEAD - sub ebp, eax - jg LimitPositive - xor ebp, ebp -LimitPositive: - -;;; int best_len = s->prev_length; - - mov eax, [edx + dsPrevLen] - mov [bestlen], eax - -;;; Store the sum of s->window + best_len in esi locally, and in esi. - - add esi, eax - mov [windowbestlen], esi - -;;; register ush scan_start = *(ushf*)scan; -;;; register ush scan_end = *(ushf*)(scan+best_len-1); -;;; Posf *prev = s->prev; - - movzx ebx, word ptr [edi] - mov [scanstart], ebx - movzx ebx, word ptr [edi + eax - 1] - mov [scanend], ebx - mov edi, [edx + dsPrev] - -;;; Jump into the main loop. - - mov edx, [chainlenwmask] - jmp short LoopEntry - -align 4 - -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; ecx = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit - -LookupLoop: - and ecx, edx - movzx ecx, word ptr [edi + ecx*2] - cmp ecx, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow -LoopEntry: movzx eax, word ptr [esi + ecx - 1] - cmp eax, ebx - jnz LookupLoop - mov eax, [window] - movzx eax, word ptr [eax + ecx] - cmp eax, [scanstart] - jnz LookupLoop - -;;; Store the current value of chainlen. - - mov [chainlenwmask], edx - -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). - - mov esi, [window] - mov edi, [scan] - add esi, ecx - mov eax, [scanalign] - mov edx, 0fffffef8h; -(MAX_MATCH_8) - lea edi, [edi + eax + 0108h] ;MAX_MATCH_8] - lea esi, [esi + eax + 0108h] ;MAX_MATCH_8] - -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust edx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (esi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. - -LoopCmps: - mov eax, [esi + edx] - xor eax, [edi + edx] - jnz LeaveLoopCmps - mov eax, [esi + edx + 4] - xor eax, [edi + edx + 4] - jnz LeaveLoopCmps4 - add edx, 8 - jnz LoopCmps - jmp short LenMaximum -LeaveLoopCmps4: add edx, 4 -LeaveLoopCmps: test eax, 0000FFFFh - jnz LenLower - add edx, 2 - shr eax, 16 -LenLower: sub al, 1 - adc edx, 0 - -;;; Calculate the length of the match. If it is longer than MAX_MATCH, -;;; then automatically accept it as the best possible match and leave. - - lea eax, [edi + edx] - mov edi, [scan] - sub eax, edi - cmp eax, MAX_MATCH - jge LenMaximum - -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. - - mov edx, [deflatestate] - mov ebx, [bestlen] - cmp eax, ebx - jg LongerMatch - mov esi, [windowbestlen] - mov edi, [edx + dsPrev] - mov ebx, [scanend] - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); - -LongerMatch: mov ebx, [nicematch] - mov [bestlen], eax - mov [edx + dsMatchStart], ecx - cmp eax, ebx - jge LeaveNow - mov esi, [window] - add esi, eax - mov [windowbestlen], esi - movzx ebx, word ptr [edi + eax - 1] - mov edi, [edx + dsPrev] - mov [scanend], ebx - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; Accept the current string, with the maximum possible length. - -LenMaximum: mov edx, [deflatestate] - mov dword ptr [bestlen], MAX_MATCH - mov [edx + dsMatchStart], ecx - -;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -;;; return s->lookahead; - -LeaveNow: - mov edx, [deflatestate] - mov ebx, [bestlen] - mov eax, [edx + dsLookahead] - cmp ebx, eax - jg LookaheadRet - mov eax, ebx -LookaheadRet: - -;;; Restore the stack and return from whence we came. - - add esp, LocalVarsSize - pop ebx - pop esi - pop edi - pop ebp - - ret -; please don't remove this string ! -; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary! - db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah - - - IFDEF NOUNDERLINE - longest_match endp - ELSE - _longest_match endp - ENDIF - - IFDEF NOUNDERLINE - match_init proc near - ret - match_init endp - ELSE - _match_init proc near - ret - _match_init endp - ENDIF - - -_TEXT ends -end diff --git a/deps/zlib/contrib/masmx86/readme.txt b/deps/zlib/contrib/masmx86/readme.txt deleted file mode 100644 index 3f8888679fc891..00000000000000 --- a/deps/zlib/contrib/masmx86/readme.txt +++ /dev/null @@ -1,27 +0,0 @@ - -Summary -------- -This directory contains ASM implementations of the functions -longest_match() and inflate_fast(). - - -Use instructions ----------------- -Assemble using MASM, and copy the object files into the zlib source -directory, then run the appropriate makefile, as suggested below. You can -donwload MASM from here: - - http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 - -You can also get objects files here: - - http://www.winimage.com/zLibDll/zlib124_masm_obj.zip - -Build instructions ------------------- -* With Microsoft C and MASM: -nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" - -* With Borland C and TASM: -make -f win32/Makefile.bor LOCAL_ZLIB="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" OBJPA="+match686c.obj+match686.obj+inffas32.obj" - diff --git a/deps/zlib/contrib/minizip/ChangeLogUnzip b/deps/zlib/contrib/minizip/ChangeLogUnzip new file mode 100644 index 00000000000000..e62af147dce682 --- /dev/null +++ b/deps/zlib/contrib/minizip/ChangeLogUnzip @@ -0,0 +1,67 @@ +Change in 1.01e (12 feb 05) +- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter) +- Fix possible memory leak in unzip.c (Zoran Stevanovic) + +Change in 1.01b (20 may 04) +- Integrate patch from Debian package (submited by Mark Brown) +- Add tools mztools from Xavier Roche + +Change in 1.01 (8 may 04) +- fix buffer overrun risk in unzip.c (Xavier Roche) +- fix a minor buffer insecurity in minizip.c (Mike Whittaker) + +Change in 1.00: (10 sept 03) +- rename to 1.00 +- cosmetic code change + +Change in 0.22: (19 May 03) +- crypting support (unless you define NOCRYPT) +- append file in existing zipfile + +Change in 0.21: (10 Mar 03) +- bug fixes + +Change in 0.17: (27 Jan 02) +- bug fixes + +Change in 0.16: (19 Jan 02) +- Support of ioapi for virtualize zip file access + +Change in 0.15: (19 Mar 98) +- fix memory leak in minizip.c + +Change in 0.14: (10 Mar 98) +- fix bugs in minizip.c sample for zipping big file +- fix problem in month in date handling +- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for + comment handling + +Change in 0.13: (6 Mar 98) +- fix bugs in zip.c +- add real minizip sample + +Change in 0.12: (4 Mar 98) +- add zip.c and zip.h for creates .zip file +- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly) +- fix miniunz.c for file without specific record for directory + +Change in 0.11: (3 Mar 98) +- fix bug in unzGetCurrentFileInfo for get extra field and comment +- enhance miniunz sample, remove the bad unztst.c sample + +Change in 0.10: (2 Mar 98) +- fix bug in unzReadCurrentFile +- rename unzip* to unz* function and structure +- remove Windows-like hungary notation variable name +- modify some structure in unzip.h +- add somes comment in source +- remove unzipGetcCurrentFile function +- replace ZUNZEXPORT by ZEXPORT +- add unzGetLocalExtrafield for get the local extrafield info +- add a new sample, miniunz.c + +Change in 0.4: (25 Feb 98) +- suppress the type unzipFileInZip. + Only on file in the zipfile can be open at the same time +- fix somes typo in code +- added tm_unz structure in unzip_file_info (date/time in readable format) diff --git a/deps/zlib/contrib/minizip/Makefile.am b/deps/zlib/contrib/minizip/Makefile.am deleted file mode 100644 index d343011ebc3b3f..00000000000000 --- a/deps/zlib/contrib/minizip/Makefile.am +++ /dev/null @@ -1,45 +0,0 @@ -lib_LTLIBRARIES = libminizip.la - -if COND_DEMOS -bin_PROGRAMS = miniunzip minizip -endif - -zlib_top_srcdir = $(top_srcdir)/../.. -zlib_top_builddir = $(top_builddir)/../.. - -AM_CPPFLAGS = -I$(zlib_top_srcdir) -AM_LDFLAGS = -L$(zlib_top_builddir) - -if WIN32 -iowin32_src = iowin32.c -iowin32_h = iowin32.h -endif - -libminizip_la_SOURCES = \ - ioapi.c \ - mztools.c \ - unzip.c \ - zip.c \ - ${iowin32_src} - -libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz - -minizip_includedir = $(includedir)/minizip -minizip_include_HEADERS = \ - crypt.h \ - ioapi.h \ - mztools.h \ - unzip.h \ - zip.h \ - ${iowin32_h} - -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = minizip.pc - -EXTRA_PROGRAMS = miniunzip minizip - -miniunzip_SOURCES = miniunz.c -miniunzip_LDADD = libminizip.la - -minizip_SOURCES = minizip.c -minizip_LDADD = libminizip.la -lz diff --git a/deps/zlib/contrib/minizip/MiniZip64_Changes.txt b/deps/zlib/contrib/minizip/MiniZip64_Changes.txt deleted file mode 100644 index 13a1bd91a9b00f..00000000000000 --- a/deps/zlib/contrib/minizip/MiniZip64_Changes.txt +++ /dev/null @@ -1,6 +0,0 @@ - -MiniZip 1.1 was derrived from MiniZip at version 1.01f - -Change in 1.0 (Okt 2009) - - **TODO - Add history** - diff --git a/deps/zlib/contrib/minizip/MiniZip64_info.txt b/deps/zlib/contrib/minizip/MiniZip64_info.txt deleted file mode 100644 index 57d715242087b3..00000000000000 --- a/deps/zlib/contrib/minizip/MiniZip64_info.txt +++ /dev/null @@ -1,74 +0,0 @@ -MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson - -Introduction ---------------------- -MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html ) - -When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0. -All possible work was done for compatibility. - - -Background ---------------------- -When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64 -support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ ) - -That was used as a starting point. And after that ZIP64 support was added to zip.c -some refactoring and code cleanup was also done. - - -Changed from MiniZip 1.0 to MiniZip 1.1 ---------------------------------------- -* Added ZIP64 support for unzip ( by Even Rouault ) -* Added ZIP64 support for zip ( by Mathias Svensson ) -* Reverted some changed that Even Rouault did. -* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users. -* Added unzip patch for BZIP Compression method (patch create by Daniel Borca) -* Added BZIP Compress method for zip -* Did some refactoring and code cleanup - - -Credits - - Gilles Vollant - Original MiniZip author - Even Rouault - ZIP64 unzip Support - Daniel Borca - BZip Compression method support in unzip - Mathias Svensson - ZIP64 zip support - Mathias Svensson - BZip Compression method support in zip - - Resources - - ZipLayout http://result42.com/projects/ZipFileLayout - Command line tool for Windows that shows the layout and information of the headers in a zip archive. - Used when debugging and validating the creation of zip files using MiniZip64 - - - ZIP App Note http://www.pkware.com/documents/casestudies/APPNOTE.TXT - Zip File specification - - -Notes. - * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined. - -License ----------------------------------------------------------- - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - ----------------------------------------------------------- - diff --git a/deps/zlib/contrib/minizip/configure.ac b/deps/zlib/contrib/minizip/configure.ac deleted file mode 100644 index 5b11970977f03d..00000000000000 --- a/deps/zlib/contrib/minizip/configure.ac +++ /dev/null @@ -1,32 +0,0 @@ -# -*- Autoconf -*- -# Process this file with autoconf to produce a configure script. - -AC_INIT([minizip], [1.2.11], [bugzilla.redhat.com]) -AC_CONFIG_SRCDIR([minizip.c]) -AM_INIT_AUTOMAKE([foreign]) -LT_INIT - -AC_MSG_CHECKING([whether to build example programs]) -AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs])) -AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes]) -if test "$enable_demos" = yes -then - AC_MSG_RESULT([yes]) -else - AC_MSG_RESULT([no]) -fi - -case "${host}" in - *-mingw* | mingw*) - WIN32="yes" - ;; - *) - ;; -esac -AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"]) - - -AC_SUBST([HAVE_UNISTD_H], [0]) -AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], []) -AC_CONFIG_FILES([Makefile minizip.pc]) -AC_OUTPUT diff --git a/deps/zlib/contrib/minizip/ioapi.c b/deps/zlib/contrib/minizip/ioapi.c index 7f5c191b2afd16..543910b5e118a4 100644 --- a/deps/zlib/contrib/minizip/ioapi.c +++ b/deps/zlib/contrib/minizip/ioapi.c @@ -14,7 +14,7 @@ #define _CRT_SECURE_NO_WARNINGS #endif -#if defined(__APPLE__) || defined(IOAPI_NO_64) +#if defined(__APPLE__) || defined(__Fuchsia__) || defined(IOAPI_NO_64) // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions #define FOPEN_FUNC(filename, mode) fopen(filename, mode) #define FTELLO_FUNC(stream) ftello(stream) diff --git a/deps/zlib/contrib/minizip/ioapi.h b/deps/zlib/contrib/minizip/ioapi.h index 8dcbdb06e35ad5..c1b7a54847f552 100644 --- a/deps/zlib/contrib/minizip/ioapi.h +++ b/deps/zlib/contrib/minizip/ioapi.h @@ -43,7 +43,7 @@ #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #if defined(USE_FILE32API) #define fopen64 fopen diff --git a/deps/zlib/contrib/minizip/iowin32.c b/deps/zlib/contrib/minizip/iowin32.c index 274f39eb1dd2c6..246ceb91a13942 100644 --- a/deps/zlib/contrib/minizip/iowin32.c +++ b/deps/zlib/contrib/minizip/iowin32.c @@ -26,12 +26,19 @@ #endif +#ifdef _WIN32_WINNT +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x601 +#endif + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 // see Include/shared/winapifamily.h in the Windows Kit #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) #if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) #define IOWIN32_USING_WINRT_API 1 #endif #endif +#endif voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); diff --git a/deps/zlib/contrib/minizip/make_vms.com b/deps/zlib/contrib/minizip/make_vms.com deleted file mode 100644 index 9ac13a98fa5fb4..00000000000000 --- a/deps/zlib/contrib/minizip/make_vms.com +++ /dev/null @@ -1,25 +0,0 @@ -$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig -$ open/write zdef vmsdefs.h -$ copy sys$input: zdef -$ deck -#define unix -#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from -#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator -#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord -#define Write_EndOfCentralDirectoryRecord Write_EoDRecord -$ eod -$ close zdef -$ copy vmsdefs.h,ioapi.h_orig ioapi.h -$ cc/include=[--]/prefix=all ioapi.c -$ cc/include=[--]/prefix=all miniunz.c -$ cc/include=[--]/prefix=all unzip.c -$ cc/include=[--]/prefix=all minizip.c -$ cc/include=[--]/prefix=all zip.c -$ link miniunz,unzip,ioapi,[--]libz.olb/lib -$ link minizip,zip,ioapi,[--]libz.olb/lib -$ mcr []minizip test minizip_info.txt -$ mcr []miniunz -l test.zip -$ rename minizip_info.txt; minizip_info.txt_old -$ mcr []miniunz test.zip -$ delete test.zip;* -$exit diff --git a/deps/zlib/contrib/minizip/miniunzip.1 b/deps/zlib/contrib/minizip/miniunzip.1 deleted file mode 100644 index 111ac69190f0b2..00000000000000 --- a/deps/zlib/contrib/minizip/miniunzip.1 +++ /dev/null @@ -1,63 +0,0 @@ -.\" Hey, EMACS: -*- nroff -*- -.TH miniunzip 1 "Nov 7, 2001" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -miniunzip - uncompress and examine ZIP archives -.SH SYNOPSIS -.B miniunzip -.RI [ -exvlo ] -zipfile [ files_to_extract ] [-d tempdir] -.SH DESCRIPTION -.B minizip -is a simple tool which allows the extraction of compressed file -archives in the ZIP format used by the MS-DOS utility PKZIP. It was -written as a demonstration of the -.IR zlib (3) -library and therefore lack many of the features of the -.IR unzip (1) -program. -.SH OPTIONS -A number of options are supported. With the exception of -.BI \-d\ tempdir -these must be supplied before any -other arguments and are: -.TP -.BI \-l\ ,\ \-\-v -List the files in the archive without extracting them. -.TP -.B \-o -Overwrite files without prompting for confirmation. -.TP -.B \-x -Extract files (default). -.PP -The -.I zipfile -argument is the name of the archive to process. The next argument can be used -to specify a single file to extract from the archive. - -Lastly, the following option can be specified at the end of the command-line: -.TP -.BI \-d\ tempdir -Extract the archive in the directory -.I tempdir -rather than the current directory. -.SH SEE ALSO -.BR minizip (1), -.BR zlib (3), -.BR unzip (1). -.SH AUTHOR -This program was written by Gilles Vollant. This manual page was -written by Mark Brown . The -d tempdir option -was added by Dirk Eddelbuettel . diff --git a/deps/zlib/contrib/minizip/minizip.1 b/deps/zlib/contrib/minizip/minizip.1 deleted file mode 100644 index 1154484c1cc158..00000000000000 --- a/deps/zlib/contrib/minizip/minizip.1 +++ /dev/null @@ -1,46 +0,0 @@ -.\" Hey, EMACS: -*- nroff -*- -.TH minizip 1 "May 2, 2001" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -minizip - create ZIP archives -.SH SYNOPSIS -.B minizip -.RI [ -o ] -zipfile [ " files" ... ] -.SH DESCRIPTION -.B minizip -is a simple tool which allows the creation of compressed file archives -in the ZIP format used by the MS-DOS utility PKZIP. It was written as -a demonstration of the -.IR zlib (3) -library and therefore lack many of the features of the -.IR zip (1) -program. -.SH OPTIONS -The first argument supplied is the name of the ZIP archive to create or -.RI -o -in which case it is ignored and the second argument treated as the -name of the ZIP file. If the ZIP file already exists it will be -overwritten. -.PP -Subsequent arguments specify a list of files to place in the ZIP -archive. If none are specified then an empty archive will be created. -.SH SEE ALSO -.BR miniunzip (1), -.BR zlib (3), -.BR zip (1). -.SH AUTHOR -This program was written by Gilles Vollant. This manual page was -written by Mark Brown . - diff --git a/deps/zlib/contrib/minizip/minizip.pc.in b/deps/zlib/contrib/minizip/minizip.pc.in deleted file mode 100644 index 69b5b7fdcb3b4a..00000000000000 --- a/deps/zlib/contrib/minizip/minizip.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@/minizip - -Name: minizip -Description: Minizip zip file manipulation library -Requires: -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lminizip -Libs.private: -lz -Cflags: -I${includedir} diff --git a/deps/zlib/contrib/minizip/mztools.c b/deps/zlib/contrib/minizip/mztools.c index 96891c2e0b71ef..8bf9cca326338a 100644 --- a/deps/zlib/contrib/minizip/mztools.c +++ b/deps/zlib/contrib/minizip/mztools.c @@ -8,7 +8,7 @@ #include #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "unzip.h" #define READ_8(adr) ((unsigned char)*(adr)) diff --git a/deps/zlib/contrib/minizip/mztools.h b/deps/zlib/contrib/minizip/mztools.h index a49a426ec2fcb2..f295ffeda6afcf 100644 --- a/deps/zlib/contrib/minizip/mztools.h +++ b/deps/zlib/contrib/minizip/mztools.h @@ -12,7 +12,7 @@ extern "C" { #endif #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #include "unzip.h" diff --git a/deps/zlib/contrib/minizip/unzip.c b/deps/zlib/contrib/minizip/unzip.c index bcfb9416ec356d..e8b2bc5c766c8a 100644 --- a/deps/zlib/contrib/minizip/unzip.c +++ b/deps/zlib/contrib/minizip/unzip.c @@ -68,11 +68,7 @@ #include #include -#ifndef NOUNCRYPT - #define NOUNCRYPT -#endif - -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "unzip.h" #ifdef STDC @@ -1630,6 +1626,7 @@ extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, zdecode(s->keys,s->pcrc_32_tab,source[i]); s->pfile_in_zip_read->pos_in_zipfile+=12; + s->pfile_in_zip_read->rest_read_compressed-=12; s->encrypted=1; } # endif @@ -1705,11 +1702,6 @@ extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) pfile_in_zip_read_info->stream.avail_out = (uInt)len; - if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && - (!(pfile_in_zip_read_info->raw))) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_uncompressed; - if ((len>pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in) && (pfile_in_zip_read_info->raw)) diff --git a/deps/zlib/contrib/minizip/unzip.h b/deps/zlib/contrib/minizip/unzip.h index 2104e39150749b..3c0143529b9144 100644 --- a/deps/zlib/contrib/minizip/unzip.h +++ b/deps/zlib/contrib/minizip/unzip.h @@ -48,7 +48,7 @@ extern "C" { #endif #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #ifndef _ZLIBIOAPI_H diff --git a/deps/zlib/contrib/minizip/zip.c b/deps/zlib/contrib/minizip/zip.c index 44e88a9cb9898d..65c0c7251843c0 100644 --- a/deps/zlib/contrib/minizip/zip.c +++ b/deps/zlib/contrib/minizip/zip.c @@ -26,7 +26,7 @@ #include #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "zip.h" #ifdef STDC diff --git a/deps/zlib/contrib/minizip/zip.h b/deps/zlib/contrib/minizip/zip.h index 8aaebb623430fc..8c06c0aa7bb08b 100644 --- a/deps/zlib/contrib/minizip/zip.h +++ b/deps/zlib/contrib/minizip/zip.h @@ -47,7 +47,7 @@ extern "C" { //#define HAVE_BZIP2 #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #ifndef _ZLIBIOAPI_H diff --git a/deps/zlib/contrib/optimizations/chunkcopy.h b/deps/zlib/contrib/optimizations/chunkcopy.h new file mode 100644 index 00000000000000..38ba0ed8a27f45 --- /dev/null +++ b/deps/zlib/contrib/optimizations/chunkcopy.h @@ -0,0 +1,444 @@ +/* chunkcopy.h -- fast chunk copy and set operations + * Copyright (C) 2017 ARM, Inc. + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#ifndef CHUNKCOPY_H +#define CHUNKCOPY_H + +#include +#include "zutil.h" + +#define Z_STATIC_ASSERT(name, assert) typedef char name[(assert) ? 1 : -1] + +#if __STDC_VERSION__ >= 199901L +#define Z_RESTRICT restrict +#else +#define Z_RESTRICT +#endif + +#if defined(__clang__) || defined(__GNUC__) || defined(__llvm__) +#define Z_BUILTIN_MEMCPY __builtin_memcpy +#else +#define Z_BUILTIN_MEMCPY zmemcpy +#endif + +#if defined(INFLATE_CHUNK_SIMD_NEON) +#include +typedef uint8x16_t z_vec128i_t; +#elif defined(INFLATE_CHUNK_SIMD_SSE2) +#include +typedef __m128i z_vec128i_t; +#else +#error chunkcopy.h inflate chunk SIMD is not defined for your build target +#endif + +/* + * chunk copy type: the z_vec128i_t type size should be exactly 128-bits + * and equal to CHUNKCOPY_CHUNK_SIZE. + */ +#define CHUNKCOPY_CHUNK_SIZE sizeof(z_vec128i_t) + +Z_STATIC_ASSERT(vector_128_bits_wide, + CHUNKCOPY_CHUNK_SIZE == sizeof(int8_t) * 16); + +/* + * Ask the compiler to perform a wide, unaligned load with a machine + * instruction appropriate for the z_vec128i_t type. + */ +static inline z_vec128i_t loadchunk( + const unsigned char FAR* s) { + z_vec128i_t v; + Z_BUILTIN_MEMCPY(&v, s, sizeof(v)); + return v; +} + +/* + * Ask the compiler to perform a wide, unaligned store with a machine + * instruction appropriate for the z_vec128i_t type. + */ +static inline void storechunk( + unsigned char FAR* d, + const z_vec128i_t v) { + Z_BUILTIN_MEMCPY(d, &v, sizeof(v)); +} + +/* + * Perform a memcpy-like operation, assuming that length is non-zero and that + * it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE bytes of output even if + * the length is shorter than this. + * + * It also guarantees that it will properly unroll the data if the distance + * between `out` and `from` is at least CHUNKCOPY_CHUNK_SIZE, which we rely on + * in chunkcopy_relaxed(). + * + * Aside from better memory bus utilisation, this means that short copies + * (CHUNKCOPY_CHUNK_SIZE bytes or fewer) will fall straight through the loop + * without iteration, which will hopefully make the branch prediction more + * reliable. + */ +static inline unsigned char FAR* chunkcopy_core( + unsigned char FAR* out, + const unsigned char FAR* from, + unsigned len) { + const int bump = (--len % CHUNKCOPY_CHUNK_SIZE) + 1; + storechunk(out, loadchunk(from)); + out += bump; + from += bump; + len /= CHUNKCOPY_CHUNK_SIZE; + while (len-- > 0) { + storechunk(out, loadchunk(from)); + out += CHUNKCOPY_CHUNK_SIZE; + from += CHUNKCOPY_CHUNK_SIZE; + } + return out; +} + +/* + * Like chunkcopy_core(), but avoid writing beyond of legal output. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_core_safe( + unsigned char FAR* out, + const unsigned char FAR* from, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + if ((limit - out) < (ptrdiff_t)CHUNKCOPY_CHUNK_SIZE) { + const unsigned char FAR* Z_RESTRICT rfrom = from; + if (len & 8) { + Z_BUILTIN_MEMCPY(out, rfrom, 8); + out += 8; + rfrom += 8; + } + if (len & 4) { + Z_BUILTIN_MEMCPY(out, rfrom, 4); + out += 4; + rfrom += 4; + } + if (len & 2) { + Z_BUILTIN_MEMCPY(out, rfrom, 2); + out += 2; + rfrom += 2; + } + if (len & 1) { + *out++ = *rfrom++; + } + return out; + } + return chunkcopy_core(out, from, len); +} + +/* + * Perform short copies until distance can be rewritten as being at least + * CHUNKCOPY_CHUNK_SIZE. + * + * Assumes it's OK to overwrite at least the first 2*CHUNKCOPY_CHUNK_SIZE + * bytes of output even if the copy is shorter than this. This assumption + * holds within zlib inflate_fast(), which starts every iteration with at + * least 258 bytes of output space available (258 being the maximum length + * output from a single token; see inffast.c). + */ +static inline unsigned char FAR* chunkunroll_relaxed( + unsigned char FAR* out, + unsigned FAR* dist, + unsigned FAR* len) { + const unsigned char FAR* from = out - *dist; + while (*dist < *len && *dist < CHUNKCOPY_CHUNK_SIZE) { + storechunk(out, loadchunk(from)); + out += *dist; + *len -= *dist; + *dist += *dist; + } + return out; +} + +#if defined(INFLATE_CHUNK_SIMD_NEON) +/* + * v_load64_dup(): load *src as an unaligned 64-bit int and duplicate it in + * every 64-bit component of the 128-bit result (64-bit int splat). + */ +static inline z_vec128i_t v_load64_dup(const void* src) { + return vcombine_u8(vld1_u8(src), vld1_u8(src)); +} + +/* + * v_load32_dup(): load *src as an unaligned 32-bit int and duplicate it in + * every 32-bit component of the 128-bit result (32-bit int splat). + */ +static inline z_vec128i_t v_load32_dup(const void* src) { + int32_t i32; + Z_BUILTIN_MEMCPY(&i32, src, sizeof(i32)); + return vreinterpretq_u8_s32(vdupq_n_s32(i32)); +} + +/* + * v_load16_dup(): load *src as an unaligned 16-bit int and duplicate it in + * every 16-bit component of the 128-bit result (16-bit int splat). + */ +static inline z_vec128i_t v_load16_dup(const void* src) { + int16_t i16; + Z_BUILTIN_MEMCPY(&i16, src, sizeof(i16)); + return vreinterpretq_u8_s16(vdupq_n_s16(i16)); +} + +/* + * v_load8_dup(): load the 8-bit int *src and duplicate it in every 8-bit + * component of the 128-bit result (8-bit int splat). + */ +static inline z_vec128i_t v_load8_dup(const void* src) { + return vld1q_dup_u8((const uint8_t*)src); +} + +/* + * v_store_128(): store the 128-bit vec in a memory destination (that might + * not be 16-byte aligned) void* out. + */ +static inline void v_store_128(void* out, const z_vec128i_t vec) { + vst1q_u8(out, vec); +} + +#elif defined(INFLATE_CHUNK_SIMD_SSE2) +/* + * v_load64_dup(): load *src as an unaligned 64-bit int and duplicate it in + * every 64-bit component of the 128-bit result (64-bit int splat). + */ +static inline z_vec128i_t v_load64_dup(const void* src) { + int64_t i64; + Z_BUILTIN_MEMCPY(&i64, src, sizeof(i64)); + return _mm_set1_epi64x(i64); +} + +/* + * v_load32_dup(): load *src as an unaligned 32-bit int and duplicate it in + * every 32-bit component of the 128-bit result (32-bit int splat). + */ +static inline z_vec128i_t v_load32_dup(const void* src) { + int32_t i32; + Z_BUILTIN_MEMCPY(&i32, src, sizeof(i32)); + return _mm_set1_epi32(i32); +} + +/* + * v_load16_dup(): load *src as an unaligned 16-bit int and duplicate it in + * every 16-bit component of the 128-bit result (16-bit int splat). + */ +static inline z_vec128i_t v_load16_dup(const void* src) { + int16_t i16; + Z_BUILTIN_MEMCPY(&i16, src, sizeof(i16)); + return _mm_set1_epi16(i16); +} + +/* + * v_load8_dup(): load the 8-bit int *src and duplicate it in every 8-bit + * component of the 128-bit result (8-bit int splat). + */ +static inline z_vec128i_t v_load8_dup(const void* src) { + return _mm_set1_epi8(*(const char*)src); +} + +/* + * v_store_128(): store the 128-bit vec in a memory destination (that might + * not be 16-byte aligned) void* out. + */ +static inline void v_store_128(void* out, const z_vec128i_t vec) { + _mm_storeu_si128((__m128i*)out, vec); +} +#endif + +/* + * Perform an overlapping copy which behaves as a memset() operation, but + * supporting periods other than one, and assume that length is non-zero and + * that it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE*3 bytes of output + * even if the length is shorter than this. + */ +static inline unsigned char FAR* chunkset_core( + unsigned char FAR* out, + unsigned period, + unsigned len) { + z_vec128i_t v; + const int bump = ((len - 1) % sizeof(v)) + 1; + + switch (period) { + case 1: + v = v_load8_dup(out - 1); + v_store_128(out, v); + out += bump; + len -= bump; + while (len > 0) { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } + return out; + case 2: + v = v_load16_dup(out - 2); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load16_dup(out - 2); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + case 4: + v = v_load32_dup(out - 4); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load32_dup(out - 4); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + case 8: + v = v_load64_dup(out - 8); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load64_dup(out - 8); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + } + out = chunkunroll_relaxed(out, &period, &len); + return chunkcopy_core(out, out - period, len); +} + +/* + * Perform a memcpy-like operation, but assume that length is non-zero and that + * it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE bytes of output even if + * the length is shorter than this. + * + * Unlike chunkcopy_core() above, no guarantee is made regarding the behaviour + * of overlapping buffers, regardless of the distance between the pointers. + * This is reflected in the `restrict`-qualified pointers, allowing the + * compiler to re-order loads and stores. + */ +static inline unsigned char FAR* chunkcopy_relaxed( + unsigned char FAR* Z_RESTRICT out, + const unsigned char FAR* Z_RESTRICT from, + unsigned len) { + return chunkcopy_core(out, from, len); +} + +/* + * Like chunkcopy_relaxed(), but avoid writing beyond of legal output. + * + * Unlike chunkcopy_core_safe() above, no guarantee is made regarding the + * behaviour of overlapping buffers, regardless of the distance between the + * pointers. This is reflected in the `restrict`-qualified pointers, allowing + * the compiler to re-order loads and stores. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_safe( + unsigned char FAR* out, + const unsigned char FAR* Z_RESTRICT from, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + return chunkcopy_core_safe(out, from, len, limit); +} + +/* + * Perform chunky copy within the same buffer, where the source and destination + * may potentially overlap. + * + * Assumes that len > 0 on entry, and that it's safe to write at least + * CHUNKCOPY_CHUNK_SIZE*3 bytes to the output. + */ +static inline unsigned char FAR* chunkcopy_lapped_relaxed( + unsigned char FAR* out, + unsigned dist, + unsigned len) { + if (dist < len && dist < CHUNKCOPY_CHUNK_SIZE) { + return chunkset_core(out, dist, len); + } + return chunkcopy_core(out, out - dist, len); +} + +/* + * Behave like chunkcopy_lapped_relaxed(), but avoid writing beyond of legal + * output. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_lapped_safe( + unsigned char FAR* out, + unsigned dist, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + if ((limit - out) < (ptrdiff_t)(3 * CHUNKCOPY_CHUNK_SIZE)) { + /* TODO(cavalcantii): try harder to optimise this */ + while (len-- > 0) { + *out = *(out - dist); + out++; + } + return out; + } + return chunkcopy_lapped_relaxed(out, dist, len); +} + +/* + * The chunk-copy code above deals with writing the decoded DEFLATE data to + * the output with SIMD methods to increase decode speed. Reading the input + * to the DEFLATE decoder with a wide, SIMD method can also increase decode + * speed. This option is supported on little endian machines, and reads the + * input data in 64-bit (8 byte) chunks. + */ + +#ifdef INFLATE_CHUNK_READ_64LE +/* + * Buffer the input in a uint64_t (8 bytes) in the wide input reading case. + */ +typedef uint64_t inflate_holder_t; + +/* + * Ask the compiler to perform a wide, unaligned load of a uint64_t using a + * machine instruction appropriate for the uint64_t type. + */ +static inline inflate_holder_t read64le(const unsigned char FAR *in) { + inflate_holder_t input; + Z_BUILTIN_MEMCPY(&input, in, sizeof(input)); + return input; +} +#else +/* + * Otherwise, buffer the input bits using zlib's default input buffer type. + */ +typedef unsigned long inflate_holder_t; + +#endif /* INFLATE_CHUNK_READ_64LE */ + +#undef Z_STATIC_ASSERT +#undef Z_RESTRICT +#undef Z_BUILTIN_MEMCPY + +#endif /* CHUNKCOPY_H */ diff --git a/deps/zlib/contrib/optimizations/inffast_chunk.c b/deps/zlib/contrib/optimizations/inffast_chunk.c new file mode 100644 index 00000000000000..4099edf3961d74 --- /dev/null +++ b/deps/zlib/contrib/optimizations/inffast_chunk.c @@ -0,0 +1,359 @@ +/* inffast_chunk.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "contrib/optimizations/inffast_chunk.h" +#include "contrib/optimizations/chunkcopy.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate() execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= INFLATE_FAST_MIN_INPUT (6 or 8 bytes) + strm->avail_out >= INFLATE_FAST_MIN_OUTPUT (258 bytes) + start >= strm->avail_out + state->bits < 8 + (state->hold >> state->bits) == 0 + strm->next_out[0..strm->avail_out] does not overlap with + strm->next_in[0..strm->avail_in] + strm->state->window is allocated with an additional + CHUNKCOPY_CHUNK_SIZE-1 bytes of padding beyond strm->state->wsize + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + INFLATE_FAST_MIN_INPUT: 6 or 8 bytes + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The wide input data reading option reads 64 input bits at a time. Thus, + if strm->avail_in >= 8, then there is enough input to avoid checking for + available input while decoding. Reading consumes the input with: + + hold |= read64le(in) << bits; + in += 6; + bits += 48; + + reporting 6 bytes of new input because |bits| is 0..15 (2 bytes rounded + up, worst case) and 6 bytes is enough to decode as noted above. At exit, + hold &= (1U << bits) - 1 drops excess input to keep the invariant: + + (state->hold >> state->bits) == 0 + + INFLATE_FAST_MIN_OUTPUT: 258 bytes + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + available output space while decoding. + */ +void ZLIB_INTERNAL inflate_fast_chunk_(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ + unsigned char FAR *limit; /* safety limit for chunky copies */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + inflate_holder_t hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - (INFLATE_FAST_MIN_INPUT - 1)); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - (INFLATE_FAST_MIN_OUTPUT - 1)); + limit = out + strm->avail_out; +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = (state->wnext == 0 && whave >= wsize) ? wsize : state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } +#endif + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext >= op) { /* contiguous in window */ + from += wnext - op; + } + else { /* wrap around window */ + op -= wnext; + from += wsize - op; + if (op < len) { /* some from end of window */ + len -= op; + out = chunkcopy_safe(out, from, op, limit); + from = window; /* more from start of window */ + op = wnext; + /* This (rare) case can create a situation where + the first chunkcopy below must be checked. + */ + } + } + if (op < len) { /* still need some from output */ + out = chunkcopy_safe(out, from, op, limit); + len -= op; + /* When dist is small the amount of data that can be + copied from the window is also small, and progress + towards the dangerous end of the output buffer is + also small. This means that for trivial memsets and + for chunkunroll_relaxed() a safety check is + unnecessary. However, these conditions may not be + entered at all, and in that case it's possible that + the main copy is near the end. + */ + out = chunkunroll_relaxed(out, &dist, &len); + out = chunkcopy_safe(out, out - dist, len, limit); + } else { + /* from points to window, so there is no risk of + overlapping pointers requiring memset-like behaviour + */ + out = chunkcopy_safe(out, from, len, limit); + } + } + else { + /* Whole reference is in range of current output. No + range checks are necessary because we start with room + for at least 258 bytes of output, so unroll and roundoff + operations can write beyond `out+len` so long as they + stay within 258 bytes of `out`. + */ + out = chunkcopy_lapped_relaxed(out, dist, len); + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? + (INFLATE_FAST_MIN_INPUT - 1) + (last - in) : + (INFLATE_FAST_MIN_INPUT - 1) - (in - last)); + strm->avail_out = (unsigned)(out < end ? + (INFLATE_FAST_MIN_OUTPUT - 1) + (end - out) : + (INFLATE_FAST_MIN_OUTPUT - 1) - (out - end)); + state->hold = hold; + state->bits = bits; + + Assert((state->hold >> state->bits) == 0, "invalid input data state"); + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/deps/zlib/contrib/optimizations/inffast_chunk.h b/deps/zlib/contrib/optimizations/inffast_chunk.h new file mode 100644 index 00000000000000..39c771b863c7ed --- /dev/null +++ b/deps/zlib/contrib/optimizations/inffast_chunk.h @@ -0,0 +1,26 @@ +/* inffast_chunk.h -- header to use inffast_chunk.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * Copyright (C) 2017 ARM, Inc. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +#include "inffast.h" + +/* INFLATE_FAST_MIN_INPUT: the minimum number of input bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair (15 bits for the length code, 5 bits for length + extra, 15 bits for the distance code, 13 bits for distance extra) requires + reading up to 48 input bits (6 bytes). The wide input data reading option + requires a little endian machine, and reads 64 input bits (8 bytes). +*/ +#ifdef INFLATE_CHUNK_READ_64LE +#undef INFLATE_FAST_MIN_INPUT +#define INFLATE_FAST_MIN_INPUT 8 +#endif + +void ZLIB_INTERNAL inflate_fast_chunk_ OF((z_streamp strm, unsigned start)); diff --git a/deps/zlib/contrib/optimizations/inflate.c b/deps/zlib/contrib/optimizations/inflate.c new file mode 100644 index 00000000000000..81d558bd6ef5fa --- /dev/null +++ b/deps/zlib/contrib/optimizations/inflate.c @@ -0,0 +1,1583 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "contrib/optimizations/inffast_chunk.h" +#include "contrib/optimizations/chunkcopy.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)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 */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + state->check = 1L; /* 1L is the result of adler32() zero length data */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + 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. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + unsigned wsize = 1U << state->wbits; + state->window = (unsigned char FAR *) + ZALLOC(strm, wsize + CHUNKCOPY_CHUNK_SIZE, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; +#ifdef INFLATE_CLEAR_UNUSED_UNDEFINED + /* Copies from the overflow portion of this buffer are undefined and + may cause analysis tools to raise a warning if we don't initialize + it. However, this undefined data overwrites other undefined data + and is subsequently either overwritten or left deliberately + undefined at the end of decode; so there's really no point. + */ + zmemzero(state->window + wsize, CHUNKCOPY_CHUNK_SIZE); +#endif + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { + RESTORE(); + inflate_fast_chunk_(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + put = chunkcopy_safe(put, from, copy, put + left); + } + else { /* copy from output */ + copy = state->length; + if (copy > left) copy = left; + put = chunkcopy_lapped_safe(put, state->offset, copy, put + left); + } + left -= copy; + state->length -= copy; + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + /* We write a defined value in the unused space to help mark + * where the stream has ended. We don't use zeros as that can + * mislead clients relying on undefined behavior (i.e. assuming + * that the data is over when the buffer has a zero/null value). + */ + if (left >= CHUNKCOPY_CHUNK_SIZE) + memset(put, 0x55, CHUNKCOPY_CHUNK_SIZE); + else + memset(put, 0x55, left); + + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/deps/zlib/contrib/optimizations/insert_string.h b/deps/zlib/contrib/optimizations/insert_string.h new file mode 100644 index 00000000000000..69eee3dc9e91fc --- /dev/null +++ b/deps/zlib/contrib/optimizations/insert_string.h @@ -0,0 +1,122 @@ +/* insert_string.h + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifdef _MSC_VER +#define INLINE __inline +#else +#define INLINE inline +#endif + +/* Optimized insert_string block */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) || defined(CRC32_ARMV8_CRC32) +#define TARGET_CPU_WITH_CRC +// clang-format off +#if defined(CRC32_SIMD_SSE42_PCLMUL) + /* Required to make MSVC bot build pass. */ + #include + #if defined(__GNUC__) || defined(__clang__) + #undef TARGET_CPU_WITH_CRC + #define TARGET_CPU_WITH_CRC __attribute__((target("sse4.2"))) + #endif + + #define _cpu_crc32_u32 _mm_crc32_u32 + +#elif defined(CRC32_ARMV8_CRC32) + #include "arm_features.h" + #if defined(__clang__) + #undef TARGET_CPU_WITH_CRC + #define __crc32cw __builtin_arm_crc32cw + #endif + + #define _cpu_crc32_u32 __crc32cw + + #if defined(__aarch64__) + #define TARGET_CPU_WITH_CRC __attribute__((target("crc"))) + #else // !defined(__aarch64__) + #define TARGET_CPU_WITH_CRC __attribute__((target("armv8-a,crc"))) + #endif // defined(__aarch64__) +#endif +// clang-format on +TARGET_CPU_WITH_CRC +local INLINE Pos insert_string_optimized(deflate_state* const s, + const Pos str) { + Pos ret; + unsigned *ip, val, h = 0; + + ip = (unsigned*)&s->window[str]; + val = *ip; + + if (s->level >= 6) + val &= 0xFFFFFF; + + /* Unlike the case of data integrity checks for GZIP format where the + * polynomial used is defined (https://tools.ietf.org/html/rfc1952#page-11), + * here it is just a hash function for the hash table used while + * performing compression. + */ + h = _cpu_crc32_u32(h, val); + + ret = s->head[h & s->hash_mask]; + s->head[h & s->hash_mask] = str; + s->prev[str & s->w_mask] = ret; + return ret; +} +#endif /* Optimized insert_string block */ + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s, h, c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask) + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +local INLINE Pos insert_string_c(deflate_state* const s, const Pos str) { + Pos ret; + + UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH - 1)]); +#ifdef FASTEST + ret = s->head[s->ins_h]; +#else + ret = s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = str; + + return ret; +} + +local INLINE Pos insert_string(deflate_state* const s, const Pos str) { +/* String dictionary insertion: faster symbol hashing has a positive impact + * on data compression speeds (around 20% on Intel and 36% on Arm Cortex big + * cores). + * A misfeature is that the generated compressed output will differ from + * vanilla zlib (even though it is still valid 'DEFLATE-d' content). + * + * We offer here a way to disable the optimization if there is the expectation + * that compressed content should match when compared to vanilla zlib. + */ +#if !defined(CHROMIUM_ZLIB_NO_CASTAGNOLI) + /* TODO(cavalcantii): unify CPU features code. */ +#if defined(CRC32_ARMV8_CRC32) + if (arm_cpu_enable_crc32) + return insert_string_optimized(s, str); +#elif defined(CRC32_SIMD_SSE42_PCLMUL) + if (x86_cpu_enable_simd) + return insert_string_optimized(s, str); +#endif +#endif + return insert_string_c(s, str); +} diff --git a/deps/zlib/contrib/optimizations/slide_hash_neon.h b/deps/zlib/contrib/optimizations/slide_hash_neon.h new file mode 100644 index 00000000000000..26995d70f709e7 --- /dev/null +++ b/deps/zlib/contrib/optimizations/slide_hash_neon.h @@ -0,0 +1,65 @@ +/* Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifndef __SLIDE_HASH__NEON__ +#define __SLIDE_HASH__NEON__ + +#include "deflate.h" +#include + +inline static void ZLIB_INTERNAL neon_slide_hash_update(Posf *hash, + const uInt hash_size, + const ush w_size) +{ + /* NEON 'Q' registers allow to store 128 bits, so we can load 8x16-bits + * values. For further details, check: + * ARM DHT 0002A, section 1.3.2 NEON Registers. + */ + const size_t chunk = sizeof(uint16x8_t) / sizeof(uint16_t); + /* Unrolling the operation yielded a compression performance boost in both + * ARMv7 (from 11.7% to 13.4%) and ARMv8 (from 3.7% to 7.5%) for HTML4 + * content. For full benchmarking data, check: http://crbug.com/863257. + */ + const size_t stride = 2*chunk; + const uint16x8_t v = vdupq_n_u16(w_size); + + for (Posf *end = hash + hash_size; hash != end; hash += stride) { + uint16x8_t m_low = vld1q_u16(hash); + uint16x8_t m_high = vld1q_u16(hash + chunk); + + /* The first 'q' in vqsubq_u16 makes these subtracts saturate to zero, + * replacing the ternary operator expression in the original code: + * (m >= wsize ? m - wsize : NIL). + */ + m_low = vqsubq_u16(m_low, v); + m_high = vqsubq_u16(m_high, v); + + vst1q_u16(hash, m_low); + vst1q_u16(hash + chunk, m_high); + } +} + + +inline static void ZLIB_INTERNAL neon_slide_hash(Posf *head, Posf *prev, + const unsigned short w_size, + const uInt hash_size) +{ + /* + * SIMD implementation for hash table rebase assumes: + * 1. hash chain offset (Pos) is 2 bytes. + * 2. hash table size is multiple of 32 bytes. + * #1 should be true as Pos is defined as "ush" + * #2 should be true as hash_bits are greater than 7 + */ + const size_t size = hash_size * sizeof(head[0]); + Assert(sizeof(Pos) == 2, "Wrong Pos size."); + Assert((size % sizeof(uint16x8_t) * 2) == 0, "Hash table size error."); + + neon_slide_hash_update(head, hash_size, w_size); +#ifndef FASTEST + neon_slide_hash_update(prev, w_size, w_size); +#endif +} + +#endif diff --git a/deps/zlib/contrib/pascal/example.pas b/deps/zlib/contrib/pascal/example.pas deleted file mode 100644 index 5518b36a730855..00000000000000 --- a/deps/zlib/contrib/pascal/example.pas +++ /dev/null @@ -1,599 +0,0 @@ -(* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Pascal translation - * Copyright (C) 1998 by Jacques Nomssi Nzali. - * For conditions of distribution and use, see copyright notice in readme.txt - * - * Adaptation to the zlibpas interface - * Copyright (C) 2003 by Cosmin Truta. - * For conditions of distribution and use, see copyright notice in readme.txt - *) - -program example; - -{$DEFINE TEST_COMPRESS} -{DO NOT $DEFINE TEST_GZIO} -{$DEFINE TEST_DEFLATE} -{$DEFINE TEST_INFLATE} -{$DEFINE TEST_FLUSH} -{$DEFINE TEST_SYNC} -{$DEFINE TEST_DICT} - -uses SysUtils, zlibpas; - -const TESTFILE = 'foo.gz'; - -(* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - *) -const hello: PChar = 'hello, hello!'; - -const dictionary: PChar = 'hello'; - -var dictId: LongInt; (* Adler32 value of the dictionary *) - -procedure CHECK_ERR(err: Integer; msg: String); -begin - if err <> Z_OK then - begin - WriteLn(msg, ' error: ', err); - Halt(1); - end; -end; - -procedure EXIT_ERR(const msg: String); -begin - WriteLn('Error: ', msg); - Halt(1); -end; - -(* =========================================================================== - * Test compress and uncompress - *) -{$IFDEF TEST_COMPRESS} -procedure test_compress(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - len: LongInt; -begin - len := StrLen(hello)+1; - - err := compress(compr, comprLen, hello, len); - CHECK_ERR(err, 'compress'); - - StrCopy(PChar(uncompr), 'garbage'); - - err := uncompress(uncompr, uncomprLen, compr, comprLen); - CHECK_ERR(err, 'uncompress'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad uncompress') - else - WriteLn('uncompress(): ', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test read/write of .gz files - *) -{$IFDEF TEST_GZIO} -procedure test_gzio(const fname: PChar; (* compressed file name *) - uncompr: Pointer; - uncomprLen: LongInt); -var err: Integer; - len: Integer; - zfile: gzFile; - pos: LongInt; -begin - len := StrLen(hello)+1; - - zfile := gzopen(fname, 'wb'); - if zfile = NIL then - begin - WriteLn('gzopen error'); - Halt(1); - end; - gzputc(zfile, 'h'); - if gzputs(zfile, 'ello') <> 4 then - begin - WriteLn('gzputs err: ', gzerror(zfile, err)); - Halt(1); - end; - {$IFDEF GZ_FORMAT_STRING} - if gzprintf(zfile, ', %s!', 'hello') <> 8 then - begin - WriteLn('gzprintf err: ', gzerror(zfile, err)); - Halt(1); - end; - {$ELSE} - if gzputs(zfile, ', hello!') <> 8 then - begin - WriteLn('gzputs err: ', gzerror(zfile, err)); - Halt(1); - end; - {$ENDIF} - gzseek(zfile, 1, SEEK_CUR); (* add one zero byte *) - gzclose(zfile); - - zfile := gzopen(fname, 'rb'); - if zfile = NIL then - begin - WriteLn('gzopen error'); - Halt(1); - end; - - StrCopy(PChar(uncompr), 'garbage'); - - if gzread(zfile, uncompr, uncomprLen) <> len then - begin - WriteLn('gzread err: ', gzerror(zfile, err)); - Halt(1); - end; - if StrComp(PChar(uncompr), hello) <> 0 then - begin - WriteLn('bad gzread: ', PChar(uncompr)); - Halt(1); - end - else - WriteLn('gzread(): ', PChar(uncompr)); - - pos := gzseek(zfile, -8, SEEK_CUR); - if (pos <> 6) or (gztell(zfile) <> pos) then - begin - WriteLn('gzseek error, pos=', pos, ', gztell=', gztell(zfile)); - Halt(1); - end; - - if gzgetc(zfile) <> ' ' then - begin - WriteLn('gzgetc error'); - Halt(1); - end; - - if gzungetc(' ', zfile) <> ' ' then - begin - WriteLn('gzungetc error'); - Halt(1); - end; - - gzgets(zfile, PChar(uncompr), uncomprLen); - uncomprLen := StrLen(PChar(uncompr)); - if uncomprLen <> 7 then (* " hello!" *) - begin - WriteLn('gzgets err after gzseek: ', gzerror(zfile, err)); - Halt(1); - end; - if StrComp(PChar(uncompr), hello + 6) <> 0 then - begin - WriteLn('bad gzgets after gzseek'); - Halt(1); - end - else - WriteLn('gzgets() after gzseek: ', PChar(uncompr)); - - gzclose(zfile); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with small buffers - *) -{$IFDEF TEST_DEFLATE} -procedure test_deflate(compr: Pointer; comprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; - len: LongInt; -begin - len := StrLen(hello)+1; - - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_in := hello; - c_stream.next_out := compr; - - while (c_stream.total_in <> len) and - (c_stream.total_out < comprLen) do - begin - c_stream.avail_out := 1; { force small buffers } - c_stream.avail_in := 1; - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - end; - - (* Finish the stream, still forcing small buffers: *) - while TRUE do - begin - c_stream.avail_out := 1; - err := deflate(c_stream, Z_FINISH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'deflate'); - end; - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with small buffers - *) -{$IFDEF TEST_INFLATE} -procedure test_inflate(compr: Pointer; comprLen : LongInt; - uncompr: Pointer; uncomprLen : LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := 0; - d_stream.next_out := uncompr; - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - while (d_stream.total_out < uncomprLen) and - (d_stream.total_in < comprLen) do - begin - d_stream.avail_out := 1; (* force small buffers *) - d_stream.avail_in := 1; - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'inflate'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad inflate') - else - WriteLn('inflate(): ', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with large buffers and dynamic change of compression level - *) -{$IFDEF TEST_DEFLATE} -procedure test_large_deflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; -begin - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_BEST_SPEED); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_out := compr; - c_stream.avail_out := Integer(comprLen); - - (* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - *) - c_stream.next_in := uncompr; - c_stream.avail_in := Integer(uncomprLen); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - if c_stream.avail_in <> 0 then - EXIT_ERR('deflate not greedy'); - - (* Feed in already compressed data and switch to no compression: *) - deflateParams(c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in := compr; - c_stream.avail_in := Integer(comprLen div 2); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - - (* Switch back to compressing mode: *) - deflateParams(c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in := uncompr; - c_stream.avail_in := Integer(uncomprLen); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - EXIT_ERR('deflate should report Z_STREAM_END'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with large buffers - *) -{$IFDEF TEST_INFLATE} -procedure test_large_inflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := Integer(comprLen); - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - while TRUE do - begin - d_stream.next_out := uncompr; (* discard the output *) - d_stream.avail_out := Integer(uncomprLen); - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'large inflate'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if d_stream.total_out <> 2 * uncomprLen + comprLen div 2 then - begin - WriteLn('bad large inflate: ', d_stream.total_out); - Halt(1); - end - else - WriteLn('large_inflate(): OK'); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with full flush - *) -{$IFDEF TEST_FLUSH} -procedure test_flush(compr: Pointer; var comprLen : LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; - len: Integer; -begin - len := StrLen(hello)+1; - - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_in := hello; - c_stream.next_out := compr; - c_stream.avail_in := 3; - c_stream.avail_out := Integer(comprLen); - err := deflate(c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, 'deflate'); - - Inc(PByteArray(compr)^[3]); (* force an error in first compressed block *) - c_stream.avail_in := len - 3; - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - CHECK_ERR(err, 'deflate'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); - - comprLen := c_stream.total_out; -end; -{$ENDIF} - -(* =========================================================================== - * Test inflateSync() - *) -{$IFDEF TEST_SYNC} -procedure test_sync(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen : LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := 2; (* just read the zlib header *) - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - d_stream.next_out := uncompr; - d_stream.avail_out := Integer(uncomprLen); - - inflate(d_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'inflate'); - - d_stream.avail_in := Integer(comprLen-2); (* read all compressed data *) - err := inflateSync(d_stream); (* but skip the damaged part *) - CHECK_ERR(err, 'inflateSync'); - - err := inflate(d_stream, Z_FINISH); - if err <> Z_DATA_ERROR then - EXIT_ERR('inflate should report DATA_ERROR'); - (* Because of incorrect adler32 *) - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - WriteLn('after inflateSync(): hel', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with preset dictionary - *) -{$IFDEF TEST_DICT} -procedure test_dict_deflate(compr: Pointer; comprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; -begin - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - err := deflateSetDictionary(c_stream, dictionary, StrLen(dictionary)); - CHECK_ERR(err, 'deflateSetDictionary'); - - dictId := c_stream.adler; - c_stream.next_out := compr; - c_stream.avail_out := Integer(comprLen); - - c_stream.next_in := hello; - c_stream.avail_in := StrLen(hello)+1; - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - EXIT_ERR('deflate should report Z_STREAM_END'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with a preset dictionary - *) -{$IFDEF TEST_DICT} -procedure test_dict_inflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := Integer(comprLen); - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - d_stream.next_out := uncompr; - d_stream.avail_out := Integer(uncomprLen); - - while TRUE do - begin - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - if err = Z_NEED_DICT then - begin - if d_stream.adler <> dictId then - EXIT_ERR('unexpected dictionary'); - err := inflateSetDictionary(d_stream, dictionary, StrLen(dictionary)); - end; - CHECK_ERR(err, 'inflate with dict'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad inflate with dict') - else - WriteLn('inflate with dictionary: ', PChar(uncompr)); -end; -{$ENDIF} - -var compr, uncompr: Pointer; - comprLen, uncomprLen: LongInt; - -begin - if zlibVersion^ <> ZLIB_VERSION[1] then - EXIT_ERR('Incompatible zlib version'); - - WriteLn('zlib version: ', zlibVersion); - WriteLn('zlib compile flags: ', Format('0x%x', [zlibCompileFlags])); - - comprLen := 10000 * SizeOf(Integer); (* don't overflow on MSDOS *) - uncomprLen := comprLen; - GetMem(compr, comprLen); - GetMem(uncompr, uncomprLen); - if (compr = NIL) or (uncompr = NIL) then - EXIT_ERR('Out of memory'); - (* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - *) - FillChar(compr^, comprLen, 0); - FillChar(uncompr^, uncomprLen, 0); - - {$IFDEF TEST_COMPRESS} - WriteLn('** Testing compress'); - test_compress(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_GZIO} - WriteLn('** Testing gzio'); - if ParamCount >= 1 then - test_gzio(ParamStr(1), uncompr, uncomprLen) - else - test_gzio(TESTFILE, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_DEFLATE} - WriteLn('** Testing deflate with small buffers'); - test_deflate(compr, comprLen); - {$ENDIF} - {$IFDEF TEST_INFLATE} - WriteLn('** Testing inflate with small buffers'); - test_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_DEFLATE} - WriteLn('** Testing deflate with large buffers'); - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - {$IFDEF TEST_INFLATE} - WriteLn('** Testing inflate with large buffers'); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_FLUSH} - WriteLn('** Testing deflate with full flush'); - test_flush(compr, comprLen); - {$ENDIF} - {$IFDEF TEST_SYNC} - WriteLn('** Testing inflateSync'); - test_sync(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - comprLen := uncomprLen; - - {$IFDEF TEST_DICT} - WriteLn('** Testing deflate and inflate with preset dictionary'); - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - FreeMem(compr, comprLen); - FreeMem(uncompr, uncomprLen); -end. diff --git a/deps/zlib/contrib/pascal/readme.txt b/deps/zlib/contrib/pascal/readme.txt deleted file mode 100644 index 60e87c8a331b5d..00000000000000 --- a/deps/zlib/contrib/pascal/readme.txt +++ /dev/null @@ -1,76 +0,0 @@ - -This directory contains a Pascal (Delphi, Kylix) interface to the -zlib data compression library. - - -Directory listing -================= - -zlibd32.mak makefile for Borland C++ -example.pas usage example of zlib -zlibpas.pas the Pascal interface to zlib -readme.txt this file - - -Compatibility notes -=================== - -- Although the name "zlib" would have been more normal for the - zlibpas unit, this name is already taken by Borland's ZLib unit. - This is somehow unfortunate, because that unit is not a genuine - interface to the full-fledged zlib functionality, but a suite of - class wrappers around zlib streams. Other essential features, - such as checksums, are missing. - It would have been more appropriate for that unit to have a name - like "ZStreams", or something similar. - -- The C and zlib-supplied types int, uInt, long, uLong, etc. are - translated directly into Pascal types of similar sizes (Integer, - LongInt, etc.), to avoid namespace pollution. In particular, - there is no conversion of unsigned int into a Pascal unsigned - integer. The Word type is non-portable and has the same size - (16 bits) both in a 16-bit and in a 32-bit environment, unlike - Integer. Even if there is a 32-bit Cardinal type, there is no - real need for unsigned int in zlib under a 32-bit environment. - -- Except for the callbacks, the zlib function interfaces are - assuming the calling convention normally used in Pascal - (__pascal for DOS and Windows16, __fastcall for Windows32). - Since the cdecl keyword is used, the old Turbo Pascal does - not work with this interface. - -- The gz* function interfaces are not translated, to avoid - interfacing problems with the C runtime library. Besides, - gzprintf(gzFile file, const char *format, ...) - cannot be translated into Pascal. - - -Legal issues -============ - -The zlibpas interface is: - Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler. - Copyright (C) 1998 by Bob Dellaca. - Copyright (C) 2003 by Cosmin Truta. - -The example program is: - Copyright (C) 1995-2003 by Jean-loup Gailly. - Copyright (C) 1998,1999,2000 by Jacques Nomssi Nzali. - Copyright (C) 2003 by Cosmin Truta. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - diff --git a/deps/zlib/contrib/pascal/zlibd32.mak b/deps/zlib/contrib/pascal/zlibd32.mak deleted file mode 100644 index 9bb00b7cc4211c..00000000000000 --- a/deps/zlib/contrib/pascal/zlibd32.mak +++ /dev/null @@ -1,99 +0,0 @@ -# Makefile for zlib -# For use with Delphi and C++ Builder under Win32 -# Updated for zlib 1.2.x by Cosmin Truta - -# ------------ Borland C++ ------------ - -# This project uses the Delphi (fastcall/register) calling convention: -LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl - -CC = bcc32 -LD = bcc32 -AR = tlib -# do not use "-pr" in CFLAGS -CFLAGS = -a -d -k- -O2 $(LOC) -LDFLAGS = - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del *.obj - -del *.exe - -del *.lib - -del *.tds - -del zlib.bak - -del foo.gz - diff --git a/deps/zlib/contrib/pascal/zlibpas.pas b/deps/zlib/contrib/pascal/zlibpas.pas deleted file mode 100644 index a0dff11b505f45..00000000000000 --- a/deps/zlib/contrib/pascal/zlibpas.pas +++ /dev/null @@ -1,276 +0,0 @@ -(* zlibpas -- Pascal interface to the zlib data compression library - * - * Copyright (C) 2003 Cosmin Truta. - * Derived from original sources by Bob Dellaca. - * For conditions of distribution and use, see copyright notice in readme.txt - *) - -unit zlibpas; - -interface - -const - ZLIB_VERSION = '1.2.11'; - ZLIB_VERNUM = $12a0; - -type - alloc_func = function(opaque: Pointer; items, size: Integer): Pointer; - cdecl; - free_func = procedure(opaque, address: Pointer); - cdecl; - - in_func = function(opaque: Pointer; var buf: PByte): Integer; - cdecl; - out_func = function(opaque: Pointer; buf: PByte; size: Integer): Integer; - cdecl; - - z_streamp = ^z_stream; - z_stream = packed record - next_in: PChar; (* next input byte *) - avail_in: Integer; (* number of bytes available at next_in *) - total_in: LongInt; (* total nb of input bytes read so far *) - - next_out: PChar; (* next output byte should be put there *) - avail_out: Integer; (* remaining free space at next_out *) - total_out: LongInt; (* total nb of bytes output so far *) - - msg: PChar; (* last error message, NULL if no error *) - state: Pointer; (* not visible by applications *) - - zalloc: alloc_func; (* used to allocate the internal state *) - zfree: free_func; (* used to free the internal state *) - opaque: Pointer; (* private data object passed to zalloc and zfree *) - - data_type: Integer; (* best guess about the data type: ascii or binary *) - adler: LongInt; (* adler32 value of the uncompressed data *) - reserved: LongInt; (* reserved for future use *) - end; - - gz_headerp = ^gz_header; - gz_header = packed record - text: Integer; (* true if compressed data believed to be text *) - time: LongInt; (* modification time *) - xflags: Integer; (* extra flags (not used when writing a gzip file) *) - os: Integer; (* operating system *) - extra: PChar; (* pointer to extra field or Z_NULL if none *) - extra_len: Integer; (* extra field length (valid if extra != Z_NULL) *) - extra_max: Integer; (* space at extra (only when reading header) *) - name: PChar; (* pointer to zero-terminated file name or Z_NULL *) - name_max: Integer; (* space at name (only when reading header) *) - comment: PChar; (* pointer to zero-terminated comment or Z_NULL *) - comm_max: Integer; (* space at comment (only when reading header) *) - hcrc: Integer; (* true if there was or will be a header crc *) - done: Integer; (* true when done reading gzip header *) - end; - -(* constants *) -const - Z_NO_FLUSH = 0; - Z_PARTIAL_FLUSH = 1; - Z_SYNC_FLUSH = 2; - Z_FULL_FLUSH = 3; - Z_FINISH = 4; - Z_BLOCK = 5; - Z_TREES = 6; - - Z_OK = 0; - Z_STREAM_END = 1; - Z_NEED_DICT = 2; - Z_ERRNO = -1; - Z_STREAM_ERROR = -2; - Z_DATA_ERROR = -3; - Z_MEM_ERROR = -4; - Z_BUF_ERROR = -5; - Z_VERSION_ERROR = -6; - - Z_NO_COMPRESSION = 0; - Z_BEST_SPEED = 1; - Z_BEST_COMPRESSION = 9; - Z_DEFAULT_COMPRESSION = -1; - - Z_FILTERED = 1; - Z_HUFFMAN_ONLY = 2; - Z_RLE = 3; - Z_FIXED = 4; - Z_DEFAULT_STRATEGY = 0; - - Z_BINARY = 0; - Z_TEXT = 1; - Z_ASCII = 1; - Z_UNKNOWN = 2; - - Z_DEFLATED = 8; - -(* basic functions *) -function zlibVersion: PChar; -function deflateInit(var strm: z_stream; level: Integer): Integer; -function deflate(var strm: z_stream; flush: Integer): Integer; -function deflateEnd(var strm: z_stream): Integer; -function inflateInit(var strm: z_stream): Integer; -function inflate(var strm: z_stream; flush: Integer): Integer; -function inflateEnd(var strm: z_stream): Integer; - -(* advanced functions *) -function deflateInit2(var strm: z_stream; level, method, windowBits, - memLevel, strategy: Integer): Integer; -function deflateSetDictionary(var strm: z_stream; const dictionary: PChar; - dictLength: Integer): Integer; -function deflateCopy(var dest, source: z_stream): Integer; -function deflateReset(var strm: z_stream): Integer; -function deflateParams(var strm: z_stream; level, strategy: Integer): Integer; -function deflateTune(var strm: z_stream; good_length, max_lazy, nice_length, max_chain: Integer): Integer; -function deflateBound(var strm: z_stream; sourceLen: LongInt): LongInt; -function deflatePending(var strm: z_stream; var pending: Integer; var bits: Integer): Integer; -function deflatePrime(var strm: z_stream; bits, value: Integer): Integer; -function deflateSetHeader(var strm: z_stream; head: gz_header): Integer; -function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; -function inflateSetDictionary(var strm: z_stream; const dictionary: PChar; - dictLength: Integer): Integer; -function inflateSync(var strm: z_stream): Integer; -function inflateCopy(var dest, source: z_stream): Integer; -function inflateReset(var strm: z_stream): Integer; -function inflateReset2(var strm: z_stream; windowBits: Integer): Integer; -function inflatePrime(var strm: z_stream; bits, value: Integer): Integer; -function inflateMark(var strm: z_stream): LongInt; -function inflateGetHeader(var strm: z_stream; var head: gz_header): Integer; -function inflateBackInit(var strm: z_stream; - windowBits: Integer; window: PChar): Integer; -function inflateBack(var strm: z_stream; in_fn: in_func; in_desc: Pointer; - out_fn: out_func; out_desc: Pointer): Integer; -function inflateBackEnd(var strm: z_stream): Integer; -function zlibCompileFlags: LongInt; - -(* utility functions *) -function compress(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt): Integer; -function compress2(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt; - level: Integer): Integer; -function compressBound(sourceLen: LongInt): LongInt; -function uncompress(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt): Integer; - -(* checksum functions *) -function adler32(adler: LongInt; const buf: PChar; len: Integer): LongInt; -function adler32_combine(adler1, adler2, len2: LongInt): LongInt; -function crc32(crc: LongInt; const buf: PChar; len: Integer): LongInt; -function crc32_combine(crc1, crc2, len2: LongInt): LongInt; - -(* various hacks, don't look :) *) -function deflateInit_(var strm: z_stream; level: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateInit_(var strm: z_stream; const version: PChar; - stream_size: Integer): Integer; -function deflateInit2_(var strm: z_stream; - level, method, windowBits, memLevel, strategy: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateInit2_(var strm: z_stream; windowBits: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateBackInit_(var strm: z_stream; - windowBits: Integer; window: PChar; - const version: PChar; stream_size: Integer): Integer; - - -implementation - -{$L adler32.obj} -{$L compress.obj} -{$L crc32.obj} -{$L deflate.obj} -{$L infback.obj} -{$L inffast.obj} -{$L inflate.obj} -{$L inftrees.obj} -{$L trees.obj} -{$L uncompr.obj} -{$L zutil.obj} - -function adler32; external; -function adler32_combine; external; -function compress; external; -function compress2; external; -function compressBound; external; -function crc32; external; -function crc32_combine; external; -function deflate; external; -function deflateBound; external; -function deflateCopy; external; -function deflateEnd; external; -function deflateInit_; external; -function deflateInit2_; external; -function deflateParams; external; -function deflatePending; external; -function deflatePrime; external; -function deflateReset; external; -function deflateSetDictionary; external; -function deflateSetHeader; external; -function deflateTune; external; -function inflate; external; -function inflateBack; external; -function inflateBackEnd; external; -function inflateBackInit_; external; -function inflateCopy; external; -function inflateEnd; external; -function inflateGetHeader; external; -function inflateInit_; external; -function inflateInit2_; external; -function inflateMark; external; -function inflatePrime; external; -function inflateReset; external; -function inflateReset2; external; -function inflateSetDictionary; external; -function inflateSync; external; -function uncompress; external; -function zlibCompileFlags; external; -function zlibVersion; external; - -function deflateInit(var strm: z_stream; level: Integer): Integer; -begin - Result := deflateInit_(strm, level, ZLIB_VERSION, sizeof(z_stream)); -end; - -function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel, - strategy: Integer): Integer; -begin - Result := deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateInit(var strm: z_stream): Integer; -begin - Result := inflateInit_(strm, ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; -begin - Result := inflateInit2_(strm, windowBits, ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateBackInit(var strm: z_stream; - windowBits: Integer; window: PChar): Integer; -begin - Result := inflateBackInit_(strm, windowBits, window, - ZLIB_VERSION, sizeof(z_stream)); -end; - -function _malloc(Size: Integer): Pointer; cdecl; -begin - GetMem(Result, Size); -end; - -procedure _free(Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; -begin - FillChar(P^, count, B); -end; - -procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; -begin - Move(source^, dest^, count); -end; - -end. diff --git a/deps/zlib/contrib/puff/Makefile b/deps/zlib/contrib/puff/Makefile deleted file mode 100644 index 0e2594c80885c0..00000000000000 --- a/deps/zlib/contrib/puff/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -CFLAGS=-O - -puff: puff.o pufftest.o - -puff.o: puff.h - -pufftest.o: puff.h - -test: puff - puff zeros.raw - -puft: puff.c puff.h pufftest.o - cc -fprofile-arcs -ftest-coverage -o puft puff.c pufftest.o - -# puff full coverage test (should say 100%) -cov: puft - @rm -f *.gcov *.gcda - @puft -w zeros.raw 2>&1 | cat > /dev/null - @echo '04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '00 00 00 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 254 - @echo '00 01 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '01 01 00 fe ff 0a' | xxd -r -p | puft -f 2>&1 | cat > /dev/null - @echo '02 7e ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '02' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '04 80 49 92 24 49 92 24 71 ff ff 93 11 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 249 - @echo '04 c0 81 08 00 00 00 00 20 7f eb 0b 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '0b 00 00' | xxd -r -p | puft -f 2>&1 | cat > /dev/null - @echo '1a 07' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '0c c0 81 00 00 00 00 00 90 ff 6b 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 245 - @puft -f zeros.raw 2>&1 | cat > /dev/null - @echo 'fc 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 253 - @echo '04 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 252 - @echo '04 00 24 49' | xxd -r -p | puft 2> /dev/null || test $$? -eq 251 - @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 84' | xxd -r -p | puft 2> /dev/null || test $$? -eq 248 - @echo '04 00 24 e9 ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 250 - @echo '04 00 24 e9 ff 6d' | xxd -r -p | puft 2> /dev/null || test $$? -eq 247 - @gcov -n puff.c - -clean: - rm -f puff puft *.o *.gc* diff --git a/deps/zlib/contrib/puff/README b/deps/zlib/contrib/puff/README deleted file mode 100644 index bbc4cb595ec1a6..00000000000000 --- a/deps/zlib/contrib/puff/README +++ /dev/null @@ -1,63 +0,0 @@ -Puff -- A Simple Inflate -3 Mar 2003 -Mark Adler -madler@alumni.caltech.edu - -What this is -- - -puff.c provides the routine puff() to decompress the deflate data format. It -does so more slowly than zlib, but the code is about one-fifth the size of the -inflate code in zlib, and written to be very easy to read. - -Why I wrote this -- - -puff.c was written to document the deflate format unambiguously, by virtue of -being working C code. It is meant to supplement RFC 1951, which formally -describes the deflate format. I have received many questions on details of the -deflate format, and I hope that reading this code will answer those questions. -puff.c is heavily commented with details of the deflate format, especially -those little nooks and cranies of the format that might not be obvious from a -specification. - -puff.c may also be useful in applications where code size or memory usage is a -very limited resource, and speed is not as important. - -How to use it -- - -Well, most likely you should just be reading puff.c and using zlib for actual -applications, but if you must ... - -Include puff.h in your code, which provides this prototype: - -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen); /* amount of input available */ - -Then you can call puff() to decompress a deflate stream that is in memory in -its entirety at source, to a sufficiently sized block of memory for the -decompressed data at dest. puff() is the only external symbol in puff.c The -only C library functions that puff.c needs are setjmp() and longjmp(), which -are used to simplify error checking in the code to improve readabilty. puff.c -does no memory allocation, and uses less than 2K bytes off of the stack. - -If destlen is not enough space for the uncompressed data, then inflate will -return an error without writing more than destlen bytes. Note that this means -that in order to decompress the deflate data successfully, you need to know -the size of the uncompressed data ahead of time. - -If needed, puff() can determine the size of the uncompressed data with no -output space. This is done by passing dest equal to (unsigned char *)0. Then -the initial value of *destlen is ignored and *destlen is set to the length of -the uncompressed data. So if the size of the uncompressed data is not known, -then two passes of puff() can be used--first to determine the size, and second -to do the actual inflation after allocating the appropriate memory. Not -pretty, but it works. (This is one of the reasons you should be using zlib.) - -The deflate format is self-terminating. If the deflate stream does not end -in *sourcelen bytes, puff() will return an error without reading at or past -endsource. - -On return, *sourcelen is updated to the amount of input data consumed, and -*destlen is updated to the size of the uncompressed data. See the comments -in puff.c for the possible return codes for puff(). diff --git a/deps/zlib/contrib/puff/puff.c b/deps/zlib/contrib/puff/puff.c deleted file mode 100644 index c6c90d714206a3..00000000000000 --- a/deps/zlib/contrib/puff/puff.c +++ /dev/null @@ -1,840 +0,0 @@ -/* - * puff.c - * Copyright (C) 2002-2013 Mark Adler - * For conditions of distribution and use, see copyright notice in puff.h - * version 2.3, 21 Jan 2013 - * - * puff.c is a simple inflate written to be an unambiguous way to specify the - * deflate format. It is not written for speed but rather simplicity. As a - * side benefit, this code might actually be useful when small code is more - * important than speed, such as bootstrap applications. For typical deflate - * data, zlib's inflate() is about four times as fast as puff(). zlib's - * inflate compiles to around 20K on my machine, whereas puff.c compiles to - * around 4K on my machine (a PowerPC using GNU cc). If the faster decode() - * function here is used, then puff() is only twice as slow as zlib's - * inflate(). - * - * All dynamically allocated memory comes from the stack. The stack required - * is less than 2K bytes. This code is compatible with 16-bit int's and - * assumes that long's are at least 32 bits. puff.c uses the short data type, - * assumed to be 16 bits, for arrays in order to conserve memory. The code - * works whether integers are stored big endian or little endian. - * - * In the comments below are "Format notes" that describe the inflate process - * and document some of the less obvious aspects of the format. This source - * code is meant to supplement RFC 1951, which formally describes the deflate - * format: - * - * http://www.zlib.org/rfc-deflate.html - */ - -/* - * Change history: - * - * 1.0 10 Feb 2002 - First version - * 1.1 17 Feb 2002 - Clarifications of some comments and notes - * - Update puff() dest and source pointers on negative - * errors to facilitate debugging deflators - * - Remove longest from struct huffman -- not needed - * - Simplify offs[] index in construct() - * - Add input size and checking, using longjmp() to - * maintain easy readability - * - Use short data type for large arrays - * - Use pointers instead of long to specify source and - * destination sizes to avoid arbitrary 4 GB limits - * 1.2 17 Mar 2002 - Add faster version of decode(), doubles speed (!), - * but leave simple version for readabilty - * - Make sure invalid distances detected if pointers - * are 16 bits - * - Fix fixed codes table error - * - Provide a scanning mode for determining size of - * uncompressed data - * 1.3 20 Mar 2002 - Go back to lengths for puff() parameters [Gailly] - * - Add a puff.h file for the interface - * - Add braces in puff() for else do [Gailly] - * - Use indexes instead of pointers for readability - * 1.4 31 Mar 2002 - Simplify construct() code set check - * - Fix some comments - * - Add FIXLCODES #define - * 1.5 6 Apr 2002 - Minor comment fixes - * 1.6 7 Aug 2002 - Minor format changes - * 1.7 3 Mar 2003 - Added test code for distribution - * - Added zlib-like license - * 1.8 9 Jan 2004 - Added some comments on no distance codes case - * 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland] - * - Catch missing end-of-block symbol error - * 2.0 25 Jul 2008 - Add #define to permit distance too far back - * - Add option in TEST code for puff to write the data - * - Add option in TEST code to skip input bytes - * - Allow TEST code to read from piped stdin - * 2.1 4 Apr 2010 - Avoid variable initialization for happier compilers - * - Avoid unsigned comparisons for even happier compilers - * 2.2 25 Apr 2010 - Fix bug in variable initializations [Oberhumer] - * - Add const where appropriate [Oberhumer] - * - Split if's and ?'s for coverage testing - * - Break out test code to separate file - * - Move NIL to puff.h - * - Allow incomplete code only if single code length is 1 - * - Add full code coverage test to Makefile - * 2.3 21 Jan 2013 - Check for invalid code length codes in dynamic blocks - */ - -#include /* for setjmp(), longjmp(), and jmp_buf */ -#include "puff.h" /* prototype for puff() */ - -#define local static /* for local function definitions */ - -/* - * Maximums for allocations and loops. It is not useful to change these -- - * they are fixed by the deflate format. - */ -#define MAXBITS 15 /* maximum bits in a code */ -#define MAXLCODES 286 /* maximum number of literal/length codes */ -#define MAXDCODES 30 /* maximum number of distance codes */ -#define MAXCODES (MAXLCODES+MAXDCODES) /* maximum codes lengths to read */ -#define FIXLCODES 288 /* number of fixed literal/length codes */ - -/* input and output state */ -struct state { - /* output state */ - unsigned char *out; /* output buffer */ - unsigned long outlen; /* available space at out */ - unsigned long outcnt; /* bytes written to out so far */ - - /* input state */ - const unsigned char *in; /* input buffer */ - unsigned long inlen; /* available input at in */ - unsigned long incnt; /* bytes read so far */ - int bitbuf; /* bit buffer */ - int bitcnt; /* number of bits in bit buffer */ - - /* input limit error return state for bits() and decode() */ - jmp_buf env; -}; - -/* - * Return need bits from the input stream. This always leaves less than - * eight bits in the buffer. bits() works properly for need == 0. - * - * Format notes: - * - * - Bits are stored in bytes from the least significant bit to the most - * significant bit. Therefore bits are dropped from the bottom of the bit - * buffer, using shift right, and new bytes are appended to the top of the - * bit buffer, using shift left. - */ -local int bits(struct state *s, int need) -{ - long val; /* bit accumulator (can use up to 20 bits) */ - - /* load at least need bits into val */ - val = s->bitbuf; - while (s->bitcnt < need) { - if (s->incnt == s->inlen) - longjmp(s->env, 1); /* out of input */ - val |= (long)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */ - s->bitcnt += 8; - } - - /* drop need bits and update buffer, always zero to seven bits left */ - s->bitbuf = (int)(val >> need); - s->bitcnt -= need; - - /* return need bits, zeroing the bits above that */ - return (int)(val & ((1L << need) - 1)); -} - -/* - * Process a stored block. - * - * Format notes: - * - * - After the two-bit stored block type (00), the stored block length and - * stored bytes are byte-aligned for fast copying. Therefore any leftover - * bits in the byte that has the last bit of the type, as many as seven, are - * discarded. The value of the discarded bits are not defined and should not - * be checked against any expectation. - * - * - The second inverted copy of the stored block length does not have to be - * checked, but it's probably a good idea to do so anyway. - * - * - A stored block can have zero length. This is sometimes used to byte-align - * subsets of the compressed data for random access or partial recovery. - */ -local int stored(struct state *s) -{ - unsigned len; /* length of stored block */ - - /* discard leftover bits from current byte (assumes s->bitcnt < 8) */ - s->bitbuf = 0; - s->bitcnt = 0; - - /* get length and check against its one's complement */ - if (s->incnt + 4 > s->inlen) - return 2; /* not enough input */ - len = s->in[s->incnt++]; - len |= s->in[s->incnt++] << 8; - if (s->in[s->incnt++] != (~len & 0xff) || - s->in[s->incnt++] != ((~len >> 8) & 0xff)) - return -2; /* didn't match complement! */ - - /* copy len bytes from in to out */ - if (s->incnt + len > s->inlen) - return 2; /* not enough input */ - if (s->out != NIL) { - if (s->outcnt + len > s->outlen) - return 1; /* not enough output space */ - while (len--) - s->out[s->outcnt++] = s->in[s->incnt++]; - } - else { /* just scanning */ - s->outcnt += len; - s->incnt += len; - } - - /* done with a valid stored block */ - return 0; -} - -/* - * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of - * each length, which for a canonical code are stepped through in order. - * symbol[] are the symbol values in canonical order, where the number of - * entries is the sum of the counts in count[]. The decoding process can be - * seen in the function decode() below. - */ -struct huffman { - short *count; /* number of symbols of each length */ - short *symbol; /* canonically ordered symbols */ -}; - -/* - * Decode a code from the stream s using huffman table h. Return the symbol or - * a negative value if there is an error. If all of the lengths are zero, i.e. - * an empty code, or if the code is incomplete and an invalid code is received, - * then -10 is returned after reading MAXBITS bits. - * - * Format notes: - * - * - The codes as stored in the compressed data are bit-reversed relative to - * a simple integer ordering of codes of the same lengths. Hence below the - * bits are pulled from the compressed data one at a time and used to - * build the code value reversed from what is in the stream in order to - * permit simple integer comparisons for decoding. A table-based decoding - * scheme (as used in zlib) does not need to do this reversal. - * - * - The first code for the shortest length is all zeros. Subsequent codes of - * the same length are simply integer increments of the previous code. When - * moving up a length, a zero bit is appended to the code. For a complete - * code, the last code of the longest length will be all ones. - * - * - Incomplete codes are handled by this decoder, since they are permitted - * in the deflate format. See the format notes for fixed() and dynamic(). - */ -#ifdef SLOW -local int decode(struct state *s, const struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - - code = first = index = 0; - for (len = 1; len <= MAXBITS; len++) { - code |= bits(s, 1); /* get next bit */ - count = h->count[len]; - if (code - count < first) /* if length len, return symbol */ - return h->symbol[index + (code - first)]; - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - } - return -10; /* ran out of codes */ -} - -/* - * A faster version of decode() for real applications of this code. It's not - * as readable, but it makes puff() twice as fast. And it only makes the code - * a few percent larger. - */ -#else /* !SLOW */ -local int decode(struct state *s, const struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - int bitbuf; /* bits from stream */ - int left; /* bits left in next or left to process */ - short *next; /* next number of codes */ - - bitbuf = s->bitbuf; - left = s->bitcnt; - code = first = index = 0; - len = 1; - next = h->count + 1; - while (1) { - while (left--) { - code |= bitbuf & 1; - bitbuf >>= 1; - count = *next++; - if (code - count < first) { /* if length len, return symbol */ - s->bitbuf = bitbuf; - s->bitcnt = (s->bitcnt - len) & 7; - return h->symbol[index + (code - first)]; - } - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - len++; - } - left = (MAXBITS+1) - len; - if (left == 0) - break; - if (s->incnt == s->inlen) - longjmp(s->env, 1); /* out of input */ - bitbuf = s->in[s->incnt++]; - if (left > 8) - left = 8; - } - return -10; /* ran out of codes */ -} -#endif /* SLOW */ - -/* - * Given the list of code lengths length[0..n-1] representing a canonical - * Huffman code for n symbols, construct the tables required to decode those - * codes. Those tables are the number of codes of each length, and the symbols - * sorted by length, retaining their original order within each length. The - * return value is zero for a complete code set, negative for an over- - * subscribed code set, and positive for an incomplete code set. The tables - * can be used if the return value is zero or positive, but they cannot be used - * if the return value is negative. If the return value is zero, it is not - * possible for decode() using that table to return an error--any stream of - * enough bits will resolve to a symbol. If the return value is positive, then - * it is possible for decode() using that table to return an error for received - * codes past the end of the incomplete lengths. - * - * Not used by decode(), but used for error checking, h->count[0] is the number - * of the n symbols not in the code. So n - h->count[0] is the number of - * codes. This is useful for checking for incomplete codes that have more than - * one symbol, which is an error in a dynamic block. - * - * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS - * This is assured by the construction of the length arrays in dynamic() and - * fixed() and is not verified by construct(). - * - * Format notes: - * - * - Permitted and expected examples of incomplete codes are one of the fixed - * codes and any code with a single symbol which in deflate is coded as one - * bit instead of zero bits. See the format notes for fixed() and dynamic(). - * - * - Within a given code length, the symbols are kept in ascending order for - * the code bits definition. - */ -local int construct(struct huffman *h, const short *length, int n) -{ - int symbol; /* current symbol when stepping through length[] */ - int len; /* current length when stepping through h->count[] */ - int left; /* number of possible codes left of current length */ - short offs[MAXBITS+1]; /* offsets in symbol table for each length */ - - /* count number of codes of each length */ - for (len = 0; len <= MAXBITS; len++) - h->count[len] = 0; - for (symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; /* assumes lengths are within bounds */ - if (h->count[0] == n) /* no codes! */ - return 0; /* complete, but decode() will fail */ - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; /* one possible code of zero length */ - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; /* one more bit, double codes left */ - left -= h->count[len]; /* deduct count from possible codes */ - if (left < 0) - return left; /* over-subscribed--return negative */ - } /* left > 0 means incomplete */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + h->count[len]; - - /* - * put symbols in table sorted by length, by symbol order within each - * length - */ - for (symbol = 0; symbol < n; symbol++) - if (length[symbol] != 0) - h->symbol[offs[length[symbol]]++] = symbol; - - /* return zero for complete set, positive for incomplete set */ - return left; -} - -/* - * Decode literal/length and distance codes until an end-of-block code. - * - * Format notes: - * - * - Compressed data that is after the block type if fixed or after the code - * description if dynamic is a combination of literals and length/distance - * pairs terminated by and end-of-block code. Literals are simply Huffman - * coded bytes. A length/distance pair is a coded length followed by a - * coded distance to represent a string that occurs earlier in the - * uncompressed data that occurs again at the current location. - * - * - Literals, lengths, and the end-of-block code are combined into a single - * code of up to 286 symbols. They are 256 literals (0..255), 29 length - * symbols (257..285), and the end-of-block symbol (256). - * - * - There are 256 possible lengths (3..258), and so 29 symbols are not enough - * to represent all of those. Lengths 3..10 and 258 are in fact represented - * by just a length symbol. Lengths 11..257 are represented as a symbol and - * some number of extra bits that are added as an integer to the base length - * of the length symbol. The number of extra bits is determined by the base - * length symbol. These are in the static arrays below, lens[] for the base - * lengths and lext[] for the corresponding number of extra bits. - * - * - The reason that 258 gets its own symbol is that the longest length is used - * often in highly redundant files. Note that 258 can also be coded as the - * base value 227 plus the maximum extra value of 31. While a good deflate - * should never do this, it is not an error, and should be decoded properly. - * - * - If a length is decoded, including its extra bits if any, then it is - * followed a distance code. There are up to 30 distance symbols. Again - * there are many more possible distances (1..32768), so extra bits are added - * to a base value represented by the symbol. The distances 1..4 get their - * own symbol, but the rest require extra bits. The base distances and - * corresponding number of extra bits are below in the static arrays dist[] - * and dext[]. - * - * - Literal bytes are simply written to the output. A length/distance pair is - * an instruction to copy previously uncompressed bytes to the output. The - * copy is from distance bytes back in the output stream, copying for length - * bytes. - * - * - Distances pointing before the beginning of the output data are not - * permitted. - * - * - Overlapped copies, where the length is greater than the distance, are - * allowed and common. For example, a distance of one and a length of 258 - * simply copies the last byte 258 times. A distance of four and a length of - * twelve copies the last four bytes three times. A simple forward copy - * ignoring whether the length is greater than the distance or not implements - * this correctly. You should not use memcpy() since its behavior is not - * defined for overlapped arrays. You should not use memmove() or bcopy() - * since though their behavior -is- defined for overlapping arrays, it is - * defined to do the wrong thing in this case. - */ -local int codes(struct state *s, - const struct huffman *lencode, - const struct huffman *distcode) -{ - int symbol; /* decoded symbol */ - int len; /* length for copy */ - unsigned dist; /* distance for copy */ - static const short lens[29] = { /* Size base for length codes 257..285 */ - 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}; - static const short lext[29] = { /* Extra bits for length codes 257..285 */ - 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}; - static const short dists[30] = { /* Offset base for distance codes 0..29 */ - 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}; - static const short dext[30] = { /* Extra bits for distance codes 0..29 */ - 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}; - - /* decode literals and length/distance pairs */ - do { - symbol = decode(s, lencode); - if (symbol < 0) - return symbol; /* invalid symbol */ - if (symbol < 256) { /* literal: symbol is the byte */ - /* write out the literal */ - if (s->out != NIL) { - if (s->outcnt == s->outlen) - return 1; - s->out[s->outcnt] = symbol; - } - s->outcnt++; - } - else if (symbol > 256) { /* length */ - /* get and compute length */ - symbol -= 257; - if (symbol >= 29) - return -10; /* invalid fixed code */ - len = lens[symbol] + bits(s, lext[symbol]); - - /* get and check distance */ - symbol = decode(s, distcode); - if (symbol < 0) - return symbol; /* invalid symbol */ - dist = dists[symbol] + bits(s, dext[symbol]); -#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - if (dist > s->outcnt) - return -11; /* distance too far back */ -#endif - - /* copy length bytes from distance bytes back */ - if (s->out != NIL) { - if (s->outcnt + len > s->outlen) - return 1; - while (len--) { - s->out[s->outcnt] = -#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - dist > s->outcnt ? - 0 : -#endif - s->out[s->outcnt - dist]; - s->outcnt++; - } - } - else - s->outcnt += len; - } - } while (symbol != 256); /* end of block symbol */ - - /* done with a valid fixed or dynamic block */ - return 0; -} - -/* - * Process a fixed codes block. - * - * Format notes: - * - * - This block type can be useful for compressing small amounts of data for - * which the size of the code descriptions in a dynamic block exceeds the - * benefit of custom codes for that block. For fixed codes, no bits are - * spent on code descriptions. Instead the code lengths for literal/length - * codes and distance codes are fixed. The specific lengths for each symbol - * can be seen in the "for" loops below. - * - * - The literal/length code is complete, but has two symbols that are invalid - * and should result in an error if received. This cannot be implemented - * simply as an incomplete code since those two symbols are in the "middle" - * of the code. They are eight bits long and the longest literal/length\ - * code is nine bits. Therefore the code must be constructed with those - * symbols, and the invalid symbols must be detected after decoding. - * - * - The fixed distance codes also have two invalid symbols that should result - * in an error if received. Since all of the distance codes are the same - * length, this can be implemented as an incomplete code. Then the invalid - * codes are detected while decoding. - */ -local int fixed(struct state *s) -{ - static int virgin = 1; - static short lencnt[MAXBITS+1], lensym[FIXLCODES]; - static short distcnt[MAXBITS+1], distsym[MAXDCODES]; - static struct huffman lencode, distcode; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - int symbol; - short lengths[FIXLCODES]; - - /* construct lencode and distcode */ - lencode.count = lencnt; - lencode.symbol = lensym; - distcode.count = distcnt; - distcode.symbol = distsym; - - /* literal/length table */ - for (symbol = 0; symbol < 144; symbol++) - lengths[symbol] = 8; - for (; symbol < 256; symbol++) - lengths[symbol] = 9; - for (; symbol < 280; symbol++) - lengths[symbol] = 7; - for (; symbol < FIXLCODES; symbol++) - lengths[symbol] = 8; - construct(&lencode, lengths, FIXLCODES); - - /* distance table */ - for (symbol = 0; symbol < MAXDCODES; symbol++) - lengths[symbol] = 5; - construct(&distcode, lengths, MAXDCODES); - - /* do this just once */ - virgin = 0; - } - - /* decode data until end-of-block code */ - return codes(s, &lencode, &distcode); -} - -/* - * Process a dynamic codes block. - * - * Format notes: - * - * - A dynamic block starts with a description of the literal/length and - * distance codes for that block. New dynamic blocks allow the compressor to - * rapidly adapt to changing data with new codes optimized for that data. - * - * - The codes used by the deflate format are "canonical", which means that - * the actual bits of the codes are generated in an unambiguous way simply - * from the number of bits in each code. Therefore the code descriptions - * are simply a list of code lengths for each symbol. - * - * - The code lengths are stored in order for the symbols, so lengths are - * provided for each of the literal/length symbols, and for each of the - * distance symbols. - * - * - If a symbol is not used in the block, this is represented by a zero as - * as the code length. This does not mean a zero-length code, but rather - * that no code should be created for this symbol. There is no way in the - * deflate format to represent a zero-length code. - * - * - The maximum number of bits in a code is 15, so the possible lengths for - * any code are 1..15. - * - * - The fact that a length of zero is not permitted for a code has an - * interesting consequence. Normally if only one symbol is used for a given - * code, then in fact that code could be represented with zero bits. However - * in deflate, that code has to be at least one bit. So for example, if - * only a single distance base symbol appears in a block, then it will be - * represented by a single code of length one, in particular one 0 bit. This - * is an incomplete code, since if a 1 bit is received, it has no meaning, - * and should result in an error. So incomplete distance codes of one symbol - * should be permitted, and the receipt of invalid codes should be handled. - * - * - It is also possible to have a single literal/length code, but that code - * must be the end-of-block code, since every dynamic block has one. This - * is not the most efficient way to create an empty block (an empty fixed - * block is fewer bits), but it is allowed by the format. So incomplete - * literal/length codes of one symbol should also be permitted. - * - * - If there are only literal codes and no lengths, then there are no distance - * codes. This is represented by one distance code with zero bits. - * - * - The list of up to 286 length/literal lengths and up to 30 distance lengths - * are themselves compressed using Huffman codes and run-length encoding. In - * the list of code lengths, a 0 symbol means no code, a 1..15 symbol means - * that length, and the symbols 16, 17, and 18 are run-length instructions. - * Each of 16, 17, and 18 are follwed by extra bits to define the length of - * the run. 16 copies the last length 3 to 6 times. 17 represents 3 to 10 - * zero lengths, and 18 represents 11 to 138 zero lengths. Unused symbols - * are common, hence the special coding for zero lengths. - * - * - The symbols for 0..18 are Huffman coded, and so that code must be - * described first. This is simply a sequence of up to 19 three-bit values - * representing no code (0) or the code length for that symbol (1..7). - * - * - A dynamic block starts with three fixed-size counts from which is computed - * the number of literal/length code lengths, the number of distance code - * lengths, and the number of code length code lengths (ok, you come up with - * a better name!) in the code descriptions. For the literal/length and - * distance codes, lengths after those provided are considered zero, i.e. no - * code. The code length code lengths are received in a permuted order (see - * the order[] array below) to make a short code length code length list more - * likely. As it turns out, very short and very long codes are less likely - * to be seen in a dynamic code description, hence what may appear initially - * to be a peculiar ordering. - * - * - Given the number of literal/length code lengths (nlen) and distance code - * lengths (ndist), then they are treated as one long list of nlen + ndist - * code lengths. Therefore run-length coding can and often does cross the - * boundary between the two sets of lengths. - * - * - So to summarize, the code description at the start of a dynamic block is - * three counts for the number of code lengths for the literal/length codes, - * the distance codes, and the code length codes. This is followed by the - * code length code lengths, three bits each. This is used to construct the - * code length code which is used to read the remainder of the lengths. Then - * the literal/length code lengths and distance lengths are read as a single - * set of lengths using the code length codes. Codes are constructed from - * the resulting two sets of lengths, and then finally you can start - * decoding actual compressed data in the block. - * - * - For reference, a "typical" size for the code description in a dynamic - * block is around 80 bytes. - */ -local int dynamic(struct state *s) -{ - int nlen, ndist, ncode; /* number of lengths in descriptor */ - int index; /* index of lengths[] */ - int err; /* construct() return value */ - short lengths[MAXCODES]; /* descriptor code lengths */ - short lencnt[MAXBITS+1], lensym[MAXLCODES]; /* lencode memory */ - short distcnt[MAXBITS+1], distsym[MAXDCODES]; /* distcode memory */ - struct huffman lencode, distcode; /* length and distance codes */ - static const short order[19] = /* permutation of code length codes */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* construct lencode and distcode */ - lencode.count = lencnt; - lencode.symbol = lensym; - distcode.count = distcnt; - distcode.symbol = distsym; - - /* get number of lengths in each table, check lengths */ - nlen = bits(s, 5) + 257; - ndist = bits(s, 5) + 1; - ncode = bits(s, 4) + 4; - if (nlen > MAXLCODES || ndist > MAXDCODES) - return -3; /* bad counts */ - - /* read code length code lengths (really), missing lengths are zero */ - for (index = 0; index < ncode; index++) - lengths[order[index]] = bits(s, 3); - for (; index < 19; index++) - lengths[order[index]] = 0; - - /* build huffman table for code lengths codes (use lencode temporarily) */ - err = construct(&lencode, lengths, 19); - if (err != 0) /* require complete code set here */ - return -4; - - /* read length/literal and distance code length tables */ - index = 0; - while (index < nlen + ndist) { - int symbol; /* decoded value */ - int len; /* last length to repeat */ - - symbol = decode(s, &lencode); - if (symbol < 0) - return symbol; /* invalid symbol */ - if (symbol < 16) /* length in 0..15 */ - lengths[index++] = symbol; - else { /* repeat instruction */ - len = 0; /* assume repeating zeros */ - if (symbol == 16) { /* repeat last length 3..6 times */ - if (index == 0) - return -5; /* no last length! */ - len = lengths[index - 1]; /* last length */ - symbol = 3 + bits(s, 2); - } - else if (symbol == 17) /* repeat zero 3..10 times */ - symbol = 3 + bits(s, 3); - else /* == 18, repeat zero 11..138 times */ - symbol = 11 + bits(s, 7); - if (index + symbol > nlen + ndist) - return -6; /* too many lengths! */ - while (symbol--) /* repeat last or zero symbol times */ - lengths[index++] = len; - } - } - - /* check for end-of-block code -- there better be one! */ - if (lengths[256] == 0) - return -9; - - /* build huffman table for literal/length codes */ - err = construct(&lencode, lengths, nlen); - if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) - return -7; /* incomplete code ok only for single length 1 code */ - - /* build huffman table for distance codes */ - err = construct(&distcode, lengths + nlen, ndist); - if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) - return -8; /* incomplete code ok only for single length 1 code */ - - /* decode data until end-of-block code */ - return codes(s, &lencode, &distcode); -} - -/* - * Inflate source to dest. On return, destlen and sourcelen are updated to the - * size of the uncompressed data and the size of the deflate data respectively. - * On success, the return value of puff() is zero. If there is an error in the - * source data, i.e. it is not in the deflate format, then a negative value is - * returned. If there is not enough input available or there is not enough - * output space, then a positive error is returned. In that case, destlen and - * sourcelen are not updated to facilitate retrying from the beginning with the - * provision of more input data or more output space. In the case of invalid - * inflate data (a negative error), the dest and source pointers are updated to - * facilitate the debugging of deflators. - * - * puff() also has a mode to determine the size of the uncompressed output with - * no output written. For this dest must be (unsigned char *)0. In this case, - * the input value of *destlen is ignored, and on return *destlen is set to the - * size of the uncompressed output. - * - * The return codes are: - * - * 2: available inflate data did not terminate - * 1: output space exhausted before completing inflate - * 0: successful inflate - * -1: invalid block type (type == 3) - * -2: stored block length did not match one's complement - * -3: dynamic block code description: too many length or distance codes - * -4: dynamic block code description: code lengths codes incomplete - * -5: dynamic block code description: repeat lengths with no first length - * -6: dynamic block code description: repeat more than specified lengths - * -7: dynamic block code description: invalid literal/length code lengths - * -8: dynamic block code description: invalid distance code lengths - * -9: dynamic block code description: missing end-of-block code - * -10: invalid literal/length or distance code in fixed or dynamic block - * -11: distance is too far back in fixed or dynamic block - * - * Format notes: - * - * - Three bits are read for each block to determine the kind of block and - * whether or not it is the last block. Then the block is decoded and the - * process repeated if it was not the last block. - * - * - The leftover bits in the last byte of the deflate data after the last - * block (if it was a fixed or dynamic block) are undefined and have no - * expected values to check. - */ -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - const unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen) /* amount of input available */ -{ - struct state s; /* input/output state */ - int last, type; /* block information */ - int err; /* return value */ - - /* initialize output state */ - s.out = dest; - s.outlen = *destlen; /* ignored if dest is NIL */ - s.outcnt = 0; - - /* initialize input state */ - s.in = source; - s.inlen = *sourcelen; - s.incnt = 0; - s.bitbuf = 0; - s.bitcnt = 0; - - /* return if bits() or decode() tries to read past available input */ - if (setjmp(s.env) != 0) /* if came back here via longjmp() */ - err = 2; /* then skip do-loop, return error */ - else { - /* process blocks until last block or error */ - do { - last = bits(&s, 1); /* one if last block */ - type = bits(&s, 2); /* block type 0..3 */ - err = type == 0 ? - stored(&s) : - (type == 1 ? - fixed(&s) : - (type == 2 ? - dynamic(&s) : - -1)); /* type == 3, invalid */ - if (err != 0) - break; /* return with error */ - } while (!last); - } - - /* update the lengths and return */ - if (err <= 0) { - *destlen = s.outcnt; - *sourcelen = s.incnt; - } - return err; -} diff --git a/deps/zlib/contrib/puff/puff.h b/deps/zlib/contrib/puff/puff.h deleted file mode 100644 index e23a2454316cfa..00000000000000 --- a/deps/zlib/contrib/puff/puff.h +++ /dev/null @@ -1,35 +0,0 @@ -/* puff.h - Copyright (C) 2002-2013 Mark Adler, all rights reserved - version 2.3, 21 Jan 2013 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - - -/* - * See puff.c for purpose and usage. - */ -#ifndef NIL -# define NIL ((unsigned char *)0) /* for no output option */ -#endif - -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - const unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen); /* amount of input available */ diff --git a/deps/zlib/contrib/puff/pufftest.c b/deps/zlib/contrib/puff/pufftest.c deleted file mode 100644 index 776481488c90d0..00000000000000 --- a/deps/zlib/contrib/puff/pufftest.c +++ /dev/null @@ -1,165 +0,0 @@ -/* - * pufftest.c - * Copyright (C) 2002-2013 Mark Adler - * For conditions of distribution and use, see copyright notice in puff.h - * version 2.3, 21 Jan 2013 - */ - -/* Example of how to use puff(). - - Usage: puff [-w] [-f] [-nnn] file - ... | puff [-w] [-f] [-nnn] - - where file is the input file with deflate data, nnn is the number of bytes - of input to skip before inflating (e.g. to skip a zlib or gzip header), and - -w is used to write the decompressed data to stdout. -f is for coverage - testing, and causes pufftest to fail with not enough output space (-f does - a write like -w, so -w is not required). */ - -#include -#include -#include "puff.h" - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#define local static - -/* Return size times approximately the cube root of 2, keeping the result as 1, - 3, or 5 times a power of 2 -- the result is always > size, until the result - is the maximum value of an unsigned long, where it remains. This is useful - to keep reallocations less than ~33% over the actual data. */ -local size_t bythirds(size_t size) -{ - int n; - size_t m; - - m = size; - for (n = 0; m; n++) - m >>= 1; - if (n < 3) - return size + 1; - n -= 3; - m = size >> n; - m += m == 6 ? 2 : 1; - m <<= n; - return m > size ? m : (size_t)(-1); -} - -/* Read the input file *name, or stdin if name is NULL, into allocated memory. - Reallocate to larger buffers until the entire file is read in. Return a - pointer to the allocated data, or NULL if there was a memory allocation - failure. *len is the number of bytes of data read from the input file (even - if load() returns NULL). If the input file was empty or could not be opened - or read, *len is zero. */ -local void *load(const char *name, size_t *len) -{ - size_t size; - void *buf, *swap; - FILE *in; - - *len = 0; - buf = malloc(size = 4096); - if (buf == NULL) - return NULL; - in = name == NULL ? stdin : fopen(name, "rb"); - if (in != NULL) { - for (;;) { - *len += fread((char *)buf + *len, 1, size - *len, in); - if (*len < size) break; - size = bythirds(size); - if (size == *len || (swap = realloc(buf, size)) == NULL) { - free(buf); - buf = NULL; - break; - } - buf = swap; - } - fclose(in); - } - return buf; -} - -int main(int argc, char **argv) -{ - int ret, put = 0, fail = 0; - unsigned skip = 0; - char *arg, *name = NULL; - unsigned char *source = NULL, *dest; - size_t len = 0; - unsigned long sourcelen, destlen; - - /* process arguments */ - while (arg = *++argv, --argc) - if (arg[0] == '-') { - if (arg[1] == 'w' && arg[2] == 0) - put = 1; - else if (arg[1] == 'f' && arg[2] == 0) - fail = 1, put = 1; - else if (arg[1] >= '0' && arg[1] <= '9') - skip = (unsigned)atoi(arg + 1); - else { - fprintf(stderr, "invalid option %s\n", arg); - return 3; - } - } - else if (name != NULL) { - fprintf(stderr, "only one file name allowed\n"); - return 3; - } - else - name = arg; - source = load(name, &len); - if (source == NULL) { - fprintf(stderr, "memory allocation failure\n"); - return 4; - } - if (len == 0) { - fprintf(stderr, "could not read %s, or it was empty\n", - name == NULL ? "" : name); - free(source); - return 3; - } - if (skip >= len) { - fprintf(stderr, "skip request of %d leaves no input\n", skip); - free(source); - return 3; - } - - /* test inflate data with offset skip */ - len -= skip; - sourcelen = (unsigned long)len; - ret = puff(NIL, &destlen, source + skip, &sourcelen); - if (ret) - fprintf(stderr, "puff() failed with return code %d\n", ret); - else { - fprintf(stderr, "puff() succeeded uncompressing %lu bytes\n", destlen); - if (sourcelen < len) fprintf(stderr, "%lu compressed bytes unused\n", - len - sourcelen); - } - - /* if requested, inflate again and write decompressd data to stdout */ - if (put && ret == 0) { - if (fail) - destlen >>= 1; - dest = malloc(destlen); - if (dest == NULL) { - fprintf(stderr, "memory allocation failure\n"); - free(source); - return 4; - } - puff(dest, &destlen, source + skip, &sourcelen); - SET_BINARY_MODE(stdout); - fwrite(dest, 1, destlen, stdout); - free(dest); - } - - /* clean up */ - free(source); - return ret; -} diff --git a/deps/zlib/contrib/puff/zeros.raw b/deps/zlib/contrib/puff/zeros.raw deleted file mode 100644 index 0a90e76b300205..00000000000000 Binary files a/deps/zlib/contrib/puff/zeros.raw and /dev/null differ diff --git a/deps/zlib/contrib/tests/OWNERS b/deps/zlib/contrib/tests/OWNERS new file mode 100644 index 00000000000000..9a2fb6fbdc6b3f --- /dev/null +++ b/deps/zlib/contrib/tests/OWNERS @@ -0,0 +1 @@ +cblume@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/BUILD.gn b/deps/zlib/contrib/tests/fuzzers/BUILD.gn new file mode 100644 index 00000000000000..c46b66440073a5 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//testing/libfuzzer/fuzzer_test.gni") + +# root BUILD depends on this target. Needed for package discovery +group("fuzzers") { +} + +fuzzer_test("zlib_uncompress_fuzzer") { + sources = [ + "uncompress_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_inflate_fuzzer") { + sources = [ + "inflate_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_deflate_set_dictionary_fuzzer") { + sources = [ + "deflate_set_dictionary_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_deflate_fuzzer") { + sources = [ + "deflate_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} diff --git a/deps/zlib/contrib/tests/fuzzers/OWNERS b/deps/zlib/contrib/tests/fuzzers/OWNERS new file mode 100644 index 00000000000000..6397ce69c70649 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/OWNERS @@ -0,0 +1,2 @@ +cblume@chromium.org +mmoroz@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc new file mode 100644 index 00000000000000..6098ff162ce1c0 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc @@ -0,0 +1,47 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // zlib's deflate requires non-zero input sizes + if (!size) + return 0; + + // We need to strip the 'const' for zlib. + std::vector input_buffer{data, data+size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { + deflateEnd(&stream); + assert(false); + } + + auto deflate_result = deflate(&stream, Z_NO_FLUSH); + deflateEnd(&stream); + if (Z_OK != deflate_result) + assert(false); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc new file mode 100644 index 00000000000000..febbfcb86f0c3e --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc @@ -0,0 +1,43 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // We need to strip the 'const' for zlib. + std::vector input_buffer{data, data + size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { + deflateEnd(&stream); + assert(false); + } + + auto deflate_set_dictionary_result = + deflateSetDictionary(&stream, data, size); + deflateEnd(&stream); + if (Z_OK != deflate_set_dictionary_result) + assert(false); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc new file mode 100644 index 00000000000000..44f9c72c18df8a --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc @@ -0,0 +1,41 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // We need to strip the 'const' for zlib + std::vector input_buffer{data, data+size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != inflateInit(&stream)) { + inflateEnd(&stream); + assert(false); + } + + inflate(&stream, Z_NO_FLUSH); + inflateEnd(&stream); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc new file mode 100644 index 00000000000000..bca5244e8b38b4 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc @@ -0,0 +1,21 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + uLongf buffer_length = static_cast(sizeof(buffer)); + if (Z_OK != + uncompress(buffer, &buffer_length, data, static_cast(size))) { + return 0; + } + return 0; +} diff --git a/deps/zlib/contrib/testzlib/testzlib.c b/deps/zlib/contrib/testzlib/testzlib.c deleted file mode 100644 index 8626c92ad17566..00000000000000 --- a/deps/zlib/contrib/testzlib/testzlib.c +++ /dev/null @@ -1,275 +0,0 @@ -#include -#include -#include - -#include "zlib.h" - - -void MyDoMinus64(LARGE_INTEGER *R,LARGE_INTEGER A,LARGE_INTEGER B) -{ - R->HighPart = A.HighPart - B.HighPart; - if (A.LowPart >= B.LowPart) - R->LowPart = A.LowPart - B.LowPart; - else - { - R->LowPart = A.LowPart - B.LowPart; - R->HighPart --; - } -} - -#ifdef _M_X64 -// see http://msdn2.microsoft.com/library/twchhe95(en-us,vs.80).aspx for __rdtsc -unsigned __int64 __rdtsc(void); -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ - // printf("rdtsc = %I64x\n",__rdtsc()); - pbeginTime64->QuadPart=__rdtsc(); -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER LIres; - unsigned _int64 res=__rdtsc()-((unsigned _int64)(beginTime64.QuadPart)); - LIres.QuadPart=res; - // printf("rdtsc = %I64x\n",__rdtsc()); - return LIres; -} -#else -#ifdef _M_IX86 -void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) -{ - DWORD dwEdx,dwEax; - _asm - { - rdtsc - mov dwEax,eax - mov dwEdx,edx - } - pbeginTime64->LowPart=dwEax; - pbeginTime64->HighPart=dwEdx; -} - -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ - myGetRDTSC32(pbeginTime64); -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER LIres,endTime64; - myGetRDTSC32(&endTime64); - - LIres.LowPart=LIres.HighPart=0; - MyDoMinus64(&LIres,endTime64,beginTime64); - return LIres; -} -#else -void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) -{ -} - -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER lr; - lr.QuadPart=0; - return lr; -} -#endif -#endif - -void BeginCountPerfCounter(LARGE_INTEGER * pbeginTime64,BOOL fComputeTimeQueryPerf) -{ - if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(pbeginTime64))) - { - pbeginTime64->LowPart = GetTickCount(); - pbeginTime64->HighPart = 0; - } -} - -DWORD GetMsecSincePerfCounter(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER endTime64,ticksPerSecond,ticks; - DWORDLONG ticksShifted,tickSecShifted; - DWORD dwLog=16+0; - DWORD dwRet; - if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(&endTime64))) - dwRet = (GetTickCount() - beginTime64.LowPart)*1; - else - { - MyDoMinus64(&ticks,endTime64,beginTime64); - QueryPerformanceFrequency(&ticksPerSecond); - - - { - ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog); - tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog); - - } - - dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted)); - dwRet *=1; - } - return dwRet; -} - -int ReadFileMemory(const char* filename,long* plFileSize,unsigned char** pFilePtr) -{ - FILE* stream; - unsigned char* ptr; - int retVal=1; - stream=fopen(filename, "rb"); - if (stream==NULL) - return 0; - - fseek(stream,0,SEEK_END); - - *plFileSize=ftell(stream); - fseek(stream,0,SEEK_SET); - ptr=malloc((*plFileSize)+1); - if (ptr==NULL) - retVal=0; - else - { - if (fread(ptr, 1, *plFileSize,stream) != (*plFileSize)) - retVal=0; - } - fclose(stream); - *pFilePtr=ptr; - return retVal; -} - -int main(int argc, char *argv[]) -{ - int BlockSizeCompress=0x8000; - int BlockSizeUncompress=0x8000; - int cprLevel=Z_DEFAULT_COMPRESSION ; - long lFileSize; - unsigned char* FilePtr; - long lBufferSizeCpr; - long lBufferSizeUncpr; - long lCompressedSize=0; - unsigned char* CprPtr; - unsigned char* UncprPtr; - long lSizeCpr,lSizeUncpr; - DWORD dwGetTick,dwMsecQP; - LARGE_INTEGER li_qp,li_rdtsc,dwResRdtsc; - - if (argc<=1) - { - printf("run TestZlib [BlockSizeCompress] [BlockSizeUncompress] [compres. level]\n"); - return 0; - } - - if (ReadFileMemory(argv[1],&lFileSize,&FilePtr)==0) - { - printf("error reading %s\n",argv[1]); - return 1; - } - else printf("file %s read, %u bytes\n",argv[1],lFileSize); - - if (argc>=3) - BlockSizeCompress=atol(argv[2]); - - if (argc>=4) - BlockSizeUncompress=atol(argv[3]); - - if (argc>=5) - cprLevel=(int)atol(argv[4]); - - lBufferSizeCpr = lFileSize + (lFileSize/0x10) + 0x200; - lBufferSizeUncpr = lBufferSizeCpr; - - CprPtr=(unsigned char*)malloc(lBufferSizeCpr + BlockSizeCompress); - - BeginCountPerfCounter(&li_qp,TRUE); - dwGetTick=GetTickCount(); - BeginCountRdtsc(&li_rdtsc); - { - z_stream zcpr; - int ret=Z_OK; - long lOrigToDo = lFileSize; - long lOrigDone = 0; - int step=0; - memset(&zcpr,0,sizeof(z_stream)); - deflateInit(&zcpr,cprLevel); - - zcpr.next_in = FilePtr; - zcpr.next_out = CprPtr; - - - do - { - long all_read_before = zcpr.total_in; - zcpr.avail_in = min(lOrigToDo,BlockSizeCompress); - zcpr.avail_out = BlockSizeCompress; - ret=deflate(&zcpr,(zcpr.avail_in==lOrigToDo) ? Z_FINISH : Z_SYNC_FLUSH); - lOrigDone += (zcpr.total_in-all_read_before); - lOrigToDo -= (zcpr.total_in-all_read_before); - step++; - } while (ret==Z_OK); - - lSizeCpr=zcpr.total_out; - deflateEnd(&zcpr); - dwGetTick=GetTickCount()-dwGetTick; - dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); - dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); - printf("total compress size = %u, in %u step\n",lSizeCpr,step); - printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); - printf("defcpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); - printf("defcpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); - } - - CprPtr=(unsigned char*)realloc(CprPtr,lSizeCpr); - UncprPtr=(unsigned char*)malloc(lBufferSizeUncpr + BlockSizeUncompress); - - BeginCountPerfCounter(&li_qp,TRUE); - dwGetTick=GetTickCount(); - BeginCountRdtsc(&li_rdtsc); - { - z_stream zcpr; - int ret=Z_OK; - long lOrigToDo = lSizeCpr; - long lOrigDone = 0; - int step=0; - memset(&zcpr,0,sizeof(z_stream)); - inflateInit(&zcpr); - - zcpr.next_in = CprPtr; - zcpr.next_out = UncprPtr; - - - do - { - long all_read_before = zcpr.total_in; - zcpr.avail_in = min(lOrigToDo,BlockSizeUncompress); - zcpr.avail_out = BlockSizeUncompress; - ret=inflate(&zcpr,Z_SYNC_FLUSH); - lOrigDone += (zcpr.total_in-all_read_before); - lOrigToDo -= (zcpr.total_in-all_read_before); - step++; - } while (ret==Z_OK); - - lSizeUncpr=zcpr.total_out; - inflateEnd(&zcpr); - dwGetTick=GetTickCount()-dwGetTick; - dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); - dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); - printf("total uncompress size = %u, in %u step\n",lSizeUncpr,step); - printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); - printf("uncpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); - printf("uncpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); - } - - if (lSizeUncpr==lFileSize) - { - if (memcmp(FilePtr,UncprPtr,lFileSize)==0) - printf("compare ok\n"); - - } - - return 0; -} diff --git a/deps/zlib/contrib/testzlib/testzlib.txt b/deps/zlib/contrib/testzlib/testzlib.txt deleted file mode 100644 index e508bb22ff4aef..00000000000000 --- a/deps/zlib/contrib/testzlib/testzlib.txt +++ /dev/null @@ -1,10 +0,0 @@ -To build testzLib with Visual Studio 2005: - -copy to a directory file from : -- root of zLib tree -- contrib/testzlib -- contrib/masmx86 -- contrib/masmx64 -- contrib/vstudio/vc7 - -and open testzlib8.sln \ No newline at end of file diff --git a/deps/zlib/contrib/untgz/Makefile b/deps/zlib/contrib/untgz/Makefile deleted file mode 100644 index b54266fba20a16..00000000000000 --- a/deps/zlib/contrib/untgz/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -CC=cc -CFLAGS=-g - -untgz: untgz.o ../../libz.a - $(CC) $(CFLAGS) -o untgz untgz.o -L../.. -lz - -untgz.o: untgz.c ../../zlib.h - $(CC) $(CFLAGS) -c -I../.. untgz.c - -../../libz.a: - cd ../..; ./configure; make - -clean: - rm -f untgz untgz.o *~ diff --git a/deps/zlib/contrib/untgz/Makefile.msc b/deps/zlib/contrib/untgz/Makefile.msc deleted file mode 100644 index 77b86022137da7..00000000000000 --- a/deps/zlib/contrib/untgz/Makefile.msc +++ /dev/null @@ -1,17 +0,0 @@ -CC=cl -CFLAGS=-MD - -untgz.exe: untgz.obj ..\..\zlib.lib - $(CC) $(CFLAGS) untgz.obj ..\..\zlib.lib - -untgz.obj: untgz.c ..\..\zlib.h - $(CC) $(CFLAGS) -c -I..\.. untgz.c - -..\..\zlib.lib: - cd ..\.. - $(MAKE) -f win32\makefile.msc - cd contrib\untgz - -clean: - -del untgz.obj - -del untgz.exe diff --git a/deps/zlib/contrib/untgz/untgz.c b/deps/zlib/contrib/untgz/untgz.c deleted file mode 100644 index 2c391e5986753d..00000000000000 --- a/deps/zlib/contrib/untgz/untgz.c +++ /dev/null @@ -1,674 +0,0 @@ -/* - * untgz.c -- Display contents and extract files from a gzip'd TAR file - * - * written by Pedro A. Aranda Gutierrez - * adaptation to Unix by Jean-loup Gailly - * various fixes by Cosmin Truta - */ - -#include -#include -#include -#include -#include - -#include "zlib.h" - -#ifdef unix -# include -#else -# include -# include -#endif - -#ifdef WIN32 -#include -# ifndef F_OK -# define F_OK 0 -# endif -# define mkdir(dirname,mode) _mkdir(dirname) -# ifdef _MSC_VER -# define access(path,mode) _access(path,mode) -# define chmod(path,mode) _chmod(path,mode) -# define strdup(str) _strdup(str) -# endif -#else -# include -#endif - - -/* values used in typeflag field */ - -#define REGTYPE '0' /* regular file */ -#define AREGTYPE '\0' /* regular file */ -#define LNKTYPE '1' /* link */ -#define SYMTYPE '2' /* reserved */ -#define CHRTYPE '3' /* character special */ -#define BLKTYPE '4' /* block special */ -#define DIRTYPE '5' /* directory */ -#define FIFOTYPE '6' /* FIFO special */ -#define CONTTYPE '7' /* reserved */ - -/* GNU tar extensions */ - -#define GNUTYPE_DUMPDIR 'D' /* file names from dumped directory */ -#define GNUTYPE_LONGLINK 'K' /* long link name */ -#define GNUTYPE_LONGNAME 'L' /* long file name */ -#define GNUTYPE_MULTIVOL 'M' /* continuation of file from another volume */ -#define GNUTYPE_NAMES 'N' /* file name that does not fit into main hdr */ -#define GNUTYPE_SPARSE 'S' /* sparse file */ -#define GNUTYPE_VOLHDR 'V' /* tape/volume header */ - - -/* tar header */ - -#define BLOCKSIZE 512 -#define SHORTNAMESIZE 100 - -struct tar_header -{ /* byte offset */ - char name[100]; /* 0 */ - char mode[8]; /* 100 */ - char uid[8]; /* 108 */ - char gid[8]; /* 116 */ - char size[12]; /* 124 */ - char mtime[12]; /* 136 */ - char chksum[8]; /* 148 */ - char typeflag; /* 156 */ - char linkname[100]; /* 157 */ - char magic[6]; /* 257 */ - char version[2]; /* 263 */ - char uname[32]; /* 265 */ - char gname[32]; /* 297 */ - char devmajor[8]; /* 329 */ - char devminor[8]; /* 337 */ - char prefix[155]; /* 345 */ - /* 500 */ -}; - -union tar_buffer -{ - char buffer[BLOCKSIZE]; - struct tar_header header; -}; - -struct attr_item -{ - struct attr_item *next; - char *fname; - int mode; - time_t time; -}; - -enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID }; - -char *TGZfname OF((const char *)); -void TGZnotfound OF((const char *)); - -int getoct OF((char *, int)); -char *strtime OF((time_t *)); -int setfiletime OF((char *, time_t)); -void push_attr OF((struct attr_item **, char *, int, time_t)); -void restore_attr OF((struct attr_item **)); - -int ExprMatch OF((char *, char *)); - -int makedir OF((char *)); -int matchname OF((int, int, char **, char *)); - -void error OF((const char *)); -int tar OF((gzFile, int, int, int, char **)); - -void help OF((int)); -int main OF((int, char **)); - -char *prog; - -const char *TGZsuffix[] = { "\0", ".tar", ".tar.gz", ".taz", ".tgz", NULL }; - -/* return the file name of the TGZ archive */ -/* or NULL if it does not exist */ - -char *TGZfname (const char *arcname) -{ - static char buffer[1024]; - int origlen,i; - - strcpy(buffer,arcname); - origlen = strlen(buffer); - - for (i=0; TGZsuffix[i]; i++) - { - strcpy(buffer+origlen,TGZsuffix[i]); - if (access(buffer,F_OK) == 0) - return buffer; - } - return NULL; -} - - -/* error message for the filename */ - -void TGZnotfound (const char *arcname) -{ - int i; - - fprintf(stderr,"%s: Couldn't find ",prog); - for (i=0;TGZsuffix[i];i++) - fprintf(stderr,(TGZsuffix[i+1]) ? "%s%s, " : "or %s%s\n", - arcname, - TGZsuffix[i]); - exit(1); -} - - -/* convert octal digits to int */ -/* on error return -1 */ - -int getoct (char *p,int width) -{ - int result = 0; - char c; - - while (width--) - { - c = *p++; - if (c == 0) - break; - if (c == ' ') - continue; - if (c < '0' || c > '7') - return -1; - result = result * 8 + (c - '0'); - } - return result; -} - - -/* convert time_t to string */ -/* use the "YYYY/MM/DD hh:mm:ss" format */ - -char *strtime (time_t *t) -{ - struct tm *local; - static char result[32]; - - local = localtime(t); - sprintf(result,"%4d/%02d/%02d %02d:%02d:%02d", - local->tm_year+1900, local->tm_mon+1, local->tm_mday, - local->tm_hour, local->tm_min, local->tm_sec); - return result; -} - - -/* set file time */ - -int setfiletime (char *fname,time_t ftime) -{ -#ifdef WIN32 - static int isWinNT = -1; - SYSTEMTIME st; - FILETIME locft, modft; - struct tm *loctm; - HANDLE hFile; - int result; - - loctm = localtime(&ftime); - if (loctm == NULL) - return -1; - - st.wYear = (WORD)loctm->tm_year + 1900; - st.wMonth = (WORD)loctm->tm_mon + 1; - st.wDayOfWeek = (WORD)loctm->tm_wday; - st.wDay = (WORD)loctm->tm_mday; - st.wHour = (WORD)loctm->tm_hour; - st.wMinute = (WORD)loctm->tm_min; - st.wSecond = (WORD)loctm->tm_sec; - st.wMilliseconds = 0; - if (!SystemTimeToFileTime(&st, &locft) || - !LocalFileTimeToFileTime(&locft, &modft)) - return -1; - - if (isWinNT < 0) - isWinNT = (GetVersion() < 0x80000000) ? 1 : 0; - hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, - (isWinNT ? FILE_FLAG_BACKUP_SEMANTICS : 0), - NULL); - if (hFile == INVALID_HANDLE_VALUE) - return -1; - result = SetFileTime(hFile, NULL, NULL, &modft) ? 0 : -1; - CloseHandle(hFile); - return result; -#else - struct utimbuf settime; - - settime.actime = settime.modtime = ftime; - return utime(fname,&settime); -#endif -} - - -/* push file attributes */ - -void push_attr(struct attr_item **list,char *fname,int mode,time_t time) -{ - struct attr_item *item; - - item = (struct attr_item *)malloc(sizeof(struct attr_item)); - if (item == NULL) - error("Out of memory"); - item->fname = strdup(fname); - item->mode = mode; - item->time = time; - item->next = *list; - *list = item; -} - - -/* restore file attributes */ - -void restore_attr(struct attr_item **list) -{ - struct attr_item *item, *prev; - - for (item = *list; item != NULL; ) - { - setfiletime(item->fname,item->time); - chmod(item->fname,item->mode); - prev = item; - item = item->next; - free(prev); - } - *list = NULL; -} - - -/* match regular expression */ - -#define ISSPECIAL(c) (((c) == '*') || ((c) == '/')) - -int ExprMatch (char *string,char *expr) -{ - while (1) - { - if (ISSPECIAL(*expr)) - { - if (*expr == '/') - { - if (*string != '\\' && *string != '/') - return 0; - string ++; expr++; - } - else if (*expr == '*') - { - if (*expr ++ == 0) - return 1; - while (*++string != *expr) - if (*string == 0) - return 0; - } - } - else - { - if (*string != *expr) - return 0; - if (*expr++ == 0) - return 1; - string++; - } - } -} - - -/* recursive mkdir */ -/* abort on ENOENT; ignore other errors like "directory already exists" */ -/* return 1 if OK */ -/* 0 on error */ - -int makedir (char *newdir) -{ - char *buffer = strdup(newdir); - char *p; - int len = strlen(buffer); - - if (len <= 0) { - free(buffer); - return 0; - } - if (buffer[len-1] == '/') { - buffer[len-1] = '\0'; - } - if (mkdir(buffer, 0755) == 0) - { - free(buffer); - return 1; - } - - p = buffer+1; - while (1) - { - char hold; - - while(*p && *p != '\\' && *p != '/') - p++; - hold = *p; - *p = 0; - if ((mkdir(buffer, 0755) == -1) && (errno == ENOENT)) - { - fprintf(stderr,"%s: Couldn't create directory %s\n",prog,buffer); - free(buffer); - return 0; - } - if (hold == 0) - break; - *p++ = hold; - } - free(buffer); - return 1; -} - - -int matchname (int arg,int argc,char **argv,char *fname) -{ - if (arg == argc) /* no arguments given (untgz tgzarchive) */ - return 1; - - while (arg < argc) - if (ExprMatch(fname,argv[arg++])) - return 1; - - return 0; /* ignore this for the moment being */ -} - - -/* tar file list or extract */ - -int tar (gzFile in,int action,int arg,int argc,char **argv) -{ - union tar_buffer buffer; - int len; - int err; - int getheader = 1; - int remaining = 0; - FILE *outfile = NULL; - char fname[BLOCKSIZE]; - int tarmode; - time_t tartime; - struct attr_item *attributes = NULL; - - if (action == TGZ_LIST) - printf(" date time size file\n" - " ---------- -------- --------- -------------------------------------\n"); - while (1) - { - len = gzread(in, &buffer, BLOCKSIZE); - if (len < 0) - error(gzerror(in, &err)); - /* - * Always expect complete blocks to process - * the tar information. - */ - if (len != BLOCKSIZE) - { - action = TGZ_INVALID; /* force error exit */ - remaining = 0; /* force I/O cleanup */ - } - - /* - * If we have to get a tar header - */ - if (getheader >= 1) - { - /* - * if we met the end of the tar - * or the end-of-tar block, - * we are done - */ - if (len == 0 || buffer.header.name[0] == 0) - break; - - tarmode = getoct(buffer.header.mode,8); - tartime = (time_t)getoct(buffer.header.mtime,12); - if (tarmode == -1 || tartime == (time_t)-1) - { - buffer.header.name[0] = 0; - action = TGZ_INVALID; - } - - if (getheader == 1) - { - strncpy(fname,buffer.header.name,SHORTNAMESIZE); - if (fname[SHORTNAMESIZE-1] != 0) - fname[SHORTNAMESIZE] = 0; - } - else - { - /* - * The file name is longer than SHORTNAMESIZE - */ - if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0) - error("bad long name"); - getheader = 1; - } - - /* - * Act according to the type flag - */ - switch (buffer.header.typeflag) - { - case DIRTYPE: - if (action == TGZ_LIST) - printf(" %s %s\n",strtime(&tartime),fname); - if (action == TGZ_EXTRACT) - { - makedir(fname); - push_attr(&attributes,fname,tarmode,tartime); - } - break; - case REGTYPE: - case AREGTYPE: - remaining = getoct(buffer.header.size,12); - if (remaining == -1) - { - action = TGZ_INVALID; - break; - } - if (action == TGZ_LIST) - printf(" %s %9d %s\n",strtime(&tartime),remaining,fname); - else if (action == TGZ_EXTRACT) - { - if (matchname(arg,argc,argv,fname)) - { - outfile = fopen(fname,"wb"); - if (outfile == NULL) { - /* try creating directory */ - char *p = strrchr(fname, '/'); - if (p != NULL) { - *p = '\0'; - makedir(fname); - *p = '/'; - outfile = fopen(fname,"wb"); - } - } - if (outfile != NULL) - printf("Extracting %s\n",fname); - else - fprintf(stderr, "%s: Couldn't create %s",prog,fname); - } - else - outfile = NULL; - } - getheader = 0; - break; - case GNUTYPE_LONGLINK: - case GNUTYPE_LONGNAME: - remaining = getoct(buffer.header.size,12); - if (remaining < 0 || remaining >= BLOCKSIZE) - { - action = TGZ_INVALID; - break; - } - len = gzread(in, fname, BLOCKSIZE); - if (len < 0) - error(gzerror(in, &err)); - if (fname[BLOCKSIZE-1] != 0 || (int)strlen(fname) > remaining) - { - action = TGZ_INVALID; - break; - } - getheader = 2; - break; - default: - if (action == TGZ_LIST) - printf(" %s <---> %s\n",strtime(&tartime),fname); - break; - } - } - else - { - unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining; - - if (outfile != NULL) - { - if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) - { - fprintf(stderr, - "%s: Error writing %s -- skipping\n",prog,fname); - fclose(outfile); - outfile = NULL; - remove(fname); - } - } - remaining -= bytes; - } - - if (remaining == 0) - { - getheader = 1; - if (outfile != NULL) - { - fclose(outfile); - outfile = NULL; - if (action != TGZ_INVALID) - push_attr(&attributes,fname,tarmode,tartime); - } - } - - /* - * Abandon if errors are found - */ - if (action == TGZ_INVALID) - { - error("broken archive"); - break; - } - } - - /* - * Restore file modes and time stamps - */ - restore_attr(&attributes); - - if (gzclose(in) != Z_OK) - error("failed gzclose"); - - return 0; -} - - -/* ============================================================ */ - -void help(int exitval) -{ - printf("untgz version 0.2.1\n" - " using zlib version %s\n\n", - zlibVersion()); - printf("Usage: untgz file.tgz extract all files\n" - " untgz file.tgz fname ... extract selected files\n" - " untgz -l file.tgz list archive contents\n" - " untgz -h display this help\n"); - exit(exitval); -} - -void error(const char *msg) -{ - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); -} - - -/* ============================================================ */ - -#if defined(WIN32) && defined(__GNUC__) -int _CRT_glob = 0; /* disable argument globbing in MinGW */ -#endif - -int main(int argc,char **argv) -{ - int action = TGZ_EXTRACT; - int arg = 1; - char *TGZfile; - gzFile *f; - - prog = strrchr(argv[0],'\\'); - if (prog == NULL) - { - prog = strrchr(argv[0],'/'); - if (prog == NULL) - { - prog = strrchr(argv[0],':'); - if (prog == NULL) - prog = argv[0]; - else - prog++; - } - else - prog++; - } - else - prog++; - - if (argc == 1) - help(0); - - if (strcmp(argv[arg],"-l") == 0) - { - action = TGZ_LIST; - if (argc == ++arg) - help(0); - } - else if (strcmp(argv[arg],"-h") == 0) - { - help(0); - } - - if ((TGZfile = TGZfname(argv[arg])) == NULL) - TGZnotfound(argv[arg]); - - ++arg; - if ((action == TGZ_LIST) && (arg != argc)) - help(1); - -/* - * Process the TGZ file - */ - switch(action) - { - case TGZ_LIST: - case TGZ_EXTRACT: - f = gzopen(TGZfile,"rb"); - if (f == NULL) - { - fprintf(stderr,"%s: Couldn't gzopen %s\n",prog,TGZfile); - return 1; - } - exit(tar(f, action, arg, argc, argv)); - break; - - default: - error("Unknown option"); - exit(1); - } - - return 0; -} diff --git a/deps/zlib/contrib/vstudio/readme.txt b/deps/zlib/contrib/vstudio/readme.txt deleted file mode 100644 index 48cccc0d2a2636..00000000000000 --- a/deps/zlib/contrib/vstudio/readme.txt +++ /dev/null @@ -1,78 +0,0 @@ -Building instructions for the DLL versions of Zlib 1.2.11 -======================================================== - -This directory contains projects that build zlib and minizip using -Microsoft Visual C++ 9.0/10.0. - -You don't need to build these projects yourself. You can download the -binaries from: - http://www.winimage.com/zLibDll - -More information can be found at this site. - - - - - -Build instructions for Visual Studio 2008 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Compile assembly code (with Visual Studio Command Prompt) by running: - bld_ml64.bat (in contrib\masmx64) - bld_ml32.bat (in contrib\masmx86) -- Open contrib\vstudio\vc9\zlibvc.sln with Microsoft Visual C++ 2008 -- Or run: vcbuild /rebuild contrib\vstudio\vc9\zlibvc.sln "Release|Win32" - -Build instructions for Visual Studio 2010 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc10\zlibvc.sln with Microsoft Visual C++ 2010 - -Build instructions for Visual Studio 2012 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc11\zlibvc.sln with Microsoft Visual C++ 2012 - -Build instructions for Visual Studio 2013 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc12\zlibvc.sln with Microsoft Visual C++ 2013 - -Build instructions for Visual Studio 2015 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc14\zlibvc.sln with Microsoft Visual C++ 2015 - - -Important ---------- -- To use zlibwapi.dll in your application, you must define the - macro ZLIB_WINAPI when compiling your application's source files. - - -Additional notes ----------------- -- This DLL, named zlibwapi.dll, is compatible to the old zlib.dll built - by Gilles Vollant from the zlib 1.1.x sources, and distributed at - http://www.winimage.com/zLibDll - It uses the WINAPI calling convention for the exported functions, and - includes the minizip functionality. If your application needs that - particular build of zlib.dll, you can rename zlibwapi.dll to zlib.dll. - -- The new DLL was renamed because there exist several incompatible - versions of zlib.dll on the Internet. - -- There is also an official DLL build of zlib, named zlib1.dll. This one - is exporting the functions using the CDECL convention. See the file - win32\DLL_FAQ.txt found in this zlib distribution. - -- There used to be a ZLIB_DLL macro in zlib 1.1.x, but now this symbol - has a slightly different effect. To avoid compatibility problems, do - not define it here. - - -Gilles Vollant -info@winimage.com - -Visual Studio 2013 and 2015 Projects from Sean Hunt -seandhunt_7@yahoo.com diff --git a/deps/zlib/contrib/vstudio/vc10/zlib.rc b/deps/zlib/contrib/vstudio/vc10/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc10/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc10/zlibvc.def b/deps/zlib/contrib/vstudio/vc10/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc10/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc11/zlib.rc b/deps/zlib/contrib/vstudio/vc11/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc11/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc11/zlibvc.def b/deps/zlib/contrib/vstudio/vc11/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc11/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc12/zlib.rc b/deps/zlib/contrib/vstudio/vc12/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc12/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc12/zlibvc.def b/deps/zlib/contrib/vstudio/vc12/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc12/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc14/zlib.rc b/deps/zlib/contrib/vstudio/vc14/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc14/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc14/zlibvc.def b/deps/zlib/contrib/vstudio/vc14/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc14/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc9/zlib.rc b/deps/zlib/contrib/vstudio/vc9/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc9/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc9/zlibvc.def b/deps/zlib/contrib/vstudio/vc9/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc9/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/crc32.c b/deps/zlib/crc32.c index 9580440c0e6b67..e95b9087351c1a 100644 --- a/deps/zlib/crc32.c +++ b/deps/zlib/crc32.c @@ -28,8 +28,17 @@ # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ +#include "deflate.h" +#include "x86.h" #include "zutil.h" /* for STDC and FAR definitions */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) +#include "crc32_simd.h" +#elif defined(CRC32_ARMV8_CRC32) +#include "arm_features.h" +#include "crc32_simd.h" +#endif + /* Definitions for doing the crc four data bytes at a time. */ #if !defined(NOBYFOUR) && defined(Z_U4) # define BYFOUR @@ -204,7 +213,39 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) const unsigned char FAR *buf; z_size_t len; { - if (buf == Z_NULL) return 0UL; + /* + * zlib convention is to call crc32(0, NULL, 0); before making + * calls to crc32(). So this is a good, early (and infrequent) + * place to cache CPU features if needed for those later, more + * interesting crc32() calls. + */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) + /* + * Use x86 sse4.2+pclmul SIMD to compute the crc32. Since this + * routine can be freely used, check CPU features here. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling crc32(0, NULL, 0); */ + x86_check_features(); + return 0UL; + } + + if (x86_cpu_enable_simd && len >= Z_CRC32_SSE42_MINIMUM_LENGTH) { + /* crc32 16-byte chunks */ + z_size_t chunk_size = len & ~Z_CRC32_SSE42_CHUNKSIZE_MASK; + crc = ~crc32_sse42_simd_(buf, chunk_size, ~(uint32_t)crc); + /* check remaining data */ + len -= chunk_size; + if (!len) + return crc; + /* Fall into the default crc32 for the remaining data. */ + buf += chunk_size; + } +#else + if (buf == Z_NULL) { + return 0UL; + } +#endif /* CRC32_SIMD_SSE42_PCLMUL */ #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) @@ -239,6 +280,22 @@ unsigned long ZEXPORT crc32(crc, buf, len) const unsigned char FAR *buf; uInt len; { +#if defined(CRC32_ARMV8_CRC32) + /* We got to verify ARM CPU features, so exploit the common usage pattern + * of calling this function with Z_NULL for an initial valid crc value. + * This allows to cache the result of the feature check and avoid extraneous + * function calls. + * TODO: try to move this to crc32_z if we don't loose performance on ARM. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling crc32(0, NULL, 0); */ + arm_check_features(); + return 0UL; + } + + if (arm_cpu_enable_crc32) + return armv8_crc32_little(crc, buf, len); +#endif return crc32_z(crc, buf, len); } @@ -440,3 +497,28 @@ uLong ZEXPORT crc32_combine64(crc1, crc2, len2) { return crc32_combine_(crc1, crc2, len2); } + +ZLIB_INTERNAL void crc_reset(deflate_state *const s) +{ + if (x86_cpu_enable_simd) { + crc_fold_init(s); + return; + } + s->strm->adler = crc32(0L, Z_NULL, 0); +} + +ZLIB_INTERNAL void crc_finalize(deflate_state *const s) +{ + if (x86_cpu_enable_simd) + s->strm->adler = crc_fold_512to32(s); +} + +ZLIB_INTERNAL void copy_with_crc(z_streamp strm, Bytef *dst, long size) +{ + if (x86_cpu_enable_simd) { + crc_fold_copy(strm->state, dst, strm->next_in, size); + return; + } + zmemcpy(dst, strm->next_in, size); + strm->adler = crc32(strm->adler, dst, size); +} diff --git a/deps/zlib/crc32_simd.c b/deps/zlib/crc32_simd.c new file mode 100644 index 00000000000000..c8e5592f38ef1e --- /dev/null +++ b/deps/zlib/crc32_simd.c @@ -0,0 +1,243 @@ +/* crc32_simd.c + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "crc32_simd.h" + +#if defined(CRC32_SIMD_SSE42_PCLMUL) + +/* + * crc32_sse42_simd_(): compute the crc32 of the buffer, where the buffer + * length must be at least 64, and a multiple of 16. Based on: + * + * "Fast CRC Computation for Generic Polynomials Using PCLMULQDQ Instruction" + * V. Gopal, E. Ozturk, et al., 2009, http://intel.ly/2ySEwL0 + */ + +#include +#include +#include + +uint32_t ZLIB_INTERNAL crc32_sse42_simd_( /* SSE4.2+PCLMUL */ + const unsigned char *buf, + z_size_t len, + uint32_t crc) +{ + /* + * Definitions of the bit-reflected domain constants k1,k2,k3, etc and + * the CRC32+Barrett polynomials given at the end of the paper. + */ + static const uint64_t zalign(16) k1k2[] = { 0x0154442bd4, 0x01c6e41596 }; + static const uint64_t zalign(16) k3k4[] = { 0x01751997d0, 0x00ccaa009e }; + static const uint64_t zalign(16) k5k0[] = { 0x0163cd6124, 0x0000000000 }; + static const uint64_t zalign(16) poly[] = { 0x01db710641, 0x01f7011641 }; + + __m128i x0, x1, x2, x3, x4, x5, x6, x7, x8, y5, y6, y7, y8; + + /* + * There's at least one block of 64. + */ + x1 = _mm_loadu_si128((__m128i *)(buf + 0x00)); + x2 = _mm_loadu_si128((__m128i *)(buf + 0x10)); + x3 = _mm_loadu_si128((__m128i *)(buf + 0x20)); + x4 = _mm_loadu_si128((__m128i *)(buf + 0x30)); + + x1 = _mm_xor_si128(x1, _mm_cvtsi32_si128(crc)); + + x0 = _mm_load_si128((__m128i *)k1k2); + + buf += 64; + len -= 64; + + /* + * Parallel fold blocks of 64, if any. + */ + while (len >= 64) + { + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x6 = _mm_clmulepi64_si128(x2, x0, 0x00); + x7 = _mm_clmulepi64_si128(x3, x0, 0x00); + x8 = _mm_clmulepi64_si128(x4, x0, 0x00); + + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x2 = _mm_clmulepi64_si128(x2, x0, 0x11); + x3 = _mm_clmulepi64_si128(x3, x0, 0x11); + x4 = _mm_clmulepi64_si128(x4, x0, 0x11); + + y5 = _mm_loadu_si128((__m128i *)(buf + 0x00)); + y6 = _mm_loadu_si128((__m128i *)(buf + 0x10)); + y7 = _mm_loadu_si128((__m128i *)(buf + 0x20)); + y8 = _mm_loadu_si128((__m128i *)(buf + 0x30)); + + x1 = _mm_xor_si128(x1, x5); + x2 = _mm_xor_si128(x2, x6); + x3 = _mm_xor_si128(x3, x7); + x4 = _mm_xor_si128(x4, x8); + + x1 = _mm_xor_si128(x1, y5); + x2 = _mm_xor_si128(x2, y6); + x3 = _mm_xor_si128(x3, y7); + x4 = _mm_xor_si128(x4, y8); + + buf += 64; + len -= 64; + } + + /* + * Fold into 128-bits. + */ + x0 = _mm_load_si128((__m128i *)k3k4); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x2); + x1 = _mm_xor_si128(x1, x5); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x3); + x1 = _mm_xor_si128(x1, x5); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x4); + x1 = _mm_xor_si128(x1, x5); + + /* + * Single fold blocks of 16, if any. + */ + while (len >= 16) + { + x2 = _mm_loadu_si128((__m128i *)buf); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x2); + x1 = _mm_xor_si128(x1, x5); + + buf += 16; + len -= 16; + } + + /* + * Fold 128-bits to 64-bits. + */ + x2 = _mm_clmulepi64_si128(x1, x0, 0x10); + x3 = _mm_setr_epi32(~0, 0, ~0, 0); + x1 = _mm_srli_si128(x1, 8); + x1 = _mm_xor_si128(x1, x2); + + x0 = _mm_loadl_epi64((__m128i*)k5k0); + + x2 = _mm_srli_si128(x1, 4); + x1 = _mm_and_si128(x1, x3); + x1 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_xor_si128(x1, x2); + + /* + * Barret reduce to 32-bits. + */ + x0 = _mm_load_si128((__m128i*)poly); + + x2 = _mm_and_si128(x1, x3); + x2 = _mm_clmulepi64_si128(x2, x0, 0x10); + x2 = _mm_and_si128(x2, x3); + x2 = _mm_clmulepi64_si128(x2, x0, 0x00); + x1 = _mm_xor_si128(x1, x2); + + /* + * Return the crc32. + */ + return _mm_extract_epi32(x1, 1); +} + +#elif defined(CRC32_ARMV8_CRC32) + +/* CRC32 checksums using ARMv8-a crypto instructions. + * + * TODO: implement a version using the PMULL instruction. + */ + +#if defined(__clang__) +/* CRC32 intrinsics are #ifdef'ed out of arm_acle.h unless we build with an + * armv8 target, which is incompatible with ThinLTO optimizations on Android. + * (Namely, mixing and matching different module-level targets makes ThinLTO + * warn, and Android defaults to armv7-a. This restriction does not apply to + * function-level `target`s, however.) + * + * Since we only need four crc intrinsics, and since clang's implementation of + * those are just wrappers around compiler builtins, it's simplest to #define + * those builtins directly. If this #define list grows too much (or we depend on + * an intrinsic that isn't a trivial wrapper), we may have to find a better way + * to go about this. + * + * NOTE: clang currently complains that "'+soft-float-abi' is not a recognized + * feature for this target (ignoring feature)." This appears to be a harmless + * bug in clang. + */ +#define __crc32b __builtin_arm_crc32b +#define __crc32d __builtin_arm_crc32d +#define __crc32w __builtin_arm_crc32w +#define __crc32cw __builtin_arm_crc32cw + +#if defined(__aarch64__) +#define TARGET_ARMV8_WITH_CRC __attribute__((target("crc"))) +#else // !defined(__aarch64__) +#define TARGET_ARMV8_WITH_CRC __attribute__((target("armv8-a,crc"))) +#endif // defined(__aarch64__) + +#elif defined(__GNUC__) +/* For GCC, we are setting CRC extensions at module level, so ThinLTO is not + * allowed. We can just include arm_acle.h. + */ +#include +#define TARGET_ARMV8_WITH_CRC +#else // !defined(__GNUC__) && !defined(_aarch64__) +#error ARM CRC32 SIMD extensions only supported for Clang and GCC +#endif + +TARGET_ARMV8_WITH_CRC +uint32_t ZLIB_INTERNAL armv8_crc32_little(unsigned long crc, + const unsigned char *buf, + z_size_t len) +{ + uint32_t c = (uint32_t) ~crc; + + while (len && ((uintptr_t)buf & 7)) { + c = __crc32b(c, *buf++); + --len; + } + + const uint64_t *buf8 = (const uint64_t *)buf; + + while (len >= 64) { + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + len -= 64; + } + + while (len >= 8) { + c = __crc32d(c, *buf8++); + len -= 8; + } + + buf = (const unsigned char *)buf8; + + while (len--) { + c = __crc32b(c, *buf++); + } + + return ~c; +} + +#endif diff --git a/deps/zlib/crc32_simd.h b/deps/zlib/crc32_simd.h new file mode 100644 index 00000000000000..68bc235cbe1682 --- /dev/null +++ b/deps/zlib/crc32_simd.h @@ -0,0 +1,36 @@ +/* crc32_simd.h + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include + +#include "zconf.h" +#include "zutil.h" +#include "deflate.h" + +/* + * crc32_sse42_simd_(): compute the crc32 of the buffer, where the buffer + * length must be at least 64, and a multiple of 16. + */ +uint32_t ZLIB_INTERNAL crc32_sse42_simd_( + const unsigned char *buf, + z_size_t len, + uint32_t crc); + +/* + * crc32_sse42_simd_ buffer size constraints: see the use in zlib/crc32.c + * for computing the crc32 of an arbitrary length buffer. + */ +#define Z_CRC32_SSE42_MINIMUM_LENGTH 64 +#define Z_CRC32_SSE42_CHUNKSIZE_MASK 15 + +/* + * CRC32 checksums using ARMv8-a crypto instructions. + */ +uint32_t ZLIB_INTERNAL armv8_crc32_little(unsigned long crc, + const unsigned char* buf, + z_size_t len); + diff --git a/deps/zlib/crc_folding.c b/deps/zlib/crc_folding.c new file mode 100644 index 00000000000000..48d77744aaf47d --- /dev/null +++ b/deps/zlib/crc_folding.c @@ -0,0 +1,493 @@ +/* + * Compute the CRC32 using a parallelized folding approach with the PCLMULQDQ + * instruction. + * + * A white paper describing this algorithm can be found at: + * http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf + * + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Authors: + * Wajdi Feghali + * Jim Guilford + * Vinodh Gopal + * Erdinc Ozturk + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "deflate.h" + +#include +#include +#include +#include + +#define CRC_LOAD(s) \ + do { \ + __m128i xmm_crc0 = _mm_loadu_si128((__m128i *)s->crc0 + 0);\ + __m128i xmm_crc1 = _mm_loadu_si128((__m128i *)s->crc0 + 1);\ + __m128i xmm_crc2 = _mm_loadu_si128((__m128i *)s->crc0 + 2);\ + __m128i xmm_crc3 = _mm_loadu_si128((__m128i *)s->crc0 + 3);\ + __m128i xmm_crc_part = _mm_loadu_si128((__m128i *)s->crc0 + 4); + +#define CRC_SAVE(s) \ + _mm_storeu_si128((__m128i *)s->crc0 + 0, xmm_crc0);\ + _mm_storeu_si128((__m128i *)s->crc0 + 1, xmm_crc1);\ + _mm_storeu_si128((__m128i *)s->crc0 + 2, xmm_crc2);\ + _mm_storeu_si128((__m128i *)s->crc0 + 3, xmm_crc3);\ + _mm_storeu_si128((__m128i *)s->crc0 + 4, xmm_crc_part);\ + } while (0); + +ZLIB_INTERNAL void crc_fold_init(deflate_state *const s) +{ + CRC_LOAD(s) + + xmm_crc0 = _mm_cvtsi32_si128(0x9db42487); + xmm_crc1 = _mm_setzero_si128(); + xmm_crc2 = _mm_setzero_si128(); + xmm_crc3 = _mm_setzero_si128(); + + CRC_SAVE(s) + + s->strm->adler = 0; +} + +local void fold_1(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3; + __m128 ps_crc0, ps_crc3, ps_res; + + x_tmp3 = *xmm_crc3; + + *xmm_crc3 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_res = _mm_xor_ps(ps_crc0, ps_crc3); + + *xmm_crc0 = *xmm_crc1; + *xmm_crc1 = *xmm_crc2; + *xmm_crc2 = x_tmp3; + *xmm_crc3 = _mm_castps_si128(ps_res); +} + +local void fold_2(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3, x_tmp2; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res31, ps_res20; + + x_tmp3 = *xmm_crc3; + x_tmp2 = *xmm_crc2; + + *xmm_crc3 = *xmm_crc1; + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_res31= _mm_xor_ps(ps_crc3, ps_crc1); + + *xmm_crc2 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_res20= _mm_xor_ps(ps_crc0, ps_crc2); + + *xmm_crc0 = x_tmp2; + *xmm_crc1 = x_tmp3; + *xmm_crc2 = _mm_castps_si128(ps_res20); + *xmm_crc3 = _mm_castps_si128(ps_res31); +} + +local void fold_3(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res32, ps_res21, ps_res10; + + x_tmp3 = *xmm_crc3; + + *xmm_crc3 = *xmm_crc2; + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_res32 = _mm_xor_ps(ps_crc2, ps_crc3); + + *xmm_crc2 = *xmm_crc1; + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_res21= _mm_xor_ps(ps_crc1, ps_crc2); + + *xmm_crc1 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_res10= _mm_xor_ps(ps_crc0, ps_crc1); + + *xmm_crc0 = x_tmp3; + *xmm_crc1 = _mm_castps_si128(ps_res10); + *xmm_crc2 = _mm_castps_si128(ps_res21); + *xmm_crc3 = _mm_castps_si128(ps_res32); +} + +local void fold_4(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp0, x_tmp1, x_tmp2, x_tmp3; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3; + __m128 ps_t0, ps_t1, ps_t2, ps_t3; + __m128 ps_res0, ps_res1, ps_res2, ps_res3; + + x_tmp0 = *xmm_crc0; + x_tmp1 = *xmm_crc1; + x_tmp2 = *xmm_crc2; + x_tmp3 = *xmm_crc3; + + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + x_tmp0 = _mm_clmulepi64_si128(x_tmp0, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_t0 = _mm_castsi128_ps(x_tmp0); + ps_res0 = _mm_xor_ps(ps_crc0, ps_t0); + + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + x_tmp1 = _mm_clmulepi64_si128(x_tmp1, xmm_fold4, 0x10); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_t1 = _mm_castsi128_ps(x_tmp1); + ps_res1 = _mm_xor_ps(ps_crc1, ps_t1); + + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); + x_tmp2 = _mm_clmulepi64_si128(x_tmp2, xmm_fold4, 0x10); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_t2 = _mm_castsi128_ps(x_tmp2); + ps_res2 = _mm_xor_ps(ps_crc2, ps_t2); + + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x01); + x_tmp3 = _mm_clmulepi64_si128(x_tmp3, xmm_fold4, 0x10); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_t3 = _mm_castsi128_ps(x_tmp3); + ps_res3 = _mm_xor_ps(ps_crc3, ps_t3); + + *xmm_crc0 = _mm_castps_si128(ps_res0); + *xmm_crc1 = _mm_castps_si128(ps_res1); + *xmm_crc2 = _mm_castps_si128(ps_res2); + *xmm_crc3 = _mm_castps_si128(ps_res3); +} + +local const unsigned zalign(32) pshufb_shf_table[60] = { + 0x84838281,0x88878685,0x8c8b8a89,0x008f8e8d, /* shl 15 (16 - 1)/shr1 */ + 0x85848382,0x89888786,0x8d8c8b8a,0x01008f8e, /* shl 14 (16 - 3)/shr2 */ + 0x86858483,0x8a898887,0x8e8d8c8b,0x0201008f, /* shl 13 (16 - 4)/shr3 */ + 0x87868584,0x8b8a8988,0x8f8e8d8c,0x03020100, /* shl 12 (16 - 4)/shr4 */ + 0x88878685,0x8c8b8a89,0x008f8e8d,0x04030201, /* shl 11 (16 - 5)/shr5 */ + 0x89888786,0x8d8c8b8a,0x01008f8e,0x05040302, /* shl 10 (16 - 6)/shr6 */ + 0x8a898887,0x8e8d8c8b,0x0201008f,0x06050403, /* shl 9 (16 - 7)/shr7 */ + 0x8b8a8988,0x8f8e8d8c,0x03020100,0x07060504, /* shl 8 (16 - 8)/shr8 */ + 0x8c8b8a89,0x008f8e8d,0x04030201,0x08070605, /* shl 7 (16 - 9)/shr9 */ + 0x8d8c8b8a,0x01008f8e,0x05040302,0x09080706, /* shl 6 (16 -10)/shr10*/ + 0x8e8d8c8b,0x0201008f,0x06050403,0x0a090807, /* shl 5 (16 -11)/shr11*/ + 0x8f8e8d8c,0x03020100,0x07060504,0x0b0a0908, /* shl 4 (16 -12)/shr12*/ + 0x008f8e8d,0x04030201,0x08070605,0x0c0b0a09, /* shl 3 (16 -13)/shr13*/ + 0x01008f8e,0x05040302,0x09080706,0x0d0c0b0a, /* shl 2 (16 -14)/shr14*/ + 0x0201008f,0x06050403,0x0a090807,0x0e0d0c0b /* shl 1 (16 -15)/shr15*/ +}; + +local void partial_fold(deflate_state *const s, const size_t len, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3, + __m128i *xmm_crc_part) +{ + + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + const __m128i xmm_mask3 = _mm_set1_epi32(0x80808080); + + __m128i xmm_shl, xmm_shr, xmm_tmp1, xmm_tmp2, xmm_tmp3; + __m128i xmm_a0_0, xmm_a0_1; + __m128 ps_crc3, psa0_0, psa0_1, ps_res; + + xmm_shl = _mm_load_si128((__m128i *)pshufb_shf_table + (len - 1)); + xmm_shr = xmm_shl; + xmm_shr = _mm_xor_si128(xmm_shr, xmm_mask3); + + xmm_a0_0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shl); + + *xmm_crc0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shr); + xmm_tmp1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shl); + *xmm_crc0 = _mm_or_si128(*xmm_crc0, xmm_tmp1); + + *xmm_crc1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shr); + xmm_tmp2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shl); + *xmm_crc1 = _mm_or_si128(*xmm_crc1, xmm_tmp2); + + *xmm_crc2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shr); + xmm_tmp3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shl); + *xmm_crc2 = _mm_or_si128(*xmm_crc2, xmm_tmp3); + + *xmm_crc3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shr); + *xmm_crc_part = _mm_shuffle_epi8(*xmm_crc_part, xmm_shl); + *xmm_crc3 = _mm_or_si128(*xmm_crc3, *xmm_crc_part); + + xmm_a0_1 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x10); + xmm_a0_0 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x01); + + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + psa0_0 = _mm_castsi128_ps(xmm_a0_0); + psa0_1 = _mm_castsi128_ps(xmm_a0_1); + + ps_res = _mm_xor_ps(ps_crc3, psa0_0); + ps_res = _mm_xor_ps(ps_res, psa0_1); + + *xmm_crc3 = _mm_castps_si128(ps_res); +} + +ZLIB_INTERNAL void crc_fold_copy(deflate_state *const s, + unsigned char *dst, const unsigned char *src, long len) +{ + unsigned long algn_diff; + __m128i xmm_t0, xmm_t1, xmm_t2, xmm_t3; + + CRC_LOAD(s) + + if (len < 16) { + if (len == 0) + return; + goto partial; + } + + algn_diff = 0 - (uintptr_t)src & 0xF; + if (algn_diff) { + xmm_crc_part = _mm_loadu_si128((__m128i *)src); + _mm_storeu_si128((__m128i *)dst, xmm_crc_part); + + dst += algn_diff; + src += algn_diff; + len -= algn_diff; + + partial_fold(s, algn_diff, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, + &xmm_crc_part); + } + + while ((len -= 64) >= 0) { + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + xmm_t2 = _mm_load_si128((__m128i *)src + 2); + xmm_t3 = _mm_load_si128((__m128i *)src + 3); + + fold_4(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); + _mm_storeu_si128((__m128i *)dst + 3, xmm_t3); + + xmm_crc0 = _mm_xor_si128(xmm_crc0, xmm_t0); + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t1); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t3); + + src += 64; + dst += 64; + } + + /* + * len = num bytes left - 64 + */ + if (len + 16 >= 0) { + len += 16; + + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + xmm_t2 = _mm_load_si128((__m128i *)src + 2); + + fold_3(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); + + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t0); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t1); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t2); + + if (len == 0) + goto done; + + dst += 48; + src += 48; + } else if (len + 32 >= 0) { + len += 32; + + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + + fold_2(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t0); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t1); + + if (len == 0) + goto done; + + dst += 32; + src += 32; + } else if (len + 48 >= 0) { + len += 48; + + xmm_t0 = _mm_load_si128((__m128i *)src); + + fold_1(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t0); + + if (len == 0) + goto done; + + dst += 16; + src += 16; + } else { + len += 64; + if (len == 0) + goto done; + } + +partial: + +#if defined(_MSC_VER) + /* VS does not permit the use of _mm_set_epi64x in 32-bit builds */ + { + int32_t parts[4] = {0, 0, 0, 0}; + memcpy(&parts, src, len); + xmm_crc_part = _mm_set_epi32(parts[3], parts[2], parts[1], parts[0]); + } +#else + { + int64_t parts[2] = {0, 0}; + memcpy(&parts, src, len); + xmm_crc_part = _mm_set_epi64x(parts[1], parts[0]); + } +#endif + + _mm_storeu_si128((__m128i *)dst, xmm_crc_part); + partial_fold(s, len, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, + &xmm_crc_part); +done: + CRC_SAVE(s) +} + +local const unsigned zalign(16) crc_k[] = { + 0xccaa009e, 0x00000000, /* rk1 */ + 0x751997d0, 0x00000001, /* rk2 */ + 0xccaa009e, 0x00000000, /* rk5 */ + 0x63cd6124, 0x00000001, /* rk6 */ + 0xf7011640, 0x00000001, /* rk7 */ + 0xdb710640, 0x00000001 /* rk8 */ +}; + +local const unsigned zalign(16) crc_mask[4] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 +}; + +local const unsigned zalign(16) crc_mask2[4] = { + 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF +}; + +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) +{ + const __m128i xmm_mask = _mm_load_si128((__m128i *)crc_mask); + const __m128i xmm_mask2 = _mm_load_si128((__m128i *)crc_mask2); + + unsigned crc; + __m128i x_tmp0, x_tmp1, x_tmp2, crc_fold; + + CRC_LOAD(s) + + /* + * k1 + */ + crc_fold = _mm_load_si128((__m128i *)crc_k); + + x_tmp0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x10); + xmm_crc0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x01); + xmm_crc1 = _mm_xor_si128(xmm_crc1, x_tmp0); + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_crc0); + + x_tmp1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x10); + xmm_crc1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x01); + xmm_crc2 = _mm_xor_si128(xmm_crc2, x_tmp1); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_crc1); + + x_tmp2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x10); + xmm_crc2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x01); + xmm_crc3 = _mm_xor_si128(xmm_crc3, x_tmp2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + + /* + * k5 + */ + crc_fold = _mm_load_si128((__m128i *)crc_k + 1); + + xmm_crc0 = xmm_crc3; + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); + xmm_crc0 = _mm_srli_si128(xmm_crc0, 8); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); + + xmm_crc0 = xmm_crc3; + xmm_crc3 = _mm_slli_si128(xmm_crc3, 4); + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); + xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask2); + + /* + * k7 + */ + xmm_crc1 = xmm_crc3; + xmm_crc2 = xmm_crc3; + crc_fold = _mm_load_si128((__m128i *)crc_k + 2); + + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask); + + xmm_crc2 = xmm_crc3; + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc1); + + crc = _mm_extract_epi32(xmm_crc3, 2); + return ~crc; + CRC_SAVE(s) +} diff --git a/deps/zlib/deflate.c b/deps/zlib/deflate.c index 909606df01fb70..201254ac1b664e 100644 --- a/deps/zlib/deflate.c +++ b/deps/zlib/deflate.c @@ -48,8 +48,17 @@ */ /* @(#) $Id$ */ - +#include #include "deflate.h" +#include "x86.h" +#include "contrib/optimizations/insert_string.h" + +#if (defined(__ARM_NEON__) || defined(__ARM_NEON)) +#include "contrib/optimizations/slide_hash_neon.h" +#endif +#if defined(CRC32_ARMV8_CRC32) +#include "crc32_simd.h" +#endif const char deflate_copyright[] = " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; @@ -86,7 +95,7 @@ local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); -local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV # pragma message("Assembler code may have bugs -- use at your own risk") void match_init OF((void)); /* asm code initialization */ @@ -100,6 +109,11 @@ local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif +/* From crc32.c */ +extern void ZLIB_INTERNAL crc_reset(deflate_state *const s); +extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s); +extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size); + /* =========================================================================== * Local data */ @@ -154,47 +168,13 @@ local const config configuration_table[10] = { /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to UPDATE_HASH are made with consecutive input - * characters, so that a running hash key can be computed from the previous - * key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to INSERT_STRING are made with consecutive input - * characters and the first MIN_MATCH bytes of str are valid (except for - * the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ - do { \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, \ - (unsigned)(s->hash_size-1)*sizeof(*s->head)); \ - } while (0) + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* =========================================================================== * Slide the hash table when sliding the window down (could be avoided with 32 @@ -204,6 +184,10 @@ local const config configuration_table[10] = { local void slide_hash(s) deflate_state *s; { +#if (defined(__ARM_NEON__) || defined(__ARM_NEON)) + /* NEON based hash table rebase. */ + return neon_slide_hash(s->head, s->prev, s->w_size, s->hash_size); +#endif unsigned n, m; Posf *p; uInt wsize = s->w_size; @@ -251,14 +235,20 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, const char *version; int stream_size; { + unsigned window_padding = 8; deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ + // Needed to activate optimized insert_string() that helps compression + // for all wrapper formats (e.g. RAW, ZLIB, GZIP). + // Feature detection is not triggered while using RAW mode (i.e. we never + // call crc32() with a NULL buffer). +#if defined(CRC32_ARMV8_CRC32) + arm_check_features(); +#elif defined(CRC32_SIMD_SSE42_PCLMUL) + x86_check_features(); +#endif if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { @@ -316,12 +306,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; - s->hash_bits = (uInt)memLevel + 7; + if (x86_cpu_enable_simd) { + s->hash_bits = 15; + } else { + s->hash_bits = memLevel + 7; + } + s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->window = (Bytef *) ZALLOC(strm, + s->w_size + window_padding, + 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); @@ -329,9 +326,46 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + /* We overlay pending_buf and sym_buf. This works since the average size + * for length/distance pairs over any compressed block is assured to be 31 + * bits or less. + * + * Analysis: The longest fixed codes are a length code of 8 bits plus 5 + * extra bits, for lengths 131 to 257. The longest fixed distance codes are + * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest + * possible fixed-codes length/distance pair is then 31 bits total. + * + * sym_buf starts one-fourth of the way into pending_buf. So there are + * three bytes in sym_buf for every four bytes in pending_buf. Each symbol + * in sym_buf is three bytes -- two for the distance and one for the + * literal/length. As each symbol is consumed, the pointer to the next + * sym_buf value to read moves forward three bytes. From that symbol, up to + * 31 bits are written to pending_buf. The closest the written pending_buf + * bits gets to the next sym_buf symbol to read is just before the last + * code is written. At that time, 31*(n-2) bits have been written, just + * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at + * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 + * symbols are written.) The closest the writing gets to what is unread is + * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and + * can range from 128 to 32768. + * + * Therefore, at a minimum, there are 142 bits of space between what is + * written and what is read in the overlain buffers, so the symbols cannot + * be overwritten by the compressed data. That space is actually 139 bits, + * due to the three-bit fixed-code block header. + * + * That covers the case where either Z_FIXED is specified, forcing fixed + * codes, or when the use of fixed codes is chosen, because that choice + * results in a smaller compressed block than dynamic codes. That latter + * condition then assures that the above analysis also covers all dynamic + * blocks. A dynamic-code block will only be chosen to be emitted if it has + * fewer bits than a fixed-code block would for the same set of symbols. + * Therefore its average symbol length is assured to be less than 31. So + * the compressed data for a dynamic block also cannot overwrite the + * symbols from which it is being constructed. + */ + s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4); + s->pending_buf_size = (ulg)s->lit_bufsize * 4; if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { @@ -340,8 +374,12 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, deflateEnd (strm); return Z_MEM_ERROR; } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s->sym_buf = s->pending_buf + s->lit_bufsize; + s->sym_end = (s->lit_bufsize - 1) * 3; + /* We avoid equality with lit_bufsize*3 because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ s->level = level; s->strategy = strategy; @@ -397,7 +435,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap == 1) strm->adler = adler32(strm->adler, dictionary, dictLength); - s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + s->wrap = 0; /* avoid computing Adler-32 in deflate_read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s->w_size) { @@ -421,11 +459,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) str = s->strstart; n = s->lookahead - (MIN_MATCH-1); do { - UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); -#ifndef FASTEST - s->prev[str & s->w_mask] = s->head[s->ins_h]; -#endif - s->head[s->ins_h] = (Pos)str; + insert_string(s, str); str++; } while (--n); s->strstart = str; @@ -552,7 +586,7 @@ int ZEXPORT deflatePrime (strm, bits, value) if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; - if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + if (s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) return Z_BUF_ERROR; do { put = Buf_size - s->bi_valid; @@ -728,7 +762,7 @@ local void putShortMSB (s, b) * Flush as much pending output as possible. All deflate() output, except for * some deflate_stored() output, goes through this function so some * applications may wish to modify it to avoid allocating a large - * strm->next_out buffer and copying into it. (See also read_buf()). + * strm->next_out buffer and copying into it. (See also deflate_read_buf()). */ local void flush_pending(strm) z_streamp strm; @@ -851,7 +885,7 @@ int ZEXPORT deflate (strm, flush) #ifdef GZIP if (s->status == GZIP_STATE) { /* gzip header */ - strm->adler = crc32(0L, Z_NULL, 0); + crc_reset(s); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); @@ -1052,6 +1086,7 @@ int ZEXPORT deflate (strm, flush) /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { + crc_finalize(s); put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); @@ -1111,7 +1146,6 @@ int ZEXPORT deflateCopy (dest, source) #else deflate_state *ds; deflate_state *ss; - ushf *overlay; if (deflateStateCheck(source) || dest == Z_NULL) { @@ -1131,8 +1165,7 @@ int ZEXPORT deflateCopy (dest, source) ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; + ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { @@ -1146,8 +1179,7 @@ int ZEXPORT deflateCopy (dest, source) zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + ds->sym_buf = ds->pending_buf + ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; @@ -1164,7 +1196,7 @@ int ZEXPORT deflateCopy (dest, source) * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ -local unsigned read_buf(strm, buf, size) +ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; @@ -1176,15 +1208,16 @@ local unsigned read_buf(strm, buf, size) strm->avail_in -= len; - zmemcpy(buf, strm->next_in, len); - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, buf, len); - } #ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, buf, len); - } + if (strm->state->wrap == 2) + copy_with_crc(strm, buf, len); + else #endif + { + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) + strm->adler = adler32(strm->adler, buf, len); + } strm->next_in += len; strm->total_in += len; @@ -1482,7 +1515,19 @@ local void check_match(s, start, match, length) * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ -local void fill_window(s) +local void fill_window_c(deflate_state *s); + +local void fill_window(deflate_state *s) +{ + if (x86_cpu_enable_simd) { + fill_window_sse(s); + return; + } + + fill_window_c(s); +} + +local void fill_window_c(s) deflate_state *s; { unsigned n; @@ -1534,7 +1579,7 @@ local void fill_window(s) */ Assert(more >= 2, "more < 2"); - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + n = deflate_read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ @@ -1723,7 +1768,7 @@ local block_state deflate_stored(s, flush) * the check value. */ if (len) { - read_buf(s->strm, s->strm->next_out, len); + deflate_read_buf(s->strm, s->strm->next_out, len); s->strm->next_out += len; s->strm->avail_out -= len; s->strm->total_out += len; @@ -1786,7 +1831,7 @@ local block_state deflate_stored(s, flush) if (have > s->strm->avail_in) have = s->strm->avail_in; if (have) { - read_buf(s->strm, s->window + s->strstart, have); + deflate_read_buf(s->strm, s->window + s->strstart, have); s->strstart += have; } if (s->high_water < s->strstart) @@ -1850,7 +1895,7 @@ local block_state deflate_fast(s, flush) */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } /* Find the longest match, discarding those <= prev_length. @@ -1881,7 +1926,7 @@ local block_state deflate_fast(s, flush) s->match_length--; /* string at strstart already in table */ do { s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ @@ -1915,7 +1960,7 @@ local block_state deflate_fast(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -1953,7 +1998,7 @@ local block_state deflate_slow(s, flush) */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } /* Find the longest match, discarding those <= prev_length. @@ -2004,7 +2049,7 @@ local block_state deflate_slow(s, flush) s->prev_length -= 2; do { if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } } while (--s->prev_length != 0); s->match_available = 0; @@ -2046,7 +2091,7 @@ local block_state deflate_slow(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -2121,7 +2166,7 @@ local block_state deflate_rle(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -2160,7 +2205,7 @@ local block_state deflate_huff(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } diff --git a/deps/zlib/deflate.h b/deps/zlib/deflate.h index 23ecdd312bc06e..78ffb00a29768e 100644 --- a/deps/zlib/deflate.h +++ b/deps/zlib/deflate.h @@ -109,8 +109,8 @@ typedef struct internal_state { ulg gzindex; /* where in extra, name, or comment */ Byte method; /* can only be DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ + unsigned crc0[4 * 5]; + /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ @@ -217,7 +217,7 @@ typedef struct internal_state { /* Depth of each subtree used as tie breaker for trees of equal frequency */ - uchf *l_buf; /* buffer for literals or lengths */ + uchf *sym_buf; /* buffer for distances and literals/lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for @@ -239,13 +239,8 @@ typedef struct internal_state { * - I can't count above 4 */ - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ + uInt sym_next; /* running index in sym_buf */ + uInt sym_end; /* symbol table full when sym_next reaches this */ ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ @@ -325,20 +320,22 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, # define _tr_tally_lit(s, c, flush) \ { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ + s->sym_buf[s->sym_next++] = 0; \ + s->sym_buf[s->sym_next++] = 0; \ + s->sym_buf[s->sym_next++] = cc; \ s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ + flush = (s->sym_next == s->sym_end); \ } # define _tr_tally_dist(s, distance, length, flush) \ { uch len = (uch)(length); \ ush dist = (ush)(distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ + s->sym_buf[s->sym_next++] = dist; \ + s->sym_buf[s->sym_next++] = dist >> 8; \ + s->sym_buf[s->sym_next++] = len; \ dist--; \ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ + flush = (s->sym_next == s->sym_end); \ } #else # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) @@ -346,4 +343,14 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, flush = _tr_tally(s, distance, length) #endif +/* Functions that are SIMD optimised on x86 */ +void ZLIB_INTERNAL crc_fold_init(deflate_state* const s); +void ZLIB_INTERNAL crc_fold_copy(deflate_state* const s, + unsigned char* dst, + const unsigned char* src, + long len); +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state* const s); + +void ZLIB_INTERNAL fill_window_sse(deflate_state* s); + #endif /* DEFLATE_H */ diff --git a/deps/zlib/doc/algorithm.txt b/deps/zlib/doc/algorithm.txt deleted file mode 100644 index c97f495020b429..00000000000000 --- a/deps/zlib/doc/algorithm.txt +++ /dev/null @@ -1,209 +0,0 @@ -1. Compression algorithm (deflate) - -The deflation algorithm used by gzip (also zip and zlib) is a variation of -LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in -the input data. The second occurrence of a string is replaced by a -pointer to the previous string, in the form of a pair (distance, -length). Distances are limited to 32K bytes, and lengths are limited -to 258 bytes. When a string does not occur anywhere in the previous -32K bytes, it is emitted as a sequence of literal bytes. (In this -description, `string' must be taken as an arbitrary sequence of bytes, -and is not restricted to printable characters.) - -Literals or match lengths are compressed with one Huffman tree, and -match distances are compressed with another tree. The trees are stored -in a compact form at the start of each block. The blocks can have any -size (except that the compressed data for one block must fit in -available memory). A block is terminated when deflate() determines that -it would be useful to start another block with fresh trees. (This is -somewhat similar to the behavior of LZW-based _compress_.) - -Duplicated strings are found using a hash table. All input strings of -length 3 are inserted in the hash table. A hash index is computed for -the next 3 bytes. If the hash chain for this index is not empty, all -strings in the chain are compared with the current input string, and -the longest match is selected. - -The hash chains are searched starting with the most recent strings, to -favor small distances and thus take advantage of the Huffman encoding. -The hash chains are singly linked. There are no deletions from the -hash chains, the algorithm simply discards matches that are too old. - -To avoid a worst-case situation, very long hash chains are arbitrarily -truncated at a certain length, determined by a runtime option (level -parameter of deflateInit). So deflate() does not always find the longest -possible match but generally finds a match which is long enough. - -deflate() also defers the selection of matches with a lazy evaluation -mechanism. After a match of length N has been found, deflate() searches for -a longer match at the next input byte. If a longer match is found, the -previous match is truncated to a length of one (thus producing a single -literal byte) and the process of lazy evaluation begins again. Otherwise, -the original match is kept, and the next match search is attempted only N -steps later. - -The lazy match evaluation is also subject to a runtime parameter. If -the current match is long enough, deflate() reduces the search for a longer -match, thus speeding up the whole process. If compression ratio is more -important than speed, deflate() attempts a complete second search even if -the first match is already long enough. - -The lazy match evaluation is not performed for the fastest compression -modes (level parameter 1 to 3). For these fast modes, new strings -are inserted in the hash table only when no match was found, or -when the match is not too long. This degrades the compression ratio -but saves time since there are both fewer insertions and fewer searches. - - -2. Decompression algorithm (inflate) - -2.1 Introduction - -The key question is how to represent a Huffman code (or any prefix code) so -that you can decode fast. The most important characteristic is that shorter -codes are much more common than longer codes, so pay attention to decoding the -short codes fast, and let the long codes take longer to decode. - -inflate() sets up a first level table that covers some number of bits of -input less than the length of longest code. It gets that many bits from the -stream, and looks it up in the table. The table will tell if the next -code is that many bits or less and how many, and if it is, it will tell -the value, else it will point to the next level table for which inflate() -grabs more bits and tries to decode a longer code. - -How many bits to make the first lookup is a tradeoff between the time it -takes to decode and the time it takes to build the table. If building the -table took no time (and if you had infinite memory), then there would only -be a first level table to cover all the way to the longest code. However, -building the table ends up taking a lot longer for more bits since short -codes are replicated many times in such a table. What inflate() does is -simply to make the number of bits in the first table a variable, and then -to set that variable for the maximum speed. - -For inflate, which has 286 possible codes for the literal/length tree, the size -of the first table is nine bits. Also the distance trees have 30 possible -values, and the size of the first table is six bits. Note that for each of -those cases, the table ended up one bit longer than the ``average'' code -length, i.e. the code length of an approximately flat code which would be a -little more than eight bits for 286 symbols and a little less than five bits -for 30 symbols. - - -2.2 More details on the inflate table lookup - -Ok, you want to know what this cleverly obfuscated inflate tree actually -looks like. You are correct that it's not a Huffman tree. It is simply a -lookup table for the first, let's say, nine bits of a Huffman symbol. The -symbol could be as short as one bit or as long as 15 bits. If a particular -symbol is shorter than nine bits, then that symbol's translation is duplicated -in all those entries that start with that symbol's bits. For example, if the -symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a -symbol is nine bits long, it appears in the table once. - -If the symbol is longer than nine bits, then that entry in the table points -to another similar table for the remaining bits. Again, there are duplicated -entries as needed. The idea is that most of the time the symbol will be short -and there will only be one table look up. (That's whole idea behind data -compression in the first place.) For the less frequent long symbols, there -will be two lookups. If you had a compression method with really long -symbols, you could have as many levels of lookups as is efficient. For -inflate, two is enough. - -So a table entry either points to another table (in which case nine bits in -the above example are gobbled), or it contains the translation for the symbol -and the number of bits to gobble. Then you start again with the next -ungobbled bit. - -You may wonder: why not just have one lookup table for how ever many bits the -longest symbol is? The reason is that if you do that, you end up spending -more time filling in duplicate symbol entries than you do actually decoding. -At least for deflate's output that generates new trees every several 10's of -kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code -would take too long if you're only decoding several thousand symbols. At the -other extreme, you could make a new table for every bit in the code. In fact, -that's essentially a Huffman tree. But then you spend too much time -traversing the tree while decoding, even for short symbols. - -So the number of bits for the first lookup table is a trade of the time to -fill out the table vs. the time spent looking at the second level and above of -the table. - -Here is an example, scaled down: - -The code being decoded, with 10 symbols, from 1 to 6 bits long: - -A: 0 -B: 10 -C: 1100 -D: 11010 -E: 11011 -F: 11100 -G: 11101 -H: 11110 -I: 111110 -J: 111111 - -Let's make the first table three bits long (eight entries): - -000: A,1 -001: A,1 -010: A,1 -011: A,1 -100: B,2 -101: B,2 -110: -> table X (gobble 3 bits) -111: -> table Y (gobble 3 bits) - -Each entry is what the bits decode as and how many bits that is, i.e. how -many bits to gobble. Or the entry points to another table, with the number of -bits to gobble implicit in the size of the table. - -Table X is two bits long since the longest code starting with 110 is five bits -long: - -00: C,1 -01: C,1 -10: D,2 -11: E,2 - -Table Y is three bits long since the longest code starting with 111 is six -bits long: - -000: F,2 -001: F,2 -010: G,2 -011: G,2 -100: H,2 -101: H,2 -110: I,3 -111: J,3 - -So what we have here are three tables with a total of 20 entries that had to -be constructed. That's compared to 64 entries for a single table. Or -compared to 16 entries for a Huffman tree (six two entry tables and one four -entry table). Assuming that the code ideally represents the probability of -the symbols, it takes on the average 1.25 lookups per symbol. That's compared -to one lookup for the single table, or 1.66 lookups per symbol for the -Huffman tree. - -There, I think that gives you a picture of what's going on. For inflate, the -meaning of a particular symbol is often more than just a letter. It can be a -byte (a "literal"), or it can be either a length or a distance which -indicates a base value and a number of bits to fetch after the code that is -added to the base value. Or it might be the special end-of-block code. The -data structures created in inftrees.c try to encode all that information -compactly in the tables. - - -Jean-loup Gailly Mark Adler -jloup@gzip.org madler@alumni.caltech.edu - - -References: - -[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data -Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3, -pp. 337-343. - -``DEFLATE Compressed Data Format Specification'' available in -http://tools.ietf.org/html/rfc1951 diff --git a/deps/zlib/doc/rfc1950.txt b/deps/zlib/doc/rfc1950.txt deleted file mode 100644 index ce6428a0f2eed4..00000000000000 --- a/deps/zlib/doc/rfc1950.txt +++ /dev/null @@ -1,619 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1950 Aladdin Enterprises -Category: Informational J-L. Gailly - Info-ZIP - May 1996 - - - ZLIB Compressed Data Format Specification version 3.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch and Jean-Loup Gailly - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format. The - data can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a priori - bounded amount of intermediate storage. The format presently uses - the DEFLATE compression method but can be easily extended to use - other compression methods. It can be implemented readily in a manner - not covered by patents. This specification also defines the ADLER-32 - checksum (an extension and improvement of the Fletcher checksum), - used for detection of data corruption, and provides an algorithm for - computing it. - - - - -Deutsch & Gailly Informational [Page 1] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................ 3 - 1.6. Changes from previous versions ............................ 3 - 2. Detailed specification ......................................... 3 - 2.1. Overall conventions ....................................... 3 - 2.2. Data format ............................................... 4 - 2.3. Compliance ................................................ 7 - 3. References ..................................................... 7 - 4. Source code .................................................... 8 - 5. Security Considerations ........................................ 8 - 6. Acknowledgements ............................................... 8 - 7. Authors' Addresses ............................................. 8 - 8. Appendix: Rationale ............................................ 9 - 9. Appendix: Sample code ..........................................10 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - - * Can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a - priori bounded amount of intermediate storage, and hence can - be used in data communications or similar structures such as - Unix filters; - - * Can use a number of different compression methods; - - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely. - - The data format defined by this specification does not attempt to - allow random access to compressed data. - - - - - - - -Deutsch & Gailly Informational [Page 2] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into zlib format and/or decompress data from zlib - format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. - - 1.3. Scope - - The specification specifies a compressed data format that can be - used for in-memory compression of a sequence of arbitrary bytes. - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any data set that conforms to all - the specifications presented here; a compliant compressor must - produce data sets that conform to all the specifications presented - here. - - 1.5. Definitions of terms and conventions used - - byte: 8 bits stored or transmitted as a unit (same as an octet). - (For this specification, a byte is exactly 8 bits, even on - machines which store a character on a number of bits different - from 8.) See below, for the numbering of bits within a byte. - - 1.6. Changes from previous versions - - Version 3.1 was the first public release of this specification. - In version 3.2, some terminology was changed and the Adler-32 - sample code was rewritten for clarity. In version 3.3, the - support for a preset dictionary was introduced, and the - specification was converted to RFC style. - -2. Detailed specification - - 2.1. Overall conventions - - In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - - - -Deutsch & Gailly Informational [Page 3] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the MOST-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00000010|00001000| - +--------+--------+ - ^ ^ - | | - | + less significant byte = 8 - + more significant byte = 2 x 256 - - 2.2. Data format - - A zlib stream has the following structure: - - 0 1 - +---+---+ - |CMF|FLG| (more-->) - +---+---+ - - - - - - - - -Deutsch & Gailly Informational [Page 4] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - (if FLG.FDICT set) - - 0 1 2 3 - +---+---+---+---+ - | DICTID | (more-->) - +---+---+---+---+ - - +=====================+---+---+---+---+ - |...compressed data...| ADLER32 | - +=====================+---+---+---+---+ - - Any data which may appear after ADLER32 are not part of the zlib - stream. - - CMF (Compression Method and flags) - This byte is divided into a 4-bit compression method and a 4- - bit information field depending on the compression method. - - bits 0 to 3 CM Compression method - bits 4 to 7 CINFO Compression info - - CM (Compression method) - This identifies the compression method used in the file. CM = 8 - denotes the "deflate" compression method with a window size up - to 32K. This is the method used by gzip and PNG (see - references [1] and [2] in Chapter 3, below, for the reference - documents). CM = 15 is reserved. It might be used in a future - version of this specification to indicate the presence of an - extra field before the compressed data. - - CINFO (Compression info) - For CM = 8, CINFO is the base-2 logarithm of the LZ77 window - size, minus eight (CINFO=7 indicates a 32K window size). Values - of CINFO above 7 are not allowed in this version of the - specification. CINFO is not defined in this specification for - CM not equal to 8. - - FLG (FLaGs) - This flag byte is divided as follows: - - bits 0 to 4 FCHECK (check bits for CMF and FLG) - bit 5 FDICT (preset dictionary) - bits 6 to 7 FLEVEL (compression level) - - The FCHECK value must be such that CMF and FLG, when viewed as - a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG), - is a multiple of 31. - - - - -Deutsch & Gailly Informational [Page 5] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - FDICT (Preset dictionary) - If FDICT is set, a DICT dictionary identifier is present - immediately after the FLG byte. The dictionary is a sequence of - bytes which are initially fed to the compressor without - producing any compressed output. DICT is the Adler-32 checksum - of this sequence of bytes (see the definition of ADLER32 - below). The decompressor can use this identifier to determine - which dictionary has been used by the compressor. - - FLEVEL (Compression level) - These flags are available for use by specific compression - methods. The "deflate" method (CM = 8) sets these flags as - follows: - - 0 - compressor used fastest algorithm - 1 - compressor used fast algorithm - 2 - compressor used default algorithm - 3 - compressor used maximum compression, slowest algorithm - - The information in FLEVEL is not needed for decompression; it - is there to indicate if recompression might be worthwhile. - - compressed data - For compression method 8, the compressed data is stored in the - deflate compressed data format as described in the document - "DEFLATE Compressed Data Format Specification" by L. Peter - Deutsch. (See reference [3] in Chapter 3, below) - - Other compressed data formats are not specified in this version - of the zlib specification. - - ADLER32 (Adler-32 checksum) - This contains a checksum value of the uncompressed data - (excluding any dictionary data) computed according to Adler-32 - algorithm. This algorithm is a 32-bit extension and improvement - of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 - standard. See references [4] and [5] in Chapter 3, below) - - Adler-32 is composed of two sums accumulated per byte: s1 is - the sum of all bytes, s2 is the sum of all s1 values. Both sums - are done modulo 65521. s1 is initialized to 1, s2 to zero. The - Adler-32 checksum is stored as s2*65536 + s1 in most- - significant-byte first (network) order. - - - - - - - - -Deutsch & Gailly Informational [Page 6] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - 2.3. Compliance - - A compliant compressor must produce streams with correct CMF, FLG - and ADLER32, but need not support preset dictionaries. When the - zlib data format is used as part of another standard data format, - the compressor may use only preset dictionaries that are specified - by this other data format. If this other format does not use the - preset dictionary feature, the compressor must not set the FDICT - flag. - - A compliant decompressor must check CMF, FLG, and ADLER32, and - provide an error indication if any of these have incorrect values. - A compliant decompressor must give an error indication if CM is - not one of the values defined in this specification (only the - value 8 is permitted in this version), since another value could - indicate the presence of new features that would cause subsequent - data to be interpreted incorrectly. A compliant decompressor must - give an error indication if FDICT is set and DICTID is not the - identifier of a known preset dictionary. A decompressor may - ignore FLEVEL and still be compliant. When the zlib data format - is being used as a part of another standard format, a compliant - decompressor must support all the preset dictionaries specified by - the other format. When the other format does not use the preset - dictionary feature, a compliant decompressor must reject any - stream in which the FDICT flag is set. - -3. References - - [1] Deutsch, L.P.,"GZIP Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [2] Thomas Boutell, "PNG (Portable Network Graphics) specification", - available in ftp://ftp.uu.net/graphics/png/documents/ - - [3] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [4] Fletcher, J. G., "An Arithmetic Checksum for Serial - Transmissions," IEEE Transactions on Communications, Vol. COM-30, - No. 1, January 1982, pp. 247-252. - - [5] ITU-T Recommendation X.224, Annex D, "Checksum Algorithms," - November, 1993, pp. 144, 145. (Available from - gopher://info.itu.ch). ITU-T X.244 is also the same as ISO 8073. - - - - - - - -Deutsch & Gailly Informational [Page 7] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -4. Source code - - Source code for a C language implementation of a "zlib" compliant - library is available at ftp://ftp.uu.net/pub/archiving/zip/zlib/. - -5. Security Considerations - - A decoder that fails to check the ADLER32 checksum value may be - subject to undetected data corruption. - -6. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Jean-Loup Gailly and Mark Adler designed the zlib format and wrote - the related software described in this specification. Glenn - Randers-Pehrson converted this document to RFC and HTML format. - -7. Authors' Addresses - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - - Jean-Loup Gailly - - EMail: - - Questions about the technical content of this specification can be - sent by email to - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - - - - -Deutsch & Gailly Informational [Page 8] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -8. Appendix: Rationale - - 8.1. Preset dictionaries - - A preset dictionary is specially useful to compress short input - sequences. The compressor can take advantage of the dictionary - context to encode the input in a more compact manner. The - decompressor can be initialized with the appropriate context by - virtually decompressing a compressed version of the dictionary - without producing any output. However for certain compression - algorithms such as the deflate algorithm this operation can be - achieved without actually performing any decompression. - - The compressor and the decompressor must use exactly the same - dictionary. The dictionary may be fixed or may be chosen among a - certain number of predefined dictionaries, according to the kind - of input data. The decompressor can determine which dictionary has - been chosen by the compressor by checking the dictionary - identifier. This document does not specify the contents of - predefined dictionaries, since the optimal dictionaries are - application specific. Standard data formats using this feature of - the zlib specification must precisely define the allowed - dictionaries. - - 8.2. The Adler-32 algorithm - - The Adler-32 algorithm is much faster than the CRC32 algorithm yet - still provides an extremely low probability of undetected errors. - - The modulo on unsigned long accumulators can be delayed for 5552 - bytes, so the modulo operation time is negligible. If the bytes - are a, b, c, the second sum is 3a + 2b + c + 3, and so is position - and order sensitive, unlike the first sum, which is just a - checksum. That 65521 is prime is important to avoid a possible - large class of two-byte errors that leave the check unchanged. - (The Fletcher checksum uses 255, which is not prime and which also - makes the Fletcher check insensitive to single byte changes 0 <-> - 255.) - - The sum s1 is initialized to 1 instead of zero to make the length - of the sequence part of s2, so that the length does not have to be - checked separately. (Any sequence of zeroes has a Fletcher - checksum of zero.) - - - - - - - - -Deutsch & Gailly Informational [Page 9] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -9. Appendix: Sample code - - The following C code computes the Adler-32 checksum of a data buffer. - It is written for clarity, not for speed. The sample code is in the - ANSI C programming language. Non C users may find it easier to read - with these hints: - - & Bitwise AND operator. - >> Bitwise right shift operator. When applied to an - unsigned quantity, as here, right shift inserts zero bit(s) - at the left. - << Bitwise left shift operator. Left shift inserts zero - bit(s) at the right. - ++ "n++" increments the variable n. - % modulo operator: a % b is the remainder of a divided by b. - - #define BASE 65521 /* largest prime smaller than 65536 */ - - /* - Update a running Adler-32 checksum with the bytes buf[0..len-1] - and return the updated checksum. The Adler-32 checksum should be - initialized to 1. - - Usage example: - - unsigned long adler = 1L; - - while (read_buffer(buffer, length) != EOF) { - adler = update_adler32(adler, buffer, length); - } - if (adler != original_adler) error(); - */ - unsigned long update_adler32(unsigned long adler, - unsigned char *buf, int len) - { - unsigned long s1 = adler & 0xffff; - unsigned long s2 = (adler >> 16) & 0xffff; - int n; - - for (n = 0; n < len; n++) { - s1 = (s1 + buf[n]) % BASE; - s2 = (s2 + s1) % BASE; - } - return (s2 << 16) + s1; - } - - /* Return the adler32 of the bytes buf[0..len-1] */ - - - - -Deutsch & Gailly Informational [Page 10] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - unsigned long adler32(unsigned char *buf, int len) - { - return update_adler32(1L, buf, len); - } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Deutsch & Gailly Informational [Page 11] - diff --git a/deps/zlib/doc/rfc1951.txt b/deps/zlib/doc/rfc1951.txt deleted file mode 100644 index 403c8c722ff24c..00000000000000 --- a/deps/zlib/doc/rfc1951.txt +++ /dev/null @@ -1,955 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1951 Aladdin Enterprises -Category: Informational May 1996 - - - DEFLATE Compressed Data Format Specification version 1.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format that - compresses data using a combination of the LZ77 algorithm and Huffman - coding, with efficiency comparable to the best currently available - general-purpose compression methods. The data can be produced or - consumed, even for an arbitrarily long sequentially presented input - data stream, using only an a priori bounded amount of intermediate - storage. The format can be implemented readily in a manner not - covered by patents. - - - - - - - - -Deutsch Informational [Page 1] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................ 3 - 1.6. Changes from previous versions ............................ 4 - 2. Compressed representation overview ............................. 4 - 3. Detailed specification ......................................... 5 - 3.1. Overall conventions ....................................... 5 - 3.1.1. Packing into bytes .................................. 5 - 3.2. Compressed block format ................................... 6 - 3.2.1. Synopsis of prefix and Huffman coding ............... 6 - 3.2.2. Use of Huffman coding in the "deflate" format ....... 7 - 3.2.3. Details of block format ............................. 9 - 3.2.4. Non-compressed blocks (BTYPE=00) ................... 11 - 3.2.5. Compressed blocks (length and distance codes) ...... 11 - 3.2.6. Compression with fixed Huffman codes (BTYPE=01) .... 12 - 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) .. 13 - 3.3. Compliance ............................................... 14 - 4. Compression algorithm details ................................. 14 - 5. References .................................................... 16 - 6. Security Considerations ....................................... 16 - 7. Source code ................................................... 16 - 8. Acknowledgements .............................................. 16 - 9. Author's Address .............................................. 17 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - * Can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a - priori bounded amount of intermediate storage, and hence - can be used in data communications or similar structures - such as Unix filters; - * Compresses data with efficiency comparable to the best - currently available general-purpose compression methods, - and in particular considerably better than the "compress" - program; - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely; - - - -Deutsch Informational [Page 2] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - * Is compatible with the file format produced by the current - widely used gzip utility, in that conforming decompressors - will be able to read data produced by the existing gzip - compressor. - - The data format defined by this specification does not attempt to: - - * Allow random access to compressed data; - * Compress specialized data (e.g., raster graphics) as well - as the best currently available specialized algorithms. - - A simple counting argument shows that no lossless compression - algorithm can compress every possible input data set. For the - format defined here, the worst case expansion is 5 bytes per 32K- - byte block, i.e., a size increase of 0.015% for large data sets. - English text usually compresses by a factor of 2.5 to 3; - executable files usually compress somewhat less; graphical data - such as raster images may compress much more. - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into "deflate" format and/or decompress data from - "deflate" format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. Familiarity with the technique of Huffman coding - is helpful but not required. - - 1.3. Scope - - The specification specifies a method for representing a sequence - of bytes as a (usually shorter) sequence of bits, and a method for - packing the latter bit sequence into bytes. - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any data set that conforms to all - the specifications presented here; a compliant compressor must - produce data sets that conform to all the specifications presented - here. - - 1.5. Definitions of terms and conventions used - - Byte: 8 bits stored or transmitted as a unit (same as an octet). - For this specification, a byte is exactly 8 bits, even on machines - - - -Deutsch Informational [Page 3] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - which store a character on a number of bits different from eight. - See below, for the numbering of bits within a byte. - - String: a sequence of arbitrary bytes. - - 1.6. Changes from previous versions - - There have been no technical changes to the deflate format since - version 1.1 of this specification. In version 1.2, some - terminology was changed. Version 1.3 is a conversion of the - specification to RFC style. - -2. Compressed representation overview - - A compressed data set consists of a series of blocks, corresponding - to successive blocks of input data. The block sizes are arbitrary, - except that non-compressible blocks are limited to 65,535 bytes. - - Each block is compressed using a combination of the LZ77 algorithm - and Huffman coding. The Huffman trees for each block are independent - of those for previous or subsequent blocks; the LZ77 algorithm may - use a reference to a duplicated string occurring in a previous block, - up to 32K input bytes before. - - Each block consists of two parts: a pair of Huffman code trees that - describe the representation of the compressed data part, and a - compressed data part. (The Huffman trees themselves are compressed - using Huffman encoding.) The compressed data consists of a series of - elements of two types: literal bytes (of strings that have not been - detected as duplicated within the previous 32K input bytes), and - pointers to duplicated strings, where a pointer is represented as a - pair . The representation used in the - "deflate" format limits distances to 32K bytes and lengths to 258 - bytes, but does not limit the size of a block, except for - uncompressible blocks, which are limited as noted above. - - Each type of value (literals, distances, and lengths) in the - compressed data is represented using a Huffman code, using one code - tree for literals and lengths and a separate code tree for distances. - The code trees for each block appear in a compact form just before - the compressed data for that block. - - - - - - - - - - -Deutsch Informational [Page 4] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -3. Detailed specification - - 3.1. Overall conventions In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the least-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00001000|00000010| - +--------+--------+ - ^ ^ - | | - | + more significant byte = 2 x 256 - + less significant byte = 8 - - 3.1.1. Packing into bytes - - This document does not address the issue of the order in which - bits of a byte are transmitted on a bit-sequential medium, - since the final data format described here is byte- rather than - - - -Deutsch Informational [Page 5] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - bit-oriented. However, we describe the compressed block format - in below, as a sequence of data elements of various bit - lengths, not a sequence of bytes. We must therefore specify - how to pack these data elements into bytes to form the final - compressed byte sequence: - - * Data elements are packed into bytes in order of - increasing bit number within the byte, i.e., starting - with the least-significant bit of the byte. - * Data elements other than Huffman codes are packed - starting with the least-significant bit of the data - element. - * Huffman codes are packed starting with the most- - significant bit of the code. - - In other words, if one were to print out the compressed data as - a sequence of bytes, starting with the first byte at the - *right* margin and proceeding to the *left*, with the most- - significant bit of each byte on the left as usual, one would be - able to parse the result from right to left, with fixed-width - elements in the correct MSB-to-LSB order and Huffman codes in - bit-reversed order (i.e., with the first bit of the code in the - relative LSB position). - - 3.2. Compressed block format - - 3.2.1. Synopsis of prefix and Huffman coding - - Prefix coding represents symbols from an a priori known - alphabet by bit sequences (codes), one code for each symbol, in - a manner such that different symbols may be represented by bit - sequences of different lengths, but a parser can always parse - an encoded string unambiguously symbol-by-symbol. - - We define a prefix code in terms of a binary tree in which the - two edges descending from each non-leaf node are labeled 0 and - 1 and in which the leaf nodes correspond one-for-one with (are - labeled with) the symbols of the alphabet; then the code for a - symbol is the sequence of 0's and 1's on the edges leading from - the root to the leaf labeled with that symbol. For example: - - - - - - - - - - - -Deutsch Informational [Page 6] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - /\ Symbol Code - 0 1 ------ ---- - / \ A 00 - /\ B B 1 - 0 1 C 011 - / \ D 010 - A /\ - 0 1 - / \ - D C - - A parser can decode the next symbol from an encoded input - stream by walking down the tree from the root, at each step - choosing the edge corresponding to the next input bit. - - Given an alphabet with known symbol frequencies, the Huffman - algorithm allows the construction of an optimal prefix code - (one which represents strings with those symbol frequencies - using the fewest bits of any possible prefix codes for that - alphabet). Such a code is called a Huffman code. (See - reference [1] in Chapter 5, references for additional - information on Huffman codes.) - - Note that in the "deflate" format, the Huffman codes for the - various alphabets must not exceed certain maximum code lengths. - This constraint complicates the algorithm for computing code - lengths from symbol frequencies. Again, see Chapter 5, - references for details. - - 3.2.2. Use of Huffman coding in the "deflate" format - - The Huffman codes used for each alphabet in the "deflate" - format have two additional rules: - - * All codes of a given bit length have lexicographically - consecutive values, in the same order as the symbols - they represent; - - * Shorter codes lexicographically precede longer codes. - - - - - - - - - - - - -Deutsch Informational [Page 7] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - We could recode the example above to follow this rule as - follows, assuming that the order of the alphabet is ABCD: - - Symbol Code - ------ ---- - A 10 - B 0 - C 110 - D 111 - - I.e., 0 precedes 10 which precedes 11x, and 110 and 111 are - lexicographically consecutive. - - Given this rule, we can define the Huffman code for an alphabet - just by giving the bit lengths of the codes for each symbol of - the alphabet in order; this is sufficient to determine the - actual codes. In our example, the code is completely defined - by the sequence of bit lengths (2, 1, 3, 3). The following - algorithm generates the codes as integers, intended to be read - from most- to least-significant bit. The code lengths are - initially in tree[I].Len; the codes are produced in - tree[I].Code. - - 1) Count the number of codes for each code length. Let - bl_count[N] be the number of codes of length N, N >= 1. - - 2) Find the numerical value of the smallest code for each - code length: - - code = 0; - bl_count[0] = 0; - for (bits = 1; bits <= MAX_BITS; bits++) { - code = (code + bl_count[bits-1]) << 1; - next_code[bits] = code; - } - - 3) Assign numerical values to all codes, using consecutive - values for all codes of the same length with the base - values determined at step 2. Codes that are never used - (which have a bit length of zero) must not be assigned a - value. - - for (n = 0; n <= max_code; n++) { - len = tree[n].Len; - if (len != 0) { - tree[n].Code = next_code[len]; - next_code[len]++; - } - - - -Deutsch Informational [Page 8] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - } - - Example: - - Consider the alphabet ABCDEFGH, with bit lengths (3, 3, 3, 3, - 3, 2, 4, 4). After step 1, we have: - - N bl_count[N] - - ----------- - 2 1 - 3 5 - 4 2 - - Step 2 computes the following next_code values: - - N next_code[N] - - ------------ - 1 0 - 2 0 - 3 2 - 4 14 - - Step 3 produces the following code values: - - Symbol Length Code - ------ ------ ---- - A 3 010 - B 3 011 - C 3 100 - D 3 101 - E 3 110 - F 2 00 - G 4 1110 - H 4 1111 - - 3.2.3. Details of block format - - Each block of compressed data begins with 3 header bits - containing the following data: - - first bit BFINAL - next 2 bits BTYPE - - Note that the header bits do not necessarily begin on a byte - boundary, since a block does not necessarily occupy an integral - number of bytes. - - - - - -Deutsch Informational [Page 9] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - BFINAL is set if and only if this is the last block of the data - set. - - BTYPE specifies how the data are compressed, as follows: - - 00 - no compression - 01 - compressed with fixed Huffman codes - 10 - compressed with dynamic Huffman codes - 11 - reserved (error) - - The only difference between the two compressed cases is how the - Huffman codes for the literal/length and distance alphabets are - defined. - - In all cases, the decoding algorithm for the actual data is as - follows: - - do - read block header from input stream. - if stored with no compression - skip any remaining bits in current partially - processed byte - read LEN and NLEN (see next section) - copy LEN bytes of data to output - otherwise - if compressed with dynamic Huffman codes - read representation of code trees (see - subsection below) - loop (until end of block code recognized) - decode literal/length value from input stream - if value < 256 - copy value (literal byte) to output stream - otherwise - if value = end of block (256) - break from loop - otherwise (value = 257..285) - decode distance from input stream - - move backwards distance bytes in the output - stream, and copy length bytes from this - position to the output stream. - end loop - while not last block - - Note that a duplicated string reference may refer to a string - in a previous block; i.e., the backward distance may cross one - or more block boundaries. However a distance cannot refer past - the beginning of the output stream. (An application using a - - - -Deutsch Informational [Page 10] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - preset dictionary might discard part of the output stream; a - distance can refer to that part of the output stream anyway) - Note also that the referenced string may overlap the current - position; for example, if the last 2 bytes decoded have values - X and Y, a string reference with - adds X,Y,X,Y,X to the output stream. - - We now specify each compression method in turn. - - 3.2.4. Non-compressed blocks (BTYPE=00) - - Any bits of input up to the next byte boundary are ignored. - The rest of the block consists of the following information: - - 0 1 2 3 4... - +---+---+---+---+================================+ - | LEN | NLEN |... LEN bytes of literal data...| - +---+---+---+---+================================+ - - LEN is the number of data bytes in the block. NLEN is the - one's complement of LEN. - - 3.2.5. Compressed blocks (length and distance codes) - - As noted above, encoded data blocks in the "deflate" format - consist of sequences of symbols drawn from three conceptually - distinct alphabets: either literal bytes, from the alphabet of - byte values (0..255), or pairs, - where the length is drawn from (3..258) and the distance is - drawn from (1..32,768). In fact, the literal and length - alphabets are merged into a single alphabet (0..285), where - values 0..255 represent literal bytes, the value 256 indicates - end-of-block, and values 257..285 represent length codes - (possibly in conjunction with extra bits following the symbol - code) as follows: - - - - - - - - - - - - - - - - -Deutsch Informational [Page 11] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - Extra Extra Extra - Code Bits Length(s) Code Bits Lengths Code Bits Length(s) - ---- ---- ------ ---- ---- ------- ---- ---- ------- - 257 0 3 267 1 15,16 277 4 67-82 - 258 0 4 268 1 17,18 278 4 83-98 - 259 0 5 269 2 19-22 279 4 99-114 - 260 0 6 270 2 23-26 280 4 115-130 - 261 0 7 271 2 27-30 281 5 131-162 - 262 0 8 272 2 31-34 282 5 163-194 - 263 0 9 273 3 35-42 283 5 195-226 - 264 0 10 274 3 43-50 284 5 227-257 - 265 1 11,12 275 3 51-58 285 0 258 - 266 1 13,14 276 3 59-66 - - The extra bits should be interpreted as a machine integer - stored with the most-significant bit first, e.g., bits 1110 - represent the value 14. - - Extra Extra Extra - Code Bits Dist Code Bits Dist Code Bits Distance - ---- ---- ---- ---- ---- ------ ---- ---- -------- - 0 0 1 10 4 33-48 20 9 1025-1536 - 1 0 2 11 4 49-64 21 9 1537-2048 - 2 0 3 12 5 65-96 22 10 2049-3072 - 3 0 4 13 5 97-128 23 10 3073-4096 - 4 1 5,6 14 6 129-192 24 11 4097-6144 - 5 1 7,8 15 6 193-256 25 11 6145-8192 - 6 2 9-12 16 7 257-384 26 12 8193-12288 - 7 2 13-16 17 7 385-512 27 12 12289-16384 - 8 3 17-24 18 8 513-768 28 13 16385-24576 - 9 3 25-32 19 8 769-1024 29 13 24577-32768 - - 3.2.6. Compression with fixed Huffman codes (BTYPE=01) - - The Huffman codes for the two alphabets are fixed, and are not - represented explicitly in the data. The Huffman code lengths - for the literal/length alphabet are: - - Lit Value Bits Codes - --------- ---- ----- - 0 - 143 8 00110000 through - 10111111 - 144 - 255 9 110010000 through - 111111111 - 256 - 279 7 0000000 through - 0010111 - 280 - 287 8 11000000 through - 11000111 - - - -Deutsch Informational [Page 12] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - The code lengths are sufficient to generate the actual codes, - as described above; we show the codes in the table for added - clarity. Literal/length values 286-287 will never actually - occur in the compressed data, but participate in the code - construction. - - Distance codes 0-31 are represented by (fixed-length) 5-bit - codes, with possible additional bits as shown in the table - shown in Paragraph 3.2.5, above. Note that distance codes 30- - 31 will never actually occur in the compressed data. - - 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) - - The Huffman codes for the two alphabets appear in the block - immediately after the header bits and before the actual - compressed data, first the literal/length code and then the - distance code. Each code is defined by a sequence of code - lengths, as discussed in Paragraph 3.2.2, above. For even - greater compactness, the code length sequences themselves are - compressed using a Huffman code. The alphabet for code lengths - is as follows: - - 0 - 15: Represent code lengths of 0 - 15 - 16: Copy the previous code length 3 - 6 times. - The next 2 bits indicate repeat length - (0 = 3, ... , 3 = 6) - Example: Codes 8, 16 (+2 bits 11), - 16 (+2 bits 10) will expand to - 12 code lengths of 8 (1 + 6 + 5) - 17: Repeat a code length of 0 for 3 - 10 times. - (3 bits of length) - 18: Repeat a code length of 0 for 11 - 138 times - (7 bits of length) - - A code length of 0 indicates that the corresponding symbol in - the literal/length or distance alphabet will not occur in the - block, and should not participate in the Huffman code - construction algorithm given earlier. If only one distance - code is used, it is encoded using one bit, not zero bits; in - this case there is a single code length of one, with one unused - code. One distance code of zero bits means that there are no - distance codes used at all (the data is all literals). - - We can now define the format of the block: - - 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) - 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) - 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) - - - -Deutsch Informational [Page 13] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - (HCLEN + 4) x 3 bits: code lengths for the code length - alphabet given just above, in the order: 16, 17, 18, - 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 - - These code lengths are interpreted as 3-bit integers - (0-7); as above, a code length of 0 means the - corresponding symbol (literal/length or distance code - length) is not used. - - HLIT + 257 code lengths for the literal/length alphabet, - encoded using the code length Huffman code - - HDIST + 1 code lengths for the distance alphabet, - encoded using the code length Huffman code - - The actual compressed data of the block, - encoded using the literal/length and distance Huffman - codes - - The literal/length symbol 256 (end of data), - encoded using the literal/length Huffman code - - The code length repeat codes can cross from HLIT + 257 to the - HDIST + 1 code lengths. In other words, all code lengths form - a single sequence of HLIT + HDIST + 258 values. - - 3.3. Compliance - - A compressor may limit further the ranges of values specified in - the previous section and still be compliant; for example, it may - limit the range of backward pointers to some value smaller than - 32K. Similarly, a compressor may limit the size of blocks so that - a compressible block fits in memory. - - A compliant decompressor must accept the full range of possible - values defined in the previous section, and must accept blocks of - arbitrary size. - -4. Compression algorithm details - - While it is the intent of this document to define the "deflate" - compressed data format without reference to any particular - compression algorithm, the format is related to the compressed - formats produced by LZ77 (Lempel-Ziv 1977, see reference [2] below); - since many variations of LZ77 are patented, it is strongly - recommended that the implementor of a compressor follow the general - algorithm presented here, which is known not to be patented per se. - The material in this section is not part of the definition of the - - - -Deutsch Informational [Page 14] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - specification per se, and a compressor need not follow it in order to - be compliant. - - The compressor terminates a block when it determines that starting a - new block with fresh trees would be useful, or when the block size - fills up the compressor's block buffer. - - The compressor uses a chained hash table to find duplicated strings, - using a hash function that operates on 3-byte sequences. At any - given point during compression, let XYZ be the next 3 input bytes to - be examined (not necessarily all different, of course). First, the - compressor examines the hash chain for XYZ. If the chain is empty, - the compressor simply writes out X as a literal byte and advances one - byte in the input. If the hash chain is not empty, indicating that - the sequence XYZ (or, if we are unlucky, some other 3 bytes with the - same hash function value) has occurred recently, the compressor - compares all strings on the XYZ hash chain with the actual input data - sequence starting at the current point, and selects the longest - match. - - The compressor searches the hash chains starting with the most recent - strings, to favor small distances and thus take advantage of the - Huffman encoding. The hash chains are singly linked. There are no - deletions from the hash chains; the algorithm simply discards matches - that are too old. To avoid a worst-case situation, very long hash - chains are arbitrarily truncated at a certain length, determined by a - run-time parameter. - - To improve overall compression, the compressor optionally defers the - selection of matches ("lazy matching"): after a match of length N has - been found, the compressor searches for a longer match starting at - the next input byte. If it finds a longer match, it truncates the - previous match to a length of one (thus producing a single literal - byte) and then emits the longer match. Otherwise, it emits the - original match, and, as described above, advances N bytes before - continuing. - - Run-time parameters also control this "lazy match" procedure. If - compression ratio is most important, the compressor attempts a - complete second search regardless of the length of the first match. - In the normal case, if the current match is "long enough", the - compressor reduces the search for a longer match, thus speeding up - the process. If speed is most important, the compressor inserts new - strings in the hash table only when no match was found, or when the - match is not "too long". This degrades the compression ratio but - saves time since there are both fewer insertions and fewer searches. - - - - - -Deutsch Informational [Page 15] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -5. References - - [1] Huffman, D. A., "A Method for the Construction of Minimum - Redundancy Codes", Proceedings of the Institute of Radio - Engineers, September 1952, Volume 40, Number 9, pp. 1098-1101. - - [2] Ziv J., Lempel A., "A Universal Algorithm for Sequential Data - Compression", IEEE Transactions on Information Theory, Vol. 23, - No. 3, pp. 337-343. - - [3] Gailly, J.-L., and Adler, M., ZLIB documentation and sources, - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [4] Gailly, J.-L., and Adler, M., GZIP documentation and sources, - available as gzip-*.tar in ftp://prep.ai.mit.edu/pub/gnu/ - - [5] Schwartz, E. S., and Kallick, B. "Generating a canonical prefix - encoding." Comm. ACM, 7,3 (Mar. 1964), pp. 166-169. - - [6] Hirschberg and Lelewer, "Efficient decoding of prefix codes," - Comm. ACM, 33,4, April 1990, pp. 449-459. - -6. Security Considerations - - Any data compression method involves the reduction of redundancy in - the data. Consequently, any corruption of the data is likely to have - severe effects and be difficult to correct. Uncompressed text, on - the other hand, will probably still be readable despite the presence - of some corrupted bytes. - - It is recommended that systems using this data format provide some - means of validating the integrity of the compressed data. See - reference [3], for example. - -7. Source code - - Source code for a C language implementation of a "deflate" compliant - compressor and decompressor is available within the zlib package at - ftp://ftp.uu.net/pub/archiving/zip/zlib/. - -8. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Phil Katz designed the deflate format. Jean-Loup Gailly and Mark - Adler wrote the related software described in this specification. - Glenn Randers-Pehrson converted this document to RFC and HTML format. - - - -Deutsch Informational [Page 16] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -9. Author's Address - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - Questions about the technical content of this specification can be - sent by email to: - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to: - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Deutsch Informational [Page 17] - diff --git a/deps/zlib/doc/rfc1952.txt b/deps/zlib/doc/rfc1952.txt deleted file mode 100644 index a8e51b4567fd49..00000000000000 --- a/deps/zlib/doc/rfc1952.txt +++ /dev/null @@ -1,675 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1952 Aladdin Enterprises -Category: Informational May 1996 - - - GZIP file format specification version 4.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format that is - compatible with the widely used GZIP utility. The format includes a - cyclic redundancy check value for detecting data corruption. The - format presently uses the DEFLATE method of compression but can be - easily extended to use other compression methods. The format can be - implemented readily in a manner not covered by patents. - - - - - - - - - - -Deutsch Informational [Page 1] - -RFC 1952 GZIP File Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................. 3 - 1.6. Changes from previous versions ............................ 3 - 2. Detailed specification ......................................... 4 - 2.1. Overall conventions ....................................... 4 - 2.2. File format ............................................... 5 - 2.3. Member format ............................................. 5 - 2.3.1. Member header and trailer ........................... 6 - 2.3.1.1. Extra field ................................... 8 - 2.3.1.2. Compliance .................................... 9 - 3. References .................................................. 9 - 4. Security Considerations .................................... 10 - 5. Acknowledgements ........................................... 10 - 6. Author's Address ........................................... 10 - 7. Appendix: Jean-Loup Gailly's gzip utility .................. 11 - 8. Appendix: Sample CRC Code .................................. 11 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - * Can compress or decompress a data stream (as opposed to a - randomly accessible file) to produce another data stream, - using only an a priori bounded amount of intermediate - storage, and hence can be used in data communications or - similar structures such as Unix filters; - * Compresses data with efficiency comparable to the best - currently available general-purpose compression methods, - and in particular considerably better than the "compress" - program; - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely; - * Is compatible with the file format produced by the current - widely used gzip utility, in that conforming decompressors - will be able to read data produced by the existing gzip - compressor. - - - - -Deutsch Informational [Page 2] - -RFC 1952 GZIP File Format Specification May 1996 - - - The data format defined by this specification does not attempt to: - - * Provide random access to compressed data; - * Compress specialized data (e.g., raster graphics) as well as - the best currently available specialized algorithms. - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into gzip format and/or decompress data from gzip - format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. - - 1.3. Scope - - The specification specifies a compression method and a file format - (the latter assuming only that a file can store a sequence of - arbitrary bytes). It does not specify any particular interface to - a file system or anything about character sets or encodings - (except for file names and comments, which are optional). - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any file that conforms to all the - specifications presented here; a compliant compressor must produce - files that conform to all the specifications presented here. The - material in the appendices is not part of the specification per se - and is not relevant to compliance. - - 1.5. Definitions of terms and conventions used - - byte: 8 bits stored or transmitted as a unit (same as an octet). - (For this specification, a byte is exactly 8 bits, even on - machines which store a character on a number of bits different - from 8.) See below for the numbering of bits within a byte. - - 1.6. Changes from previous versions - - There have been no technical changes to the gzip format since - version 4.1 of this specification. In version 4.2, some - terminology was changed, and the sample CRC code was rewritten for - clarity and to eliminate the requirement for the caller to do pre- - and post-conditioning. Version 4.3 is a conversion of the - specification to RFC style. - - - -Deutsch Informational [Page 3] - -RFC 1952 GZIP File Format Specification May 1996 - - -2. Detailed specification - - 2.1. Overall conventions - - In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - This document does not address the issue of the order in which - bits of a byte are transmitted on a bit-sequential medium, since - the data format described here is byte- rather than bit-oriented. - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the least-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00001000|00000010| - +--------+--------+ - ^ ^ - | | - | + more significant byte = 2 x 256 - + less significant byte = 8 - - - -Deutsch Informational [Page 4] - -RFC 1952 GZIP File Format Specification May 1996 - - - 2.2. File format - - A gzip file consists of a series of "members" (compressed data - sets). The format of each member is specified in the following - section. The members simply appear one after another in the file, - with no additional information before, between, or after them. - - 2.3. Member format - - Each member has the following structure: - - +---+---+---+---+---+---+---+---+---+---+ - |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) - +---+---+---+---+---+---+---+---+---+---+ - - (if FLG.FEXTRA set) - - +---+---+=================================+ - | XLEN |...XLEN bytes of "extra field"...| (more-->) - +---+---+=================================+ - - (if FLG.FNAME set) - - +=========================================+ - |...original file name, zero-terminated...| (more-->) - +=========================================+ - - (if FLG.FCOMMENT set) - - +===================================+ - |...file comment, zero-terminated...| (more-->) - +===================================+ - - (if FLG.FHCRC set) - - +---+---+ - | CRC16 | - +---+---+ - - +=======================+ - |...compressed blocks...| (more-->) - +=======================+ - - 0 1 2 3 4 5 6 7 - +---+---+---+---+---+---+---+---+ - | CRC32 | ISIZE | - +---+---+---+---+---+---+---+---+ - - - - -Deutsch Informational [Page 5] - -RFC 1952 GZIP File Format Specification May 1996 - - - 2.3.1. Member header and trailer - - ID1 (IDentification 1) - ID2 (IDentification 2) - These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 - (0x8b, \213), to identify the file as being in gzip format. - - CM (Compression Method) - This identifies the compression method used in the file. CM - = 0-7 are reserved. CM = 8 denotes the "deflate" - compression method, which is the one customarily used by - gzip and which is documented elsewhere. - - FLG (FLaGs) - This flag byte is divided into individual bits as follows: - - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - - If FTEXT is set, the file is probably ASCII text. This is - an optional indication, which the compressor may set by - checking a small amount of the input data to see whether any - non-ASCII characters are present. In case of doubt, FTEXT - is cleared, indicating binary data. For systems which have - different file formats for ascii text and binary data, the - decompressor can use FTEXT to choose the appropriate format. - We deliberately do not specify the algorithm used to set - this bit, since a compressor always has the option of - leaving it cleared and a decompressor always has the option - of ignoring it and letting some other program handle issues - of data conversion. - - If FHCRC is set, a CRC16 for the gzip header is present, - immediately before the compressed data. The CRC16 consists - of the two least significant bytes of the CRC32 for all - bytes of the gzip header up to and not including the CRC16. - [The FHCRC bit was never set by versions of gzip up to - 1.2.4, even though it was documented with a different - meaning in gzip 1.2.4.] - - If FEXTRA is set, optional extra fields are present, as - described in a following section. - - - -Deutsch Informational [Page 6] - -RFC 1952 GZIP File Format Specification May 1996 - - - If FNAME is set, an original file name is present, - terminated by a zero byte. The name must consist of ISO - 8859-1 (LATIN-1) characters; on operating systems using - EBCDIC or any other character set for file names, the name - must be translated to the ISO LATIN-1 character set. This - is the original name of the file being compressed, with any - directory components removed, and, if the file being - compressed is on a file system with case insensitive names, - forced to lower case. There is no original file name if the - data was compressed from a source other than a named file; - for example, if the source was stdin on a Unix system, there - is no file name. - - If FCOMMENT is set, a zero-terminated file comment is - present. This comment is not interpreted; it is only - intended for human consumption. The comment must consist of - ISO 8859-1 (LATIN-1) characters. Line breaks should be - denoted by a single line feed character (10 decimal). - - Reserved FLG bits must be zero. - - MTIME (Modification TIME) - This gives the most recent modification time of the original - file being compressed. The time is in Unix format, i.e., - seconds since 00:00:00 GMT, Jan. 1, 1970. (Note that this - may cause problems for MS-DOS and other systems that use - local rather than Universal time.) If the compressed data - did not come from a file, MTIME is set to the time at which - compression started. MTIME = 0 means no time stamp is - available. - - XFL (eXtra FLags) - These flags are available for use by specific compression - methods. The "deflate" method (CM = 8) sets these flags as - follows: - - XFL = 2 - compressor used maximum compression, - slowest algorithm - XFL = 4 - compressor used fastest algorithm - - OS (Operating System) - This identifies the type of file system on which compression - took place. This may be useful in determining end-of-line - convention for text files. The currently defined values are - as follows: - - - - - - -Deutsch Informational [Page 7] - -RFC 1952 GZIP File Format Specification May 1996 - - - 0 - FAT filesystem (MS-DOS, OS/2, NT/Win32) - 1 - Amiga - 2 - VMS (or OpenVMS) - 3 - Unix - 4 - VM/CMS - 5 - Atari TOS - 6 - HPFS filesystem (OS/2, NT) - 7 - Macintosh - 8 - Z-System - 9 - CP/M - 10 - TOPS-20 - 11 - NTFS filesystem (NT) - 12 - QDOS - 13 - Acorn RISCOS - 255 - unknown - - XLEN (eXtra LENgth) - If FLG.FEXTRA is set, this gives the length of the optional - extra field. See below for details. - - CRC32 (CRC-32) - This contains a Cyclic Redundancy Check value of the - uncompressed data computed according to CRC-32 algorithm - used in the ISO 3309 standard and in section 8.1.1.6.2 of - ITU-T recommendation V.42. (See http://www.iso.ch for - ordering ISO documents. See gopher://info.itu.ch for an - online version of ITU-T V.42.) - - ISIZE (Input SIZE) - This contains the size of the original (uncompressed) input - data modulo 2^32. - - 2.3.1.1. Extra field - - If the FLG.FEXTRA bit is set, an "extra field" is present in - the header, with total length XLEN bytes. It consists of a - series of subfields, each of the form: - - +---+---+---+---+==================================+ - |SI1|SI2| LEN |... LEN bytes of subfield data ...| - +---+---+---+---+==================================+ - - SI1 and SI2 provide a subfield ID, typically two ASCII letters - with some mnemonic value. Jean-Loup Gailly - is maintaining a registry of subfield - IDs; please send him any subfield ID you wish to use. Subfield - IDs with SI2 = 0 are reserved for future use. The following - IDs are currently defined: - - - -Deutsch Informational [Page 8] - -RFC 1952 GZIP File Format Specification May 1996 - - - SI1 SI2 Data - ---------- ---------- ---- - 0x41 ('A') 0x70 ('P') Apollo file type information - - LEN gives the length of the subfield data, excluding the 4 - initial bytes. - - 2.3.1.2. Compliance - - A compliant compressor must produce files with correct ID1, - ID2, CM, CRC32, and ISIZE, but may set all the other fields in - the fixed-length part of the header to default values (255 for - OS, 0 for all others). The compressor must set all reserved - bits to zero. - - A compliant decompressor must check ID1, ID2, and CM, and - provide an error indication if any of these have incorrect - values. It must examine FEXTRA/XLEN, FNAME, FCOMMENT and FHCRC - at least so it can skip over the optional fields if they are - present. It need not examine any other part of the header or - trailer; in particular, a decompressor may ignore FTEXT and OS - and always produce binary output, and still be compliant. A - compliant decompressor must give an error indication if any - reserved bit is non-zero, since such a bit could indicate the - presence of a new field that would cause subsequent data to be - interpreted incorrectly. - -3. References - - [1] "Information Processing - 8-bit single-byte coded graphic - character sets - Part 1: Latin alphabet No.1" (ISO 8859-1:1987). - The ISO 8859-1 (Latin-1) character set is a superset of 7-bit - ASCII. Files defining this character set are available as - iso_8859-1.* in ftp://ftp.uu.net/graphics/png/documents/ - - [2] ISO 3309 - - [3] ITU-T recommendation V.42 - - [4] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [5] Gailly, J.-L., GZIP documentation, available as gzip-*.tar in - ftp://prep.ai.mit.edu/pub/gnu/ - - [6] Sarwate, D.V., "Computation of Cyclic Redundancy Checks via Table - Look-Up", Communications of the ACM, 31(8), pp.1008-1013. - - - - -Deutsch Informational [Page 9] - -RFC 1952 GZIP File Format Specification May 1996 - - - [7] Schwaderer, W.D., "CRC Calculation", April 85 PC Tech Journal, - pp.118-133. - - [8] ftp://ftp.adelaide.edu.au/pub/rocksoft/papers/crc_v3.txt, - describing the CRC concept. - -4. Security Considerations - - Any data compression method involves the reduction of redundancy in - the data. Consequently, any corruption of the data is likely to have - severe effects and be difficult to correct. Uncompressed text, on - the other hand, will probably still be readable despite the presence - of some corrupted bytes. - - It is recommended that systems using this data format provide some - means of validating the integrity of the compressed data, such as by - setting and checking the CRC-32 check value. - -5. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Jean-Loup Gailly designed the gzip format and wrote, with Mark Adler, - the related software described in this specification. Glenn - Randers-Pehrson converted this document to RFC and HTML format. - -6. Author's Address - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - Questions about the technical content of this specification can be - sent by email to: - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to: - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - -Deutsch Informational [Page 10] - -RFC 1952 GZIP File Format Specification May 1996 - - -7. Appendix: Jean-Loup Gailly's gzip utility - - The most widely used implementation of gzip compression, and the - original documentation on which this specification is based, were - created by Jean-Loup Gailly . Since this - implementation is a de facto standard, we mention some more of its - features here. Again, the material in this section is not part of - the specification per se, and implementations need not follow it to - be compliant. - - When compressing or decompressing a file, gzip preserves the - protection, ownership, and modification time attributes on the local - file system, since there is no provision for representing protection - attributes in the gzip file format itself. Since the file format - includes a modification time, the gzip decompressor provides a - command line switch that assigns the modification time from the file, - rather than the local modification time of the compressed input, to - the decompressed output. - -8. Appendix: Sample CRC Code - - The following sample code represents a practical implementation of - the CRC (Cyclic Redundancy Check). (See also ISO 3309 and ITU-T V.42 - for a formal specification.) - - The sample code is in the ANSI C programming language. Non C users - may find it easier to read with these hints: - - & Bitwise AND operator. - ^ Bitwise exclusive-OR operator. - >> Bitwise right shift operator. When applied to an - unsigned quantity, as here, right shift inserts zero - bit(s) at the left. - ! Logical NOT operator. - ++ "n++" increments the variable n. - 0xNNN 0x introduces a hexadecimal (base 16) constant. - Suffix L indicates a long value (at least 32 bits). - - /* Table of CRCs of all 8-bit messages. */ - unsigned long crc_table[256]; - - /* Flag: has the table been computed? Initially false. */ - int crc_table_computed = 0; - - /* Make the table for a fast CRC. */ - void make_crc_table(void) - { - unsigned long c; - - - -Deutsch Informational [Page 11] - -RFC 1952 GZIP File Format Specification May 1996 - - - int n, k; - for (n = 0; n < 256; n++) { - c = (unsigned long) n; - for (k = 0; k < 8; k++) { - if (c & 1) { - c = 0xedb88320L ^ (c >> 1); - } else { - c = c >> 1; - } - } - crc_table[n] = c; - } - crc_table_computed = 1; - } - - /* - Update a running crc with the bytes buf[0..len-1] and return - the updated crc. The crc should be initialized to zero. Pre- and - post-conditioning (one's complement) is performed within this - function so it shouldn't be done by the caller. Usage example: - - unsigned long crc = 0L; - - while (read_buffer(buffer, length) != EOF) { - crc = update_crc(crc, buffer, length); - } - if (crc != original_crc) error(); - */ - unsigned long update_crc(unsigned long crc, - unsigned char *buf, int len) - { - unsigned long c = crc ^ 0xffffffffL; - int n; - - if (!crc_table_computed) - make_crc_table(); - for (n = 0; n < len; n++) { - c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); - } - return c ^ 0xffffffffL; - } - - /* Return the CRC of the bytes buf[0..len-1]. */ - unsigned long crc(unsigned char *buf, int len) - { - return update_crc(0L, buf, len); - } - - - - -Deutsch Informational [Page 12] - diff --git a/deps/zlib/doc/txtvsbin.txt b/deps/zlib/doc/txtvsbin.txt deleted file mode 100644 index 3d0f0634f72e64..00000000000000 --- a/deps/zlib/doc/txtvsbin.txt +++ /dev/null @@ -1,107 +0,0 @@ -A Fast Method for Identifying Plain Text Files -============================================== - - -Introduction ------------- - -Given a file coming from an unknown source, it is sometimes desirable -to find out whether the format of that file is plain text. Although -this may appear like a simple task, a fully accurate detection of the -file type requires heavy-duty semantic analysis on the file contents. -It is, however, possible to obtain satisfactory results by employing -various heuristics. - -Previous versions of PKZip and other zip-compatible compression tools -were using a crude detection scheme: if more than 80% (4/5) of the bytes -found in a certain buffer are within the range [7..127], the file is -labeled as plain text, otherwise it is labeled as binary. A prominent -limitation of this scheme is the restriction to Latin-based alphabets. -Other alphabets, like Greek, Cyrillic or Asian, make extensive use of -the bytes within the range [128..255], and texts using these alphabets -are most often misidentified by this scheme; in other words, the rate -of false negatives is sometimes too high, which means that the recall -is low. Another weakness of this scheme is a reduced precision, due to -the false positives that may occur when binary files containing large -amounts of textual characters are misidentified as plain text. - -In this article we propose a new, simple detection scheme that features -a much increased precision and a near-100% recall. This scheme is -designed to work on ASCII, Unicode and other ASCII-derived alphabets, -and it handles single-byte encodings (ISO-8859, MacRoman, KOI8, etc.) -and variable-sized encodings (ISO-2022, UTF-8, etc.). Wider encodings -(UCS-2/UTF-16 and UCS-4/UTF-32) are not handled, however. - - -The Algorithm -------------- - -The algorithm works by dividing the set of bytecodes [0..255] into three -categories: -- The white list of textual bytecodes: - 9 (TAB), 10 (LF), 13 (CR), 32 (SPACE) to 255. -- The gray list of tolerated bytecodes: - 7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB), 27 (ESC). -- The black list of undesired, non-textual bytecodes: - 0 (NUL) to 6, 14 to 31. - -If a file contains at least one byte that belongs to the white list and -no byte that belongs to the black list, then the file is categorized as -plain text; otherwise, it is categorized as binary. (The boundary case, -when the file is empty, automatically falls into the latter category.) - - -Rationale ---------- - -The idea behind this algorithm relies on two observations. - -The first observation is that, although the full range of 7-bit codes -[0..127] is properly specified by the ASCII standard, most control -characters in the range [0..31] are not used in practice. The only -widely-used, almost universally-portable control codes are 9 (TAB), -10 (LF) and 13 (CR). There are a few more control codes that are -recognized on a reduced range of platforms and text viewers/editors: -7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB) and 27 (ESC); but these -codes are rarely (if ever) used alone, without being accompanied by -some printable text. Even the newer, portable text formats such as -XML avoid using control characters outside the list mentioned here. - -The second observation is that most of the binary files tend to contain -control characters, especially 0 (NUL). Even though the older text -detection schemes observe the presence of non-ASCII codes from the range -[128..255], the precision rarely has to suffer if this upper range is -labeled as textual, because the files that are genuinely binary tend to -contain both control characters and codes from the upper range. On the -other hand, the upper range needs to be labeled as textual, because it -is used by virtually all ASCII extensions. In particular, this range is -used for encoding non-Latin scripts. - -Since there is no counting involved, other than simply observing the -presence or the absence of some byte values, the algorithm produces -consistent results, regardless what alphabet encoding is being used. -(If counting were involved, it could be possible to obtain different -results on a text encoded, say, using ISO-8859-16 versus UTF-8.) - -There is an extra category of plain text files that are "polluted" with -one or more black-listed codes, either by mistake or by peculiar design -considerations. In such cases, a scheme that tolerates a small fraction -of black-listed codes would provide an increased recall (i.e. more true -positives). This, however, incurs a reduced precision overall, since -false positives are more likely to appear in binary files that contain -large chunks of textual data. Furthermore, "polluted" plain text should -be regarded as binary by general-purpose text detection schemes, because -general-purpose text processing algorithms might not be applicable. -Under this premise, it is safe to say that our detection method provides -a near-100% recall. - -Experiments have been run on many files coming from various platforms -and applications. We tried plain text files, system logs, source code, -formatted office documents, compiled object code, etc. The results -confirm the optimistic assumptions about the capabilities of this -algorithm. - - --- -Cosmin Truta -Last updated: 2006-May-28 diff --git a/deps/zlib/examples/README.examples b/deps/zlib/examples/README.examples deleted file mode 100644 index 56a31714e566aa..00000000000000 --- a/deps/zlib/examples/README.examples +++ /dev/null @@ -1,49 +0,0 @@ -This directory contains examples of the use of zlib and other relevant -programs and documentation. - -enough.c - calculation and justification of ENOUGH parameter in inftrees.h - - calculates the maximum table space used in inflate tree - construction over all possible Huffman codes - -fitblk.c - compress just enough input to nearly fill a requested output size - - zlib isn't designed to do this, but fitblk does it anyway - -gun.c - uncompress a gzip file - - illustrates the use of inflateBack() for high speed file-to-file - decompression using call-back functions - - is approximately twice as fast as gzip -d - - also provides Unix uncompress functionality, again twice as fast - -gzappend.c - append to a gzip file - - illustrates the use of the Z_BLOCK flush parameter for inflate() - - illustrates the use of deflatePrime() to start at any bit - -gzjoin.c - join gzip files without recalculating the crc or recompressing - - illustrates the use of the Z_BLOCK flush parameter for inflate() - - illustrates the use of crc32_combine() - -gzlog.c -gzlog.h - efficiently and robustly maintain a message log file in gzip format - - illustrates use of raw deflate, Z_PARTIAL_FLUSH, deflatePrime(), - and deflateSetDictionary() - - illustrates use of a gzip header extra field - -zlib_how.html - painfully comprehensive description of zpipe.c (see below) - - describes in excruciating detail the use of deflate() and inflate() - -zpipe.c - reads and writes zlib streams from stdin to stdout - - illustrates the proper use of deflate() and inflate() - - deeply commented in zlib_how.html (see above) - -zran.c - index a zlib or gzip stream and randomly access it - - illustrates the use of Z_BLOCK, inflatePrime(), and - inflateSetDictionary() to provide random access diff --git a/deps/zlib/examples/enough.c b/deps/zlib/examples/enough.c deleted file mode 100644 index b991144305253c..00000000000000 --- a/deps/zlib/examples/enough.c +++ /dev/null @@ -1,572 +0,0 @@ -/* enough.c -- determine the maximum size of inflate's Huffman code tables over - * all possible valid and complete Huffman codes, subject to a length limit. - * Copyright (C) 2007, 2008, 2012 Mark Adler - * Version 1.4 18 August 2012 Mark Adler - */ - -/* Version history: - 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4) - 1.1 4 Jan 2007 Use faster incremental table usage computation - Prune examine() search on previously visited states - 1.2 5 Jan 2007 Comments clean up - As inflate does, decrease root for short codes - Refuse cases where inflate would increase root - 1.3 17 Feb 2008 Add argument for initial root table size - Fix bug for initial root table size == max - 1 - Use a macro to compute the history index - 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!) - Clean up comparisons of different types - Clean up code indentation - */ - -/* - Examine all possible Huffman codes for a given number of symbols and a - maximum code length in bits to determine the maximum table size for zilb's - inflate. Only complete Huffman codes are counted. - - Two codes are considered distinct if the vectors of the number of codes per - length are not identical. So permutations of the symbol assignments result - in the same code for the counting, as do permutations of the assignments of - the bit values to the codes (i.e. only canonical codes are counted). - - We build a code from shorter to longer lengths, determining how many symbols - are coded at each length. At each step, we have how many symbols remain to - be coded, what the last code length used was, and how many bit patterns of - that length remain unused. Then we add one to the code length and double the - number of unused patterns to graduate to the next code length. We then - assign all portions of the remaining symbols to that code length that - preserve the properties of a correct and eventually complete code. Those - properties are: we cannot use more bit patterns than are available; and when - all the symbols are used, there are exactly zero possible bit patterns - remaining. - - The inflate Huffman decoding algorithm uses two-level lookup tables for - speed. There is a single first-level table to decode codes up to root bits - in length (root == 9 in the current inflate implementation). The table - has 1 << root entries and is indexed by the next root bits of input. Codes - shorter than root bits have replicated table entries, so that the correct - entry is pointed to regardless of the bits that follow the short code. If - the code is longer than root bits, then the table entry points to a second- - level table. The size of that table is determined by the longest code with - that root-bit prefix. If that longest code has length len, then the table - has size 1 << (len - root), to index the remaining bits in that set of - codes. Each subsequent root-bit prefix then has its own sub-table. The - total number of table entries required by the code is calculated - incrementally as the number of codes at each bit length is populated. When - all of the codes are shorter than root bits, then root is reduced to the - longest code length, resulting in a single, smaller, one-level table. - - The inflate algorithm also provides for small values of root (relative to - the log2 of the number of symbols), where the shortest code has more bits - than root. In that case, root is increased to the length of the shortest - code. This program, by design, does not handle that case, so it is verified - that the number of symbols is less than 2^(root + 1). - - In order to speed up the examination (by about ten orders of magnitude for - the default arguments), the intermediate states in the build-up of a code - are remembered and previously visited branches are pruned. The memory - required for this will increase rapidly with the total number of symbols and - the maximum code length in bits. However this is a very small price to pay - for the vast speedup. - - First, all of the possible Huffman codes are counted, and reachable - intermediate states are noted by a non-zero count in a saved-results array. - Second, the intermediate states that lead to (root + 1) bit or longer codes - are used to look at all sub-codes from those junctures for their inflate - memory usage. (The amount of memory used is not affected by the number of - codes of root bits or less in length.) Third, the visited states in the - construction of those sub-codes and the associated calculation of the table - size is recalled in order to avoid recalculating from the same juncture. - Beginning the code examination at (root + 1) bit codes, which is enabled by - identifying the reachable nodes, accounts for about six of the orders of - magnitude of improvement for the default arguments. About another four - orders of magnitude come from not revisiting previous states. Out of - approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes - need to be examined to cover all of the possible table memory usage cases - for the default arguments of 286 symbols limited to 15-bit codes. - - Note that an unsigned long long type is used for counting. It is quite easy - to exceed the capacity of an eight-byte integer with a large number of - symbols and a large maximum code length, so multiple-precision arithmetic - would need to replace the unsigned long long arithmetic in that case. This - program will abort if an overflow occurs. The big_t type identifies where - the counting takes place. - - An unsigned long long type is also used for calculating the number of - possible codes remaining at the maximum length. This limits the maximum - code length to the number of bits in a long long minus the number of bits - needed to represent the symbols in a flat code. The code_t type identifies - where the bit pattern counting takes place. - */ - -#include -#include -#include -#include - -#define local static - -/* special data types */ -typedef unsigned long long big_t; /* type for code counting */ -typedef unsigned long long code_t; /* type for bit pattern counting */ -struct tab { /* type for been here check */ - size_t len; /* length of bit vector in char's */ - char *vec; /* allocated bit vector */ -}; - -/* The array for saving results, num[], is indexed with this triplet: - - syms: number of symbols remaining to code - left: number of available bit patterns at length len - len: number of bits in the codes currently being assigned - - Those indices are constrained thusly when saving results: - - syms: 3..totsym (totsym == total symbols to code) - left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6) - len: 1..max - 1 (max == maximum code length in bits) - - syms == 2 is not saved since that immediately leads to a single code. left - must be even, since it represents the number of available bit patterns at - the current length, which is double the number at the previous length. - left ends at syms-1 since left == syms immediately results in a single code. - (left > sym is not allowed since that would result in an incomplete code.) - len is less than max, since the code completes immediately when len == max. - - The offset into the array is calculated for the three indices with the - first one (syms) being outermost, and the last one (len) being innermost. - We build the array with length max-1 lists for the len index, with syms-3 - of those for each symbol. There are totsym-2 of those, with each one - varying in length as a function of sym. See the calculation of index in - count() for the index, and the calculation of size in main() for the size - of the array. - - For the deflate example of 286 symbols limited to 15-bit codes, the array - has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than - half of the space allocated for saved results is actually used -- not all - possible triplets are reached in the generation of valid Huffman codes. - */ - -/* The array for tracking visited states, done[], is itself indexed identically - to the num[] array as described above for the (syms, left, len) triplet. - Each element in the array is further indexed by the (mem, rem) doublet, - where mem is the amount of inflate table space used so far, and rem is the - remaining unused entries in the current inflate sub-table. Each indexed - element is simply one bit indicating whether the state has been visited or - not. Since the ranges for mem and rem are not known a priori, each bit - vector is of a variable size, and grows as needed to accommodate the visited - states. mem and rem are used to calculate a single index in a triangular - array. Since the range of mem is expected in the default case to be about - ten times larger than the range of rem, the array is skewed to reduce the - memory usage, with eight times the range for mem than for rem. See the - calculations for offset and bit in beenhere() for the details. - - For the deflate example of 286 symbols limited to 15-bit codes, the bit - vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[] - array itself. - */ - -/* Globals to avoid propagating constants or constant pointers recursively */ -local int max; /* maximum allowed bit length for the codes */ -local int root; /* size of base code table in bits */ -local int large; /* largest code table so far */ -local size_t size; /* number of elements in num and done */ -local int *code; /* number of symbols assigned to each bit length */ -local big_t *num; /* saved results array for code counting */ -local struct tab *done; /* states already evaluated array */ - -/* Index function for num[] and done[] */ -#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1) - -/* Free allocated space. Uses globals code, num, and done. */ -local void cleanup(void) -{ - size_t n; - - if (done != NULL) { - for (n = 0; n < size; n++) - if (done[n].len) - free(done[n].vec); - free(done); - } - if (num != NULL) - free(num); - if (code != NULL) - free(code); -} - -/* Return the number of possible Huffman codes using bit patterns of lengths - len through max inclusive, coding syms symbols, with left bit patterns of - length len unused -- return -1 if there is an overflow in the counting. - Keep a record of previous results in num to prevent repeating the same - calculation. Uses the globals max and num. */ -local big_t count(int syms, int len, int left) -{ - big_t sum; /* number of possible codes from this juncture */ - big_t got; /* value returned from count() */ - int least; /* least number of syms to use at this juncture */ - int most; /* most number of syms to use at this juncture */ - int use; /* number of bit patterns to use in next call */ - size_t index; /* index of this case in *num */ - - /* see if only one possible code */ - if (syms == left) - return 1; - - /* note and verify the expected state */ - assert(syms > left && left > 0 && len < max); - - /* see if we've done this one already */ - index = INDEX(syms, left, len); - got = num[index]; - if (got) - return got; /* we have -- return the saved result */ - - /* we need to use at least this many bit patterns so that the code won't be - incomplete at the next length (more bit patterns than symbols) */ - least = (left << 1) - syms; - if (least < 0) - least = 0; - - /* we can use at most this many bit patterns, lest there not be enough - available for the remaining symbols at the maximum length (if there were - no limit to the code length, this would become: most = left - 1) */ - most = (((code_t)left << (max - len)) - syms) / - (((code_t)1 << (max - len)) - 1); - - /* count all possible codes from this juncture and add them up */ - sum = 0; - for (use = least; use <= most; use++) { - got = count(syms - use, len + 1, (left - use) << 1); - sum += got; - if (got == (big_t)0 - 1 || sum < got) /* overflow */ - return (big_t)0 - 1; - } - - /* verify that all recursive calls are productive */ - assert(sum != 0); - - /* save the result and return it */ - num[index] = sum; - return sum; -} - -/* Return true if we've been here before, set to true if not. Set a bit in a - bit vector to indicate visiting this state. Each (syms,len,left) state - has a variable size bit vector indexed by (mem,rem). The bit vector is - lengthened if needed to allow setting the (mem,rem) bit. */ -local int beenhere(int syms, int len, int left, int mem, int rem) -{ - size_t index; /* index for this state's bit vector */ - size_t offset; /* offset in this state's bit vector */ - int bit; /* mask for this state's bit */ - size_t length; /* length of the bit vector in bytes */ - char *vector; /* new or enlarged bit vector */ - - /* point to vector for (syms,left,len), bit in vector for (mem,rem) */ - index = INDEX(syms, left, len); - mem -= 1 << root; - offset = (mem >> 3) + rem; - offset = ((offset * (offset + 1)) >> 1) + rem; - bit = 1 << (mem & 7); - - /* see if we've been here */ - length = done[index].len; - if (offset < length && (done[index].vec[offset] & bit) != 0) - return 1; /* done this! */ - - /* we haven't been here before -- set the bit to show we have now */ - - /* see if we need to lengthen the vector in order to set the bit */ - if (length <= offset) { - /* if we have one already, enlarge it, zero out the appended space */ - if (length) { - do { - length <<= 1; - } while (length <= offset); - vector = realloc(done[index].vec, length); - if (vector != NULL) - memset(vector + done[index].len, 0, length - done[index].len); - } - - /* otherwise we need to make a new vector and zero it out */ - else { - length = 1 << (len - root); - while (length <= offset) - length <<= 1; - vector = calloc(length, sizeof(char)); - } - - /* in either case, bail if we can't get the memory */ - if (vector == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - exit(1); - } - - /* install the new vector */ - done[index].len = length; - done[index].vec = vector; - } - - /* set the bit */ - done[index].vec[offset] |= bit; - return 0; -} - -/* Examine all possible codes from the given node (syms, len, left). Compute - the amount of memory required to build inflate's decoding tables, where the - number of code structures used so far is mem, and the number remaining in - the current sub-table is rem. Uses the globals max, code, root, large, and - done. */ -local void examine(int syms, int len, int left, int mem, int rem) -{ - int least; /* least number of syms to use at this juncture */ - int most; /* most number of syms to use at this juncture */ - int use; /* number of bit patterns to use in next call */ - - /* see if we have a complete code */ - if (syms == left) { - /* set the last code entry */ - code[len] = left; - - /* complete computation of memory used by this code */ - while (rem < left) { - left -= rem; - rem = 1 << (len - root); - mem += rem; - } - assert(rem == left); - - /* if this is a new maximum, show the entries used and the sub-code */ - if (mem > large) { - large = mem; - printf("max %d: ", mem); - for (use = root + 1; use <= max; use++) - if (code[use]) - printf("%d[%d] ", code[use], use); - putchar('\n'); - fflush(stdout); - } - - /* remove entries as we drop back down in the recursion */ - code[len] = 0; - return; - } - - /* prune the tree if we can */ - if (beenhere(syms, len, left, mem, rem)) - return; - - /* we need to use at least this many bit patterns so that the code won't be - incomplete at the next length (more bit patterns than symbols) */ - least = (left << 1) - syms; - if (least < 0) - least = 0; - - /* we can use at most this many bit patterns, lest there not be enough - available for the remaining symbols at the maximum length (if there were - no limit to the code length, this would become: most = left - 1) */ - most = (((code_t)left << (max - len)) - syms) / - (((code_t)1 << (max - len)) - 1); - - /* occupy least table spaces, creating new sub-tables as needed */ - use = least; - while (rem < use) { - use -= rem; - rem = 1 << (len - root); - mem += rem; - } - rem -= use; - - /* examine codes from here, updating table space as we go */ - for (use = least; use <= most; use++) { - code[len] = use; - examine(syms - use, len + 1, (left - use) << 1, - mem + (rem ? 1 << (len - root) : 0), rem << 1); - if (rem == 0) { - rem = 1 << (len - root); - mem += rem; - } - rem--; - } - - /* remove entries as we drop back down in the recursion */ - code[len] = 0; -} - -/* Look at all sub-codes starting with root + 1 bits. Look at only the valid - intermediate code states (syms, left, len). For each completed code, - calculate the amount of memory required by inflate to build the decoding - tables. Find the maximum amount of memory required and show the code that - requires that maximum. Uses the globals max, root, and num. */ -local void enough(int syms) -{ - int n; /* number of remaing symbols for this node */ - int left; /* number of unused bit patterns at this length */ - size_t index; /* index of this case in *num */ - - /* clear code */ - for (n = 0; n <= max; n++) - code[n] = 0; - - /* look at all (root + 1) bit and longer codes */ - large = 1 << root; /* base table */ - if (root < max) /* otherwise, there's only a base table */ - for (n = 3; n <= syms; n++) - for (left = 2; left < n; left += 2) - { - /* look at all reachable (root + 1) bit nodes, and the - resulting codes (complete at root + 2 or more) */ - index = INDEX(n, left, root + 1); - if (root + 1 < max && num[index]) /* reachable node */ - examine(n, root + 1, left, 1 << root, 0); - - /* also look at root bit codes with completions at root + 1 - bits (not saved in num, since complete), just in case */ - if (num[index - 1] && n <= left << 1) - examine((n - left) << 1, root + 1, (n - left) << 1, - 1 << root, 0); - } - - /* done */ - printf("done: maximum of %d table entries\n", large); -} - -/* - Examine and show the total number of possible Huffman codes for a given - maximum number of symbols, initial root table size, and maximum code length - in bits -- those are the command arguments in that order. The default - values are 286, 9, and 15 respectively, for the deflate literal/length code. - The possible codes are counted for each number of coded symbols from two to - the maximum. The counts for each of those and the total number of codes are - shown. The maximum number of inflate table entires is then calculated - across all possible codes. Each new maximum number of table entries and the - associated sub-code (starting at root + 1 == 10 bits) is shown. - - To count and examine Huffman codes that are not length-limited, provide a - maximum length equal to the number of symbols minus one. - - For the deflate literal/length code, use "enough". For the deflate distance - code, use "enough 30 6". - - This uses the %llu printf format to print big_t numbers, which assumes that - big_t is an unsigned long long. If the big_t type is changed (for example - to a multiple precision type), the method of printing will also need to be - updated. - */ -int main(int argc, char **argv) -{ - int syms; /* total number of symbols to code */ - int n; /* number of symbols to code for this run */ - big_t got; /* return value of count() */ - big_t sum; /* accumulated number of codes over n */ - code_t word; /* for counting bits in code_t */ - - /* set up globals for cleanup() */ - code = NULL; - num = NULL; - done = NULL; - - /* get arguments -- default to the deflate literal/length code */ - syms = 286; - root = 9; - max = 15; - if (argc > 1) { - syms = atoi(argv[1]); - if (argc > 2) { - root = atoi(argv[2]); - if (argc > 3) - max = atoi(argv[3]); - } - } - if (argc > 4 || syms < 2 || root < 1 || max < 1) { - fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n", - stderr); - return 1; - } - - /* if not restricting the code length, the longest is syms - 1 */ - if (max > syms - 1) - max = syms - 1; - - /* determine the number of bits in a code_t */ - for (n = 0, word = 1; word; n++, word <<= 1) - ; - - /* make sure that the calculation of most will not overflow */ - if (max > n || (code_t)(syms - 2) >= (((code_t)0 - 1) >> (max - 1))) { - fputs("abort: code length too long for internal types\n", stderr); - return 1; - } - - /* reject impossible code requests */ - if ((code_t)(syms - 1) > ((code_t)1 << max) - 1) { - fprintf(stderr, "%d symbols cannot be coded in %d bits\n", - syms, max); - return 1; - } - - /* allocate code vector */ - code = calloc(max + 1, sizeof(int)); - if (code == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - return 1; - } - - /* determine size of saved results array, checking for overflows, - allocate and clear the array (set all to zero with calloc()) */ - if (syms == 2) /* iff max == 1 */ - num = NULL; /* won't be saving any results */ - else { - size = syms >> 1; - if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) || - (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) || - (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) || - (num = calloc(size, sizeof(big_t))) == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - return 1; - } - } - - /* count possible codes for all numbers of symbols, add up counts */ - sum = 0; - for (n = 2; n <= syms; n++) { - got = count(n, 1, 2); - sum += got; - if (got == (big_t)0 - 1 || sum < got) { /* overflow */ - fputs("abort: can't count that high!\n", stderr); - cleanup(); - return 1; - } - printf("%llu %d-codes\n", got, n); - } - printf("%llu total codes for 2 to %d symbols", sum, syms); - if (max < syms - 1) - printf(" (%d-bit length limit)\n", max); - else - puts(" (no length limit)"); - - /* allocate and clear done array for beenhere() */ - if (syms == 2) - done = NULL; - else if (size > ((size_t)0 - 1) / sizeof(struct tab) || - (done = calloc(size, sizeof(struct tab))) == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - return 1; - } - - /* find and show maximum inflate table usage */ - if (root > max) /* reduce root to max length */ - root = max; - if ((code_t)syms < ((code_t)1 << (root + 1))) - enough(syms); - else - puts("cannot handle minimum code lengths > root"); - - /* done */ - cleanup(); - return 0; -} diff --git a/deps/zlib/examples/fitblk.c b/deps/zlib/examples/fitblk.c deleted file mode 100644 index c61de5c99672d1..00000000000000 --- a/deps/zlib/examples/fitblk.c +++ /dev/null @@ -1,233 +0,0 @@ -/* fitblk.c: example of fitting compressed output to a specified size - Not copyrighted -- provided to the public domain - Version 1.1 25 November 2004 Mark Adler */ - -/* Version history: - 1.0 24 Nov 2004 First version - 1.1 25 Nov 2004 Change deflateInit2() to deflateInit() - Use fixed-size, stack-allocated raw buffers - Simplify code moving compression to subroutines - Use assert() for internal errors - Add detailed description of approach - */ - -/* Approach to just fitting a requested compressed size: - - fitblk performs three compression passes on a portion of the input - data in order to determine how much of that input will compress to - nearly the requested output block size. The first pass generates - enough deflate blocks to produce output to fill the requested - output size plus a specfied excess amount (see the EXCESS define - below). The last deflate block may go quite a bit past that, but - is discarded. The second pass decompresses and recompresses just - the compressed data that fit in the requested plus excess sized - buffer. The deflate process is terminated after that amount of - input, which is less than the amount consumed on the first pass. - The last deflate block of the result will be of a comparable size - to the final product, so that the header for that deflate block and - the compression ratio for that block will be about the same as in - the final product. The third compression pass decompresses the - result of the second step, but only the compressed data up to the - requested size minus an amount to allow the compressed stream to - complete (see the MARGIN define below). That will result in a - final compressed stream whose length is less than or equal to the - requested size. Assuming sufficient input and a requested size - greater than a few hundred bytes, the shortfall will typically be - less than ten bytes. - - If the input is short enough that the first compression completes - before filling the requested output size, then that compressed - stream is return with no recompression. - - EXCESS is chosen to be just greater than the shortfall seen in a - two pass approach similar to the above. That shortfall is due to - the last deflate block compressing more efficiently with a smaller - header on the second pass. EXCESS is set to be large enough so - that there is enough uncompressed data for the second pass to fill - out the requested size, and small enough so that the final deflate - block of the second pass will be close in size to the final deflate - block of the third and final pass. MARGIN is chosen to be just - large enough to assure that the final compression has enough room - to complete in all cases. - */ - -#include -#include -#include -#include "zlib.h" - -#define local static - -/* print nastygram and leave */ -local void quit(char *why) -{ - fprintf(stderr, "fitblk abort: %s\n", why); - exit(1); -} - -#define RAWLEN 4096 /* intermediate uncompressed buffer size */ - -/* compress from file to def until provided buffer is full or end of - input reached; return last deflate() return value, or Z_ERRNO if - there was read error on the file */ -local int partcompress(FILE *in, z_streamp def) -{ - int ret, flush; - unsigned char raw[RAWLEN]; - - flush = Z_NO_FLUSH; - do { - def->avail_in = fread(raw, 1, RAWLEN, in); - if (ferror(in)) - return Z_ERRNO; - def->next_in = raw; - if (feof(in)) - flush = Z_FINISH; - ret = deflate(def, flush); - assert(ret != Z_STREAM_ERROR); - } while (def->avail_out != 0 && flush == Z_NO_FLUSH); - return ret; -} - -/* recompress from inf's input to def's output; the input for inf and - the output for def are set in those structures before calling; - return last deflate() return value, or Z_MEM_ERROR if inflate() - was not able to allocate enough memory when it needed to */ -local int recompress(z_streamp inf, z_streamp def) -{ - int ret, flush; - unsigned char raw[RAWLEN]; - - flush = Z_NO_FLUSH; - do { - /* decompress */ - inf->avail_out = RAWLEN; - inf->next_out = raw; - ret = inflate(inf, Z_NO_FLUSH); - assert(ret != Z_STREAM_ERROR && ret != Z_DATA_ERROR && - ret != Z_NEED_DICT); - if (ret == Z_MEM_ERROR) - return ret; - - /* compress what was decompresed until done or no room */ - def->avail_in = RAWLEN - inf->avail_out; - def->next_in = raw; - if (inf->avail_out != 0) - flush = Z_FINISH; - ret = deflate(def, flush); - assert(ret != Z_STREAM_ERROR); - } while (ret != Z_STREAM_END && def->avail_out != 0); - return ret; -} - -#define EXCESS 256 /* empirically determined stream overage */ -#define MARGIN 8 /* amount to back off for completion */ - -/* compress from stdin to fixed-size block on stdout */ -int main(int argc, char **argv) -{ - int ret; /* return code */ - unsigned size; /* requested fixed output block size */ - unsigned have; /* bytes written by deflate() call */ - unsigned char *blk; /* intermediate and final stream */ - unsigned char *tmp; /* close to desired size stream */ - z_stream def, inf; /* zlib deflate and inflate states */ - - /* get requested output size */ - if (argc != 2) - quit("need one argument: size of output block"); - ret = strtol(argv[1], argv + 1, 10); - if (argv[1][0] != 0) - quit("argument must be a number"); - if (ret < 8) /* 8 is minimum zlib stream size */ - quit("need positive size of 8 or greater"); - size = (unsigned)ret; - - /* allocate memory for buffers and compression engine */ - blk = malloc(size + EXCESS); - def.zalloc = Z_NULL; - def.zfree = Z_NULL; - def.opaque = Z_NULL; - ret = deflateInit(&def, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK || blk == NULL) - quit("out of memory"); - - /* compress from stdin until output full, or no more input */ - def.avail_out = size + EXCESS; - def.next_out = blk; - ret = partcompress(stdin, &def); - if (ret == Z_ERRNO) - quit("error reading input"); - - /* if it all fit, then size was undersubscribed -- done! */ - if (ret == Z_STREAM_END && def.avail_out >= EXCESS) { - /* write block to stdout */ - have = size + EXCESS - def.avail_out; - if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) - quit("error writing output"); - - /* clean up and print results to stderr */ - ret = deflateEnd(&def); - assert(ret != Z_STREAM_ERROR); - free(blk); - fprintf(stderr, - "%u bytes unused out of %u requested (all input)\n", - size - have, size); - return 0; - } - - /* it didn't all fit -- set up for recompression */ - inf.zalloc = Z_NULL; - inf.zfree = Z_NULL; - inf.opaque = Z_NULL; - inf.avail_in = 0; - inf.next_in = Z_NULL; - ret = inflateInit(&inf); - tmp = malloc(size + EXCESS); - if (ret != Z_OK || tmp == NULL) - quit("out of memory"); - ret = deflateReset(&def); - assert(ret != Z_STREAM_ERROR); - - /* do first recompression close to the right amount */ - inf.avail_in = size + EXCESS; - inf.next_in = blk; - def.avail_out = size + EXCESS; - def.next_out = tmp; - ret = recompress(&inf, &def); - if (ret == Z_MEM_ERROR) - quit("out of memory"); - - /* set up for next reocmpression */ - ret = inflateReset(&inf); - assert(ret != Z_STREAM_ERROR); - ret = deflateReset(&def); - assert(ret != Z_STREAM_ERROR); - - /* do second and final recompression (third compression) */ - inf.avail_in = size - MARGIN; /* assure stream will complete */ - inf.next_in = tmp; - def.avail_out = size; - def.next_out = blk; - ret = recompress(&inf, &def); - if (ret == Z_MEM_ERROR) - quit("out of memory"); - assert(ret == Z_STREAM_END); /* otherwise MARGIN too small */ - - /* done -- write block to stdout */ - have = size - def.avail_out; - if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) - quit("error writing output"); - - /* clean up and print results to stderr */ - free(tmp); - ret = inflateEnd(&inf); - assert(ret != Z_STREAM_ERROR); - ret = deflateEnd(&def); - assert(ret != Z_STREAM_ERROR); - free(blk); - fprintf(stderr, - "%u bytes unused out of %u requested (%lu input)\n", - size - have, size, def.total_in); - return 0; -} diff --git a/deps/zlib/examples/gun.c b/deps/zlib/examples/gun.c deleted file mode 100644 index be44fa51ff522c..00000000000000 --- a/deps/zlib/examples/gun.c +++ /dev/null @@ -1,702 +0,0 @@ -/* gun.c -- simple gunzip to give an example of the use of inflateBack() - * Copyright (C) 2003, 2005, 2008, 2010, 2012 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - Version 1.7 12 August 2012 Mark Adler */ - -/* Version history: - 1.0 16 Feb 2003 First version for testing of inflateBack() - 1.1 21 Feb 2005 Decompress concatenated gzip streams - Remove use of "this" variable (C++ keyword) - Fix return value for in() - Improve allocation failure checking - Add typecasting for void * structures - Add -h option for command version and usage - Add a bunch of comments - 1.2 20 Mar 2005 Add Unix compress (LZW) decompression - Copy file attributes from input file to output file - 1.3 12 Jun 2005 Add casts for error messages [Oberhumer] - 1.4 8 Dec 2006 LZW decompression speed improvements - 1.5 9 Feb 2008 Avoid warning in latest version of gcc - 1.6 17 Jan 2010 Avoid signed/unsigned comparison warnings - 1.7 12 Aug 2012 Update for z_const usage in zlib 1.2.8 - */ - -/* - gun [ -t ] [ name ... ] - - decompresses the data in the named gzip files. If no arguments are given, - gun will decompress from stdin to stdout. The names must end in .gz, -gz, - .z, -z, _z, or .Z. The uncompressed data will be written to a file name - with the suffix stripped. On success, the original file is deleted. On - failure, the output file is deleted. For most failures, the command will - continue to process the remaining names on the command line. A memory - allocation failure will abort the command. If -t is specified, then the - listed files or stdin will be tested as gzip files for integrity (without - checking for a proper suffix), no output will be written, and no files - will be deleted. - - Like gzip, gun allows concatenated gzip streams and will decompress them, - writing all of the uncompressed data to the output. Unlike gzip, gun allows - an empty file on input, and will produce no error writing an empty output - file. - - gun will also decompress files made by Unix compress, which uses LZW - compression. These files are automatically detected by virtue of their - magic header bytes. Since the end of Unix compress stream is marked by the - end-of-file, they cannot be concantenated. If a Unix compress stream is - encountered in an input file, it is the last stream in that file. - - Like gunzip and uncompress, the file attributes of the original compressed - file are maintained in the final uncompressed file, to the extent that the - user permissions allow it. - - On my Mac OS X PowerPC G4, gun is almost twice as fast as gunzip (version - 1.2.4) is on the same file, when gun is linked with zlib 1.2.2. Also the - LZW decompression provided by gun is about twice as fast as the standard - Unix uncompress command. - */ - -/* external functions and related types and constants */ -#include /* fprintf() */ -#include /* malloc(), free() */ -#include /* strerror(), strcmp(), strlen(), memcpy() */ -#include /* errno */ -#include /* open() */ -#include /* read(), write(), close(), chown(), unlink() */ -#include -#include /* stat(), chmod() */ -#include /* utime() */ -#include "zlib.h" /* inflateBackInit(), inflateBack(), */ - /* inflateBackEnd(), crc32() */ - -/* function declaration */ -#define local static - -/* buffer constants */ -#define SIZE 32768U /* input and output buffer sizes */ -#define PIECE 16384 /* limits i/o chunks for 16-bit int case */ - -/* structure for infback() to pass to input function in() -- it maintains the - input file and a buffer of size SIZE */ -struct ind { - int infile; - unsigned char *inbuf; -}; - -/* Load input buffer, assumed to be empty, and return bytes loaded and a - pointer to them. read() is called until the buffer is full, or until it - returns end-of-file or error. Return 0 on error. */ -local unsigned in(void *in_desc, z_const unsigned char **buf) -{ - int ret; - unsigned len; - unsigned char *next; - struct ind *me = (struct ind *)in_desc; - - next = me->inbuf; - *buf = next; - len = 0; - do { - ret = PIECE; - if ((unsigned)ret > SIZE - len) - ret = (int)(SIZE - len); - ret = (int)read(me->infile, next, ret); - if (ret == -1) { - len = 0; - break; - } - next += ret; - len += ret; - } while (ret != 0 && len < SIZE); - return len; -} - -/* structure for infback() to pass to output function out() -- it maintains the - output file, a running CRC-32 check on the output and the total number of - bytes output, both for checking against the gzip trailer. (The length in - the gzip trailer is stored modulo 2^32, so it's ok if a long is 32 bits and - the output is greater than 4 GB.) */ -struct outd { - int outfile; - int check; /* true if checking crc and total */ - unsigned long crc; - unsigned long total; -}; - -/* Write output buffer and update the CRC-32 and total bytes written. write() - is called until all of the output is written or an error is encountered. - On success out() returns 0. For a write failure, out() returns 1. If the - output file descriptor is -1, then nothing is written. - */ -local int out(void *out_desc, unsigned char *buf, unsigned len) -{ - int ret; - struct outd *me = (struct outd *)out_desc; - - if (me->check) { - me->crc = crc32(me->crc, buf, len); - me->total += len; - } - if (me->outfile != -1) - do { - ret = PIECE; - if ((unsigned)ret > len) - ret = (int)len; - ret = (int)write(me->outfile, buf, ret); - if (ret == -1) - return 1; - buf += ret; - len -= ret; - } while (len != 0); - return 0; -} - -/* next input byte macro for use inside lunpipe() and gunpipe() */ -#define NEXT() (have ? 0 : (have = in(indp, &next)), \ - last = have ? (have--, (int)(*next++)) : -1) - -/* memory for gunpipe() and lunpipe() -- - the first 256 entries of prefix[] and suffix[] are never used, could - have offset the index, but it's faster to waste the memory */ -unsigned char inbuf[SIZE]; /* input buffer */ -unsigned char outbuf[SIZE]; /* output buffer */ -unsigned short prefix[65536]; /* index to LZW prefix string */ -unsigned char suffix[65536]; /* one-character LZW suffix */ -unsigned char match[65280 + 2]; /* buffer for reversed match or gzip - 32K sliding window */ - -/* throw out what's left in the current bits byte buffer (this is a vestigial - aspect of the compressed data format derived from an implementation that - made use of a special VAX machine instruction!) */ -#define FLUSHCODE() \ - do { \ - left = 0; \ - rem = 0; \ - if (chunk > have) { \ - chunk -= have; \ - have = 0; \ - if (NEXT() == -1) \ - break; \ - chunk--; \ - if (chunk > have) { \ - chunk = have = 0; \ - break; \ - } \ - } \ - have -= chunk; \ - next += chunk; \ - chunk = 0; \ - } while (0) - -/* Decompress a compress (LZW) file from indp to outfile. The compress magic - header (two bytes) has already been read and verified. There are have bytes - of buffered input at next. strm is used for passing error information back - to gunpipe(). - - lunpipe() will return Z_OK on success, Z_BUF_ERROR for an unexpected end of - file, read error, or write error (a write error indicated by strm->next_in - not equal to Z_NULL), or Z_DATA_ERROR for invalid input. - */ -local int lunpipe(unsigned have, z_const unsigned char *next, struct ind *indp, - int outfile, z_stream *strm) -{ - int last; /* last byte read by NEXT(), or -1 if EOF */ - unsigned chunk; /* bytes left in current chunk */ - int left; /* bits left in rem */ - unsigned rem; /* unused bits from input */ - int bits; /* current bits per code */ - unsigned code; /* code, table traversal index */ - unsigned mask; /* mask for current bits codes */ - int max; /* maximum bits per code for this stream */ - unsigned flags; /* compress flags, then block compress flag */ - unsigned end; /* last valid entry in prefix/suffix tables */ - unsigned temp; /* current code */ - unsigned prev; /* previous code */ - unsigned final; /* last character written for previous code */ - unsigned stack; /* next position for reversed string */ - unsigned outcnt; /* bytes in output buffer */ - struct outd outd; /* output structure */ - unsigned char *p; - - /* set up output */ - outd.outfile = outfile; - outd.check = 0; - - /* process remainder of compress header -- a flags byte */ - flags = NEXT(); - if (last == -1) - return Z_BUF_ERROR; - if (flags & 0x60) { - strm->msg = (char *)"unknown lzw flags set"; - return Z_DATA_ERROR; - } - max = flags & 0x1f; - if (max < 9 || max > 16) { - strm->msg = (char *)"lzw bits out of range"; - return Z_DATA_ERROR; - } - if (max == 9) /* 9 doesn't really mean 9 */ - max = 10; - flags &= 0x80; /* true if block compress */ - - /* clear table */ - bits = 9; - mask = 0x1ff; - end = flags ? 256 : 255; - - /* set up: get first 9-bit code, which is the first decompressed byte, but - don't create a table entry until the next code */ - if (NEXT() == -1) /* no compressed data is ok */ - return Z_OK; - final = prev = (unsigned)last; /* low 8 bits of code */ - if (NEXT() == -1) /* missing a bit */ - return Z_BUF_ERROR; - if (last & 1) { /* code must be < 256 */ - strm->msg = (char *)"invalid lzw code"; - return Z_DATA_ERROR; - } - rem = (unsigned)last >> 1; /* remaining 7 bits */ - left = 7; - chunk = bits - 2; /* 7 bytes left in this chunk */ - outbuf[0] = (unsigned char)final; /* write first decompressed byte */ - outcnt = 1; - - /* decode codes */ - stack = 0; - for (;;) { - /* if the table will be full after this, increment the code size */ - if (end >= mask && bits < max) { - FLUSHCODE(); - bits++; - mask <<= 1; - mask++; - } - - /* get a code of length bits */ - if (chunk == 0) /* decrement chunk modulo bits */ - chunk = bits; - code = rem; /* low bits of code */ - if (NEXT() == -1) { /* EOF is end of compressed data */ - /* write remaining buffered output */ - if (outcnt && out(&outd, outbuf, outcnt)) { - strm->next_in = outbuf; /* signal write error */ - return Z_BUF_ERROR; - } - return Z_OK; - } - code += (unsigned)last << left; /* middle (or high) bits of code */ - left += 8; - chunk--; - if (bits > left) { /* need more bits */ - if (NEXT() == -1) /* can't end in middle of code */ - return Z_BUF_ERROR; - code += (unsigned)last << left; /* high bits of code */ - left += 8; - chunk--; - } - code &= mask; /* mask to current code length */ - left -= bits; /* number of unused bits */ - rem = (unsigned)last >> (8 - left); /* unused bits from last byte */ - - /* process clear code (256) */ - if (code == 256 && flags) { - FLUSHCODE(); - bits = 9; /* initialize bits and mask */ - mask = 0x1ff; - end = 255; /* empty table */ - continue; /* get next code */ - } - - /* special code to reuse last match */ - temp = code; /* save the current code */ - if (code > end) { - /* Be picky on the allowed code here, and make sure that the code - we drop through (prev) will be a valid index so that random - input does not cause an exception. The code != end + 1 check is - empirically derived, and not checked in the original uncompress - code. If this ever causes a problem, that check could be safely - removed. Leaving this check in greatly improves gun's ability - to detect random or corrupted input after a compress header. - In any case, the prev > end check must be retained. */ - if (code != end + 1 || prev > end) { - strm->msg = (char *)"invalid lzw code"; - return Z_DATA_ERROR; - } - match[stack++] = (unsigned char)final; - code = prev; - } - - /* walk through linked list to generate output in reverse order */ - p = match + stack; - while (code >= 256) { - *p++ = suffix[code]; - code = prefix[code]; - } - stack = p - match; - match[stack++] = (unsigned char)code; - final = code; - - /* link new table entry */ - if (end < mask) { - end++; - prefix[end] = (unsigned short)prev; - suffix[end] = (unsigned char)final; - } - - /* set previous code for next iteration */ - prev = temp; - - /* write output in forward order */ - while (stack > SIZE - outcnt) { - while (outcnt < SIZE) - outbuf[outcnt++] = match[--stack]; - if (out(&outd, outbuf, outcnt)) { - strm->next_in = outbuf; /* signal write error */ - return Z_BUF_ERROR; - } - outcnt = 0; - } - p = match + stack; - do { - outbuf[outcnt++] = *--p; - } while (p > match); - stack = 0; - - /* loop for next code with final and prev as the last match, rem and - left provide the first 0..7 bits of the next code, end is the last - valid table entry */ - } -} - -/* Decompress a gzip file from infile to outfile. strm is assumed to have been - successfully initialized with inflateBackInit(). The input file may consist - of a series of gzip streams, in which case all of them will be decompressed - to the output file. If outfile is -1, then the gzip stream(s) integrity is - checked and nothing is written. - - The return value is a zlib error code: Z_MEM_ERROR if out of memory, - Z_DATA_ERROR if the header or the compressed data is invalid, or if the - trailer CRC-32 check or length doesn't match, Z_BUF_ERROR if the input ends - prematurely or a write error occurs, or Z_ERRNO if junk (not a another gzip - stream) follows a valid gzip stream. - */ -local int gunpipe(z_stream *strm, int infile, int outfile) -{ - int ret, first, last; - unsigned have, flags, len; - z_const unsigned char *next = NULL; - struct ind ind, *indp; - struct outd outd; - - /* setup input buffer */ - ind.infile = infile; - ind.inbuf = inbuf; - indp = &ind; - - /* decompress concatenated gzip streams */ - have = 0; /* no input data read in yet */ - first = 1; /* looking for first gzip header */ - strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ - for (;;) { - /* look for the two magic header bytes for a gzip stream */ - if (NEXT() == -1) { - ret = Z_OK; - break; /* empty gzip stream is ok */ - } - if (last != 31 || (NEXT() != 139 && last != 157)) { - strm->msg = (char *)"incorrect header check"; - ret = first ? Z_DATA_ERROR : Z_ERRNO; - break; /* not a gzip or compress header */ - } - first = 0; /* next non-header is junk */ - - /* process a compress (LZW) file -- can't be concatenated after this */ - if (last == 157) { - ret = lunpipe(have, next, indp, outfile, strm); - break; - } - - /* process remainder of gzip header */ - ret = Z_BUF_ERROR; - if (NEXT() != 8) { /* only deflate method allowed */ - if (last == -1) break; - strm->msg = (char *)"unknown compression method"; - ret = Z_DATA_ERROR; - break; - } - flags = NEXT(); /* header flags */ - NEXT(); /* discard mod time, xflgs, os */ - NEXT(); - NEXT(); - NEXT(); - NEXT(); - NEXT(); - if (last == -1) break; - if (flags & 0xe0) { - strm->msg = (char *)"unknown header flags set"; - ret = Z_DATA_ERROR; - break; - } - if (flags & 4) { /* extra field */ - len = NEXT(); - len += (unsigned)(NEXT()) << 8; - if (last == -1) break; - while (len > have) { - len -= have; - have = 0; - if (NEXT() == -1) break; - len--; - } - if (last == -1) break; - have -= len; - next += len; - } - if (flags & 8) /* file name */ - while (NEXT() != 0 && last != -1) - ; - if (flags & 16) /* comment */ - while (NEXT() != 0 && last != -1) - ; - if (flags & 2) { /* header crc */ - NEXT(); - NEXT(); - } - if (last == -1) break; - - /* set up output */ - outd.outfile = outfile; - outd.check = 1; - outd.crc = crc32(0L, Z_NULL, 0); - outd.total = 0; - - /* decompress data to output */ - strm->next_in = next; - strm->avail_in = have; - ret = inflateBack(strm, in, indp, out, &outd); - if (ret != Z_STREAM_END) break; - next = strm->next_in; - have = strm->avail_in; - strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ - - /* check trailer */ - ret = Z_BUF_ERROR; - if (NEXT() != (int)(outd.crc & 0xff) || - NEXT() != (int)((outd.crc >> 8) & 0xff) || - NEXT() != (int)((outd.crc >> 16) & 0xff) || - NEXT() != (int)((outd.crc >> 24) & 0xff)) { - /* crc error */ - if (last != -1) { - strm->msg = (char *)"incorrect data check"; - ret = Z_DATA_ERROR; - } - break; - } - if (NEXT() != (int)(outd.total & 0xff) || - NEXT() != (int)((outd.total >> 8) & 0xff) || - NEXT() != (int)((outd.total >> 16) & 0xff) || - NEXT() != (int)((outd.total >> 24) & 0xff)) { - /* length error */ - if (last != -1) { - strm->msg = (char *)"incorrect length check"; - ret = Z_DATA_ERROR; - } - break; - } - - /* go back and look for another gzip stream */ - } - - /* clean up and return */ - return ret; -} - -/* Copy file attributes, from -> to, as best we can. This is best effort, so - no errors are reported. The mode bits, including suid, sgid, and the sticky - bit are copied (if allowed), the owner's user id and group id are copied - (again if allowed), and the access and modify times are copied. */ -local void copymeta(char *from, char *to) -{ - struct stat was; - struct utimbuf when; - - /* get all of from's Unix meta data, return if not a regular file */ - if (stat(from, &was) != 0 || (was.st_mode & S_IFMT) != S_IFREG) - return; - - /* set to's mode bits, ignore errors */ - (void)chmod(to, was.st_mode & 07777); - - /* copy owner's user and group, ignore errors */ - (void)chown(to, was.st_uid, was.st_gid); - - /* copy access and modify times, ignore errors */ - when.actime = was.st_atime; - when.modtime = was.st_mtime; - (void)utime(to, &when); -} - -/* Decompress the file inname to the file outnname, of if test is true, just - decompress without writing and check the gzip trailer for integrity. If - inname is NULL or an empty string, read from stdin. If outname is NULL or - an empty string, write to stdout. strm is a pre-initialized inflateBack - structure. When appropriate, copy the file attributes from inname to - outname. - - gunzip() returns 1 if there is an out-of-memory error or an unexpected - return code from gunpipe(). Otherwise it returns 0. - */ -local int gunzip(z_stream *strm, char *inname, char *outname, int test) -{ - int ret; - int infile, outfile; - - /* open files */ - if (inname == NULL || *inname == 0) { - inname = "-"; - infile = 0; /* stdin */ - } - else { - infile = open(inname, O_RDONLY, 0); - if (infile == -1) { - fprintf(stderr, "gun cannot open %s\n", inname); - return 0; - } - } - if (test) - outfile = -1; - else if (outname == NULL || *outname == 0) { - outname = "-"; - outfile = 1; /* stdout */ - } - else { - outfile = open(outname, O_CREAT | O_TRUNC | O_WRONLY, 0666); - if (outfile == -1) { - close(infile); - fprintf(stderr, "gun cannot create %s\n", outname); - return 0; - } - } - errno = 0; - - /* decompress */ - ret = gunpipe(strm, infile, outfile); - if (outfile > 2) close(outfile); - if (infile > 2) close(infile); - - /* interpret result */ - switch (ret) { - case Z_OK: - case Z_ERRNO: - if (infile > 2 && outfile > 2) { - copymeta(inname, outname); /* copy attributes */ - unlink(inname); - } - if (ret == Z_ERRNO) - fprintf(stderr, "gun warning: trailing garbage ignored in %s\n", - inname); - break; - case Z_DATA_ERROR: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun data error on %s: %s\n", inname, strm->msg); - break; - case Z_MEM_ERROR: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun out of memory error--aborting\n"); - return 1; - case Z_BUF_ERROR: - if (outfile > 2) unlink(outname); - if (strm->next_in != Z_NULL) { - fprintf(stderr, "gun write error on %s: %s\n", - outname, strerror(errno)); - } - else if (errno) { - fprintf(stderr, "gun read error on %s: %s\n", - inname, strerror(errno)); - } - else { - fprintf(stderr, "gun unexpected end of file on %s\n", - inname); - } - break; - default: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun internal error--aborting\n"); - return 1; - } - return 0; -} - -/* Process the gun command line arguments. See the command syntax near the - beginning of this source file. */ -int main(int argc, char **argv) -{ - int ret, len, test; - char *outname; - unsigned char *window; - z_stream strm; - - /* initialize inflateBack state for repeated use */ - window = match; /* reuse LZW match buffer */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - ret = inflateBackInit(&strm, 15, window); - if (ret != Z_OK) { - fprintf(stderr, "gun out of memory error--aborting\n"); - return 1; - } - - /* decompress each file to the same name with the suffix removed */ - argc--; - argv++; - test = 0; - if (argc && strcmp(*argv, "-h") == 0) { - fprintf(stderr, "gun 1.6 (17 Jan 2010)\n"); - fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n"); - fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n"); - return 0; - } - if (argc && strcmp(*argv, "-t") == 0) { - test = 1; - argc--; - argv++; - } - if (argc) - do { - if (test) - outname = NULL; - else { - len = (int)strlen(*argv); - if (strcmp(*argv + len - 3, ".gz") == 0 || - strcmp(*argv + len - 3, "-gz") == 0) - len -= 3; - else if (strcmp(*argv + len - 2, ".z") == 0 || - strcmp(*argv + len - 2, "-z") == 0 || - strcmp(*argv + len - 2, "_z") == 0 || - strcmp(*argv + len - 2, ".Z") == 0) - len -= 2; - else { - fprintf(stderr, "gun error: no gz type on %s--skipping\n", - *argv); - continue; - } - outname = malloc(len + 1); - if (outname == NULL) { - fprintf(stderr, "gun out of memory error--aborting\n"); - ret = 1; - break; - } - memcpy(outname, *argv, len); - outname[len] = 0; - } - ret = gunzip(&strm, *argv, outname, test); - if (outname != NULL) free(outname); - if (ret) break; - } while (argv++, --argc); - else - ret = gunzip(&strm, NULL, NULL, test); - - /* clean up */ - inflateBackEnd(&strm); - return ret; -} diff --git a/deps/zlib/examples/gzappend.c b/deps/zlib/examples/gzappend.c deleted file mode 100644 index 662dec3794b7c0..00000000000000 --- a/deps/zlib/examples/gzappend.c +++ /dev/null @@ -1,504 +0,0 @@ -/* gzappend -- command to append to a gzip file - - Copyright (C) 2003, 2012 Mark Adler, all rights reserved - version 1.2, 11 Oct 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* - * Change history: - * - * 1.0 19 Oct 2003 - First version - * 1.1 4 Nov 2003 - Expand and clarify some comments and notes - * - Add version and copyright to help - * - Send help to stdout instead of stderr - * - Add some preemptive typecasts - * - Add L to constants in lseek() calls - * - Remove some debugging information in error messages - * - Use new data_type definition for zlib 1.2.1 - * - Simplfy and unify file operations - * - Finish off gzip file in gztack() - * - Use deflatePrime() instead of adding empty blocks - * - Keep gzip file clean on appended file read errors - * - Use in-place rotate instead of auxiliary buffer - * (Why you ask? Because it was fun to write!) - * 1.2 11 Oct 2012 - Fix for proper z_const usage - * - Check for input buffer malloc failure - */ - -/* - gzappend takes a gzip file and appends to it, compressing files from the - command line or data from stdin. The gzip file is written to directly, to - avoid copying that file, in case it's large. Note that this results in the - unfriendly behavior that if gzappend fails, the gzip file is corrupted. - - This program was written to illustrate the use of the new Z_BLOCK option of - zlib 1.2.x's inflate() function. This option returns from inflate() at each - block boundary to facilitate locating and modifying the last block bit at - the start of the final deflate block. Also whether using Z_BLOCK or not, - another required feature of zlib 1.2.x is that inflate() now provides the - number of unusued bits in the last input byte used. gzappend will not work - with versions of zlib earlier than 1.2.1. - - gzappend first decompresses the gzip file internally, discarding all but - the last 32K of uncompressed data, and noting the location of the last block - bit and the number of unused bits in the last byte of the compressed data. - The gzip trailer containing the CRC-32 and length of the uncompressed data - is verified. This trailer will be later overwritten. - - Then the last block bit is cleared by seeking back in the file and rewriting - the byte that contains it. Seeking forward, the last byte of the compressed - data is saved along with the number of unused bits to initialize deflate. - - A deflate process is initialized, using the last 32K of the uncompressed - data from the gzip file to initialize the dictionary. If the total - uncompressed data was less than 32K, then all of it is used to initialize - the dictionary. The deflate output bit buffer is also initialized with the - last bits from the original deflate stream. From here on, the data to - append is simply compressed using deflate, and written to the gzip file. - When that is complete, the new CRC-32 and uncompressed length are written - as the trailer of the gzip file. - */ - -#include -#include -#include -#include -#include -#include "zlib.h" - -#define local static -#define LGCHUNK 14 -#define CHUNK (1U << LGCHUNK) -#define DSIZE 32768U - -/* print an error message and terminate with extreme prejudice */ -local void bye(char *msg1, char *msg2) -{ - fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2); - exit(1); -} - -/* return the greatest common divisor of a and b using Euclid's algorithm, - modified to be fast when one argument much greater than the other, and - coded to avoid unnecessary swapping */ -local unsigned gcd(unsigned a, unsigned b) -{ - unsigned c; - - while (a && b) - if (a > b) { - c = b; - while (a - c >= c) - c <<= 1; - a -= c; - } - else { - c = a; - while (b - c >= c) - c <<= 1; - b -= c; - } - return a + b; -} - -/* rotate list[0..len-1] left by rot positions, in place */ -local void rotate(unsigned char *list, unsigned len, unsigned rot) -{ - unsigned char tmp; - unsigned cycles; - unsigned char *start, *last, *to, *from; - - /* normalize rot and handle degenerate cases */ - if (len < 2) return; - if (rot >= len) rot %= len; - if (rot == 0) return; - - /* pointer to last entry in list */ - last = list + (len - 1); - - /* do simple left shift by one */ - if (rot == 1) { - tmp = *list; - memcpy(list, list + 1, len - 1); - *last = tmp; - return; - } - - /* do simple right shift by one */ - if (rot == len - 1) { - tmp = *last; - memmove(list + 1, list, len - 1); - *list = tmp; - return; - } - - /* otherwise do rotate as a set of cycles in place */ - cycles = gcd(len, rot); /* number of cycles */ - do { - start = from = list + cycles; /* start index is arbitrary */ - tmp = *from; /* save entry to be overwritten */ - for (;;) { - to = from; /* next step in cycle */ - from += rot; /* go right rot positions */ - if (from > last) from -= len; /* (pointer better not wrap) */ - if (from == start) break; /* all but one shifted */ - *to = *from; /* shift left */ - } - *to = tmp; /* complete the circle */ - } while (--cycles); -} - -/* structure for gzip file read operations */ -typedef struct { - int fd; /* file descriptor */ - int size; /* 1 << size is bytes in buf */ - unsigned left; /* bytes available at next */ - unsigned char *buf; /* buffer */ - z_const unsigned char *next; /* next byte in buffer */ - char *name; /* file name for error messages */ -} file; - -/* reload buffer */ -local int readin(file *in) -{ - int len; - - len = read(in->fd, in->buf, 1 << in->size); - if (len == -1) bye("error reading ", in->name); - in->left = (unsigned)len; - in->next = in->buf; - return len; -} - -/* read from file in, exit if end-of-file */ -local int readmore(file *in) -{ - if (readin(in) == 0) bye("unexpected end of ", in->name); - return 0; -} - -#define read1(in) (in->left == 0 ? readmore(in) : 0, \ - in->left--, *(in->next)++) - -/* skip over n bytes of in */ -local void skip(file *in, unsigned n) -{ - unsigned bypass; - - if (n > in->left) { - n -= in->left; - bypass = n & ~((1U << in->size) - 1); - if (bypass) { - if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1) - bye("seeking ", in->name); - n -= bypass; - } - readmore(in); - if (n > in->left) - bye("unexpected end of ", in->name); - } - in->left -= n; - in->next += n; -} - -/* read a four-byte unsigned integer, little-endian, from in */ -unsigned long read4(file *in) -{ - unsigned long val; - - val = read1(in); - val += (unsigned)read1(in) << 8; - val += (unsigned long)read1(in) << 16; - val += (unsigned long)read1(in) << 24; - return val; -} - -/* skip over gzip header */ -local void gzheader(file *in) -{ - int flags; - unsigned n; - - if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file"); - if (read1(in) != 8) bye("unknown compression method in", in->name); - flags = read1(in); - if (flags & 0xe0) bye("unknown header flags set in", in->name); - skip(in, 6); - if (flags & 4) { - n = read1(in); - n += (unsigned)(read1(in)) << 8; - skip(in, n); - } - if (flags & 8) while (read1(in) != 0) ; - if (flags & 16) while (read1(in) != 0) ; - if (flags & 2) skip(in, 2); -} - -/* decompress gzip file "name", return strm with a deflate stream ready to - continue compression of the data in the gzip file, and return a file - descriptor pointing to where to write the compressed data -- the deflate - stream is initialized to compress using level "level" */ -local int gzscan(char *name, z_stream *strm, int level) -{ - int ret, lastbit, left, full; - unsigned have; - unsigned long crc, tot; - unsigned char *window; - off_t lastoff, end; - file gz; - - /* open gzip file */ - gz.name = name; - gz.fd = open(name, O_RDWR, 0); - if (gz.fd == -1) bye("cannot open ", name); - gz.buf = malloc(CHUNK); - if (gz.buf == NULL) bye("out of memory", ""); - gz.size = LGCHUNK; - gz.left = 0; - - /* skip gzip header */ - gzheader(&gz); - - /* prepare to decompress */ - window = malloc(DSIZE); - if (window == NULL) bye("out of memory", ""); - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; - strm->opaque = Z_NULL; - ret = inflateInit2(strm, -15); - if (ret != Z_OK) bye("out of memory", " or library mismatch"); - - /* decompress the deflate stream, saving append information */ - lastbit = 0; - lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; - left = 0; - strm->avail_in = gz.left; - strm->next_in = gz.next; - crc = crc32(0L, Z_NULL, 0); - have = full = 0; - do { - /* if needed, get more input */ - if (strm->avail_in == 0) { - readmore(&gz); - strm->avail_in = gz.left; - strm->next_in = gz.next; - } - - /* set up output to next available section of sliding window */ - strm->avail_out = DSIZE - have; - strm->next_out = window + have; - - /* inflate and check for errors */ - ret = inflate(strm, Z_BLOCK); - if (ret == Z_STREAM_ERROR) bye("internal stream error!", ""); - if (ret == Z_MEM_ERROR) bye("out of memory", ""); - if (ret == Z_DATA_ERROR) - bye("invalid compressed data--format violated in", name); - - /* update crc and sliding window pointer */ - crc = crc32(crc, window + have, DSIZE - have - strm->avail_out); - if (strm->avail_out) - have = DSIZE - strm->avail_out; - else { - have = 0; - full = 1; - } - - /* process end of block */ - if (strm->data_type & 128) { - if (strm->data_type & 64) - left = strm->data_type & 0x1f; - else { - lastbit = strm->data_type & 0x1f; - lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in; - } - } - } while (ret != Z_STREAM_END); - inflateEnd(strm); - gz.left = strm->avail_in; - gz.next = strm->next_in; - - /* save the location of the end of the compressed data */ - end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; - - /* check gzip trailer and save total for deflate */ - if (crc != read4(&gz)) - bye("invalid compressed data--crc mismatch in ", name); - tot = strm->total_out; - if ((tot & 0xffffffffUL) != read4(&gz)) - bye("invalid compressed data--length mismatch in", name); - - /* if not at end of file, warn */ - if (gz.left || readin(&gz)) - fprintf(stderr, - "gzappend warning: junk at end of gzip file overwritten\n"); - - /* clear last block bit */ - lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET); - if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); - *gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7))); - lseek(gz.fd, -1L, SEEK_CUR); - if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name); - - /* if window wrapped, build dictionary from window by rotating */ - if (full) { - rotate(window, DSIZE, have); - have = DSIZE; - } - - /* set up deflate stream with window, crc, total_in, and leftover bits */ - ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); - if (ret != Z_OK) bye("out of memory", ""); - deflateSetDictionary(strm, window, have); - strm->adler = crc; - strm->total_in = tot; - if (left) { - lseek(gz.fd, --end, SEEK_SET); - if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); - deflatePrime(strm, 8 - left, *gz.buf); - } - lseek(gz.fd, end, SEEK_SET); - - /* clean up and return */ - free(window); - free(gz.buf); - return gz.fd; -} - -/* append file "name" to gzip file gd using deflate stream strm -- if last - is true, then finish off the deflate stream at the end */ -local void gztack(char *name, int gd, z_stream *strm, int last) -{ - int fd, len, ret; - unsigned left; - unsigned char *in, *out; - - /* open file to compress and append */ - fd = 0; - if (name != NULL) { - fd = open(name, O_RDONLY, 0); - if (fd == -1) - fprintf(stderr, "gzappend warning: %s not found, skipping ...\n", - name); - } - - /* allocate buffers */ - in = malloc(CHUNK); - out = malloc(CHUNK); - if (in == NULL || out == NULL) bye("out of memory", ""); - - /* compress input file and append to gzip file */ - do { - /* get more input */ - len = read(fd, in, CHUNK); - if (len == -1) { - fprintf(stderr, - "gzappend warning: error reading %s, skipping rest ...\n", - name); - len = 0; - } - strm->avail_in = (unsigned)len; - strm->next_in = in; - if (len) strm->adler = crc32(strm->adler, in, (unsigned)len); - - /* compress and write all available output */ - do { - strm->avail_out = CHUNK; - strm->next_out = out; - ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH); - left = CHUNK - strm->avail_out; - while (left) { - len = write(gd, out + CHUNK - strm->avail_out - left, left); - if (len == -1) bye("writing gzip file", ""); - left -= (unsigned)len; - } - } while (strm->avail_out == 0 && ret != Z_STREAM_END); - } while (len != 0); - - /* write trailer after last entry */ - if (last) { - deflateEnd(strm); - out[0] = (unsigned char)(strm->adler); - out[1] = (unsigned char)(strm->adler >> 8); - out[2] = (unsigned char)(strm->adler >> 16); - out[3] = (unsigned char)(strm->adler >> 24); - out[4] = (unsigned char)(strm->total_in); - out[5] = (unsigned char)(strm->total_in >> 8); - out[6] = (unsigned char)(strm->total_in >> 16); - out[7] = (unsigned char)(strm->total_in >> 24); - len = 8; - do { - ret = write(gd, out + 8 - len, len); - if (ret == -1) bye("writing gzip file", ""); - len -= ret; - } while (len); - close(gd); - } - - /* clean up and return */ - free(out); - free(in); - if (fd > 0) close(fd); -} - -/* process the compression level option if present, scan the gzip file, and - append the specified files, or append the data from stdin if no other file - names are provided on the command line -- the gzip file must be writable - and seekable */ -int main(int argc, char **argv) -{ - int gd, level; - z_stream strm; - - /* ignore command name */ - argc--; argv++; - - /* provide usage if no arguments */ - if (*argv == NULL) { - printf( - "gzappend 1.2 (11 Oct 2012) Copyright (C) 2003, 2012 Mark Adler\n" - ); - printf( - "usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n"); - return 0; - } - - /* set compression level */ - level = Z_DEFAULT_COMPRESSION; - if (argv[0][0] == '-') { - if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0) - bye("invalid compression level", ""); - level = argv[0][1] - '0'; - if (*++argv == NULL) bye("no gzip file name after options", ""); - } - - /* prepare to append to gzip file */ - gd = gzscan(*argv++, &strm, level); - - /* append files on command line, or from stdin if none */ - if (*argv == NULL) - gztack(NULL, gd, &strm, 1); - else - do { - gztack(*argv, gd, &strm, argv[1] == NULL); - } while (*++argv != NULL); - return 0; -} diff --git a/deps/zlib/examples/gzjoin.c b/deps/zlib/examples/gzjoin.c deleted file mode 100644 index 89e8098441b6b5..00000000000000 --- a/deps/zlib/examples/gzjoin.c +++ /dev/null @@ -1,449 +0,0 @@ -/* gzjoin -- command to join gzip files into one gzip file - - Copyright (C) 2004, 2005, 2012 Mark Adler, all rights reserved - version 1.2, 14 Aug 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* - * Change history: - * - * 1.0 11 Dec 2004 - First version - * 1.1 12 Jun 2005 - Changed ssize_t to long for portability - * 1.2 14 Aug 2012 - Clean up for z_const usage - */ - -/* - gzjoin takes one or more gzip files on the command line and writes out a - single gzip file that will uncompress to the concatenation of the - uncompressed data from the individual gzip files. gzjoin does this without - having to recompress any of the data and without having to calculate a new - crc32 for the concatenated uncompressed data. gzjoin does however have to - decompress all of the input data in order to find the bits in the compressed - data that need to be modified to concatenate the streams. - - gzjoin does not do an integrity check on the input gzip files other than - checking the gzip header and decompressing the compressed data. They are - otherwise assumed to be complete and correct. - - Each joint between gzip files removes at least 18 bytes of previous trailer - and subsequent header, and inserts an average of about three bytes to the - compressed data in order to connect the streams. The output gzip file - has a minimal ten-byte gzip header with no file name or modification time. - - This program was written to illustrate the use of the Z_BLOCK option of - inflate() and the crc32_combine() function. gzjoin will not compile with - versions of zlib earlier than 1.2.3. - */ - -#include /* fputs(), fprintf(), fwrite(), putc() */ -#include /* exit(), malloc(), free() */ -#include /* open() */ -#include /* close(), read(), lseek() */ -#include "zlib.h" - /* crc32(), crc32_combine(), inflateInit2(), inflate(), inflateEnd() */ - -#define local static - -/* exit with an error (return a value to allow use in an expression) */ -local int bail(char *why1, char *why2) -{ - fprintf(stderr, "gzjoin error: %s%s, output incomplete\n", why1, why2); - exit(1); - return 0; -} - -/* -- simple buffered file input with access to the buffer -- */ - -#define CHUNK 32768 /* must be a power of two and fit in unsigned */ - -/* bin buffered input file type */ -typedef struct { - char *name; /* name of file for error messages */ - int fd; /* file descriptor */ - unsigned left; /* bytes remaining at next */ - unsigned char *next; /* next byte to read */ - unsigned char *buf; /* allocated buffer of length CHUNK */ -} bin; - -/* close a buffered file and free allocated memory */ -local void bclose(bin *in) -{ - if (in != NULL) { - if (in->fd != -1) - close(in->fd); - if (in->buf != NULL) - free(in->buf); - free(in); - } -} - -/* open a buffered file for input, return a pointer to type bin, or NULL on - failure */ -local bin *bopen(char *name) -{ - bin *in; - - in = malloc(sizeof(bin)); - if (in == NULL) - return NULL; - in->buf = malloc(CHUNK); - in->fd = open(name, O_RDONLY, 0); - if (in->buf == NULL || in->fd == -1) { - bclose(in); - return NULL; - } - in->left = 0; - in->next = in->buf; - in->name = name; - return in; -} - -/* load buffer from file, return -1 on read error, 0 or 1 on success, with - 1 indicating that end-of-file was reached */ -local int bload(bin *in) -{ - long len; - - if (in == NULL) - return -1; - if (in->left != 0) - return 0; - in->next = in->buf; - do { - len = (long)read(in->fd, in->buf + in->left, CHUNK - in->left); - if (len < 0) - return -1; - in->left += (unsigned)len; - } while (len != 0 && in->left < CHUNK); - return len == 0 ? 1 : 0; -} - -/* get a byte from the file, bail if end of file */ -#define bget(in) (in->left ? 0 : bload(in), \ - in->left ? (in->left--, *(in->next)++) : \ - bail("unexpected end of file on ", in->name)) - -/* get a four-byte little-endian unsigned integer from file */ -local unsigned long bget4(bin *in) -{ - unsigned long val; - - val = bget(in); - val += (unsigned long)(bget(in)) << 8; - val += (unsigned long)(bget(in)) << 16; - val += (unsigned long)(bget(in)) << 24; - return val; -} - -/* skip bytes in file */ -local void bskip(bin *in, unsigned skip) -{ - /* check pointer */ - if (in == NULL) - return; - - /* easy case -- skip bytes in buffer */ - if (skip <= in->left) { - in->left -= skip; - in->next += skip; - return; - } - - /* skip what's in buffer, discard buffer contents */ - skip -= in->left; - in->left = 0; - - /* seek past multiples of CHUNK bytes */ - if (skip > CHUNK) { - unsigned left; - - left = skip & (CHUNK - 1); - if (left == 0) { - /* exact number of chunks: seek all the way minus one byte to check - for end-of-file with a read */ - lseek(in->fd, skip - 1, SEEK_CUR); - if (read(in->fd, in->buf, 1) != 1) - bail("unexpected end of file on ", in->name); - return; - } - - /* skip the integral chunks, update skip with remainder */ - lseek(in->fd, skip - left, SEEK_CUR); - skip = left; - } - - /* read more input and skip remainder */ - bload(in); - if (skip > in->left) - bail("unexpected end of file on ", in->name); - in->left -= skip; - in->next += skip; -} - -/* -- end of buffered input functions -- */ - -/* skip the gzip header from file in */ -local void gzhead(bin *in) -{ - int flags; - - /* verify gzip magic header and compression method */ - if (bget(in) != 0x1f || bget(in) != 0x8b || bget(in) != 8) - bail(in->name, " is not a valid gzip file"); - - /* get and verify flags */ - flags = bget(in); - if ((flags & 0xe0) != 0) - bail("unknown reserved bits set in ", in->name); - - /* skip modification time, extra flags, and os */ - bskip(in, 6); - - /* skip extra field if present */ - if (flags & 4) { - unsigned len; - - len = bget(in); - len += (unsigned)(bget(in)) << 8; - bskip(in, len); - } - - /* skip file name if present */ - if (flags & 8) - while (bget(in) != 0) - ; - - /* skip comment if present */ - if (flags & 16) - while (bget(in) != 0) - ; - - /* skip header crc if present */ - if (flags & 2) - bskip(in, 2); -} - -/* write a four-byte little-endian unsigned integer to out */ -local void put4(unsigned long val, FILE *out) -{ - putc(val & 0xff, out); - putc((val >> 8) & 0xff, out); - putc((val >> 16) & 0xff, out); - putc((val >> 24) & 0xff, out); -} - -/* Load up zlib stream from buffered input, bail if end of file */ -local void zpull(z_streamp strm, bin *in) -{ - if (in->left == 0) - bload(in); - if (in->left == 0) - bail("unexpected end of file on ", in->name); - strm->avail_in = in->left; - strm->next_in = in->next; -} - -/* Write header for gzip file to out and initialize trailer. */ -local void gzinit(unsigned long *crc, unsigned long *tot, FILE *out) -{ - fwrite("\x1f\x8b\x08\0\0\0\0\0\0\xff", 1, 10, out); - *crc = crc32(0L, Z_NULL, 0); - *tot = 0; -} - -/* Copy the compressed data from name, zeroing the last block bit of the last - block if clr is true, and adding empty blocks as needed to get to a byte - boundary. If clr is false, then the last block becomes the last block of - the output, and the gzip trailer is written. crc and tot maintains the - crc and length (modulo 2^32) of the output for the trailer. The resulting - gzip file is written to out. gzinit() must be called before the first call - of gzcopy() to write the gzip header and to initialize crc and tot. */ -local void gzcopy(char *name, int clr, unsigned long *crc, unsigned long *tot, - FILE *out) -{ - int ret; /* return value from zlib functions */ - int pos; /* where the "last block" bit is in byte */ - int last; /* true if processing the last block */ - bin *in; /* buffered input file */ - unsigned char *start; /* start of compressed data in buffer */ - unsigned char *junk; /* buffer for uncompressed data -- discarded */ - z_off_t len; /* length of uncompressed data (support > 4 GB) */ - z_stream strm; /* zlib inflate stream */ - - /* open gzip file and skip header */ - in = bopen(name); - if (in == NULL) - bail("could not open ", name); - gzhead(in); - - /* allocate buffer for uncompressed data and initialize raw inflate - stream */ - junk = malloc(CHUNK); - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -15); - if (junk == NULL || ret != Z_OK) - bail("out of memory", ""); - - /* inflate and copy compressed data, clear last-block bit if requested */ - len = 0; - zpull(&strm, in); - start = in->next; - last = start[0] & 1; - if (last && clr) - start[0] &= ~1; - strm.avail_out = 0; - for (;;) { - /* if input used and output done, write used input and get more */ - if (strm.avail_in == 0 && strm.avail_out != 0) { - fwrite(start, 1, strm.next_in - start, out); - start = in->buf; - in->left = 0; - zpull(&strm, in); - } - - /* decompress -- return early when end-of-block reached */ - strm.avail_out = CHUNK; - strm.next_out = junk; - ret = inflate(&strm, Z_BLOCK); - switch (ret) { - case Z_MEM_ERROR: - bail("out of memory", ""); - case Z_DATA_ERROR: - bail("invalid compressed data in ", in->name); - } - - /* update length of uncompressed data */ - len += CHUNK - strm.avail_out; - - /* check for block boundary (only get this when block copied out) */ - if (strm.data_type & 128) { - /* if that was the last block, then done */ - if (last) - break; - - /* number of unused bits in last byte */ - pos = strm.data_type & 7; - - /* find the next last-block bit */ - if (pos != 0) { - /* next last-block bit is in last used byte */ - pos = 0x100 >> pos; - last = strm.next_in[-1] & pos; - if (last && clr) - in->buf[strm.next_in - in->buf - 1] &= ~pos; - } - else { - /* next last-block bit is in next unused byte */ - if (strm.avail_in == 0) { - /* don't have that byte yet -- get it */ - fwrite(start, 1, strm.next_in - start, out); - start = in->buf; - in->left = 0; - zpull(&strm, in); - } - last = strm.next_in[0] & 1; - if (last && clr) - in->buf[strm.next_in - in->buf] &= ~1; - } - } - } - - /* update buffer with unused input */ - in->left = strm.avail_in; - in->next = in->buf + (strm.next_in - in->buf); - - /* copy used input, write empty blocks to get to byte boundary */ - pos = strm.data_type & 7; - fwrite(start, 1, in->next - start - 1, out); - last = in->next[-1]; - if (pos == 0 || !clr) - /* already at byte boundary, or last file: write last byte */ - putc(last, out); - else { - /* append empty blocks to last byte */ - last &= ((0x100 >> pos) - 1); /* assure unused bits are zero */ - if (pos & 1) { - /* odd -- append an empty stored block */ - putc(last, out); - if (pos == 1) - putc(0, out); /* two more bits in block header */ - fwrite("\0\0\xff\xff", 1, 4, out); - } - else { - /* even -- append 1, 2, or 3 empty fixed blocks */ - switch (pos) { - case 6: - putc(last | 8, out); - last = 0; - case 4: - putc(last | 0x20, out); - last = 0; - case 2: - putc(last | 0x80, out); - putc(0, out); - } - } - } - - /* update crc and tot */ - *crc = crc32_combine(*crc, bget4(in), len); - *tot += (unsigned long)len; - - /* clean up */ - inflateEnd(&strm); - free(junk); - bclose(in); - - /* write trailer if this is the last gzip file */ - if (!clr) { - put4(*crc, out); - put4(*tot, out); - } -} - -/* join the gzip files on the command line, write result to stdout */ -int main(int argc, char **argv) -{ - unsigned long crc, tot; /* running crc and total uncompressed length */ - - /* skip command name */ - argc--; - argv++; - - /* show usage if no arguments */ - if (argc == 0) { - fputs("gzjoin usage: gzjoin f1.gz [f2.gz [f3.gz ...]] > fjoin.gz\n", - stderr); - return 0; - } - - /* join gzip files on command line and write to stdout */ - gzinit(&crc, &tot, stdout); - while (argc--) - gzcopy(*argv++, argc, &crc, &tot, stdout); - - /* done */ - return 0; -} diff --git a/deps/zlib/examples/gzlog.c b/deps/zlib/examples/gzlog.c deleted file mode 100644 index b8c29274e8b9ec..00000000000000 --- a/deps/zlib/examples/gzlog.c +++ /dev/null @@ -1,1059 +0,0 @@ -/* - * gzlog.c - * Copyright (C) 2004, 2008, 2012, 2016 Mark Adler, all rights reserved - * For conditions of distribution and use, see copyright notice in gzlog.h - * version 2.2, 14 Aug 2012 - */ - -/* - gzlog provides a mechanism for frequently appending short strings to a gzip - file that is efficient both in execution time and compression ratio. The - strategy is to write the short strings in an uncompressed form to the end of - the gzip file, only compressing when the amount of uncompressed data has - reached a given threshold. - - gzlog also provides protection against interruptions in the process due to - system crashes. The status of the operation is recorded in an extra field - in the gzip file, and is only updated once the gzip file is brought to a - valid state. The last data to be appended or compressed is saved in an - auxiliary file, so that if the operation is interrupted, it can be completed - the next time an append operation is attempted. - - gzlog maintains another auxiliary file with the last 32K of data from the - compressed portion, which is preloaded for the compression of the subsequent - data. This minimizes the impact to the compression ratio of appending. - */ - -/* - Operations Concept: - - Files (log name "foo"): - foo.gz -- gzip file with the complete log - foo.add -- last message to append or last data to compress - foo.dict -- dictionary of the last 32K of data for next compression - foo.temp -- temporary dictionary file for compression after this one - foo.lock -- lock file for reading and writing the other files - foo.repairs -- log file for log file recovery operations (not compressed) - - gzip file structure: - - fixed-length (no file name) header with extra field (see below) - - compressed data ending initially with empty stored block - - uncompressed data filling out originally empty stored block and - subsequent stored blocks as needed (16K max each) - - gzip trailer - - no junk at end (no other gzip streams) - - When appending data, the information in the first three items above plus the - foo.add file are sufficient to recover an interrupted append operation. The - extra field has the necessary information to restore the start of the last - stored block and determine where to append the data in the foo.add file, as - well as the crc and length of the gzip data before the append operation. - - The foo.add file is created before the gzip file is marked for append, and - deleted after the gzip file is marked as complete. So if the append - operation is interrupted, the data to add will still be there. If due to - some external force, the foo.add file gets deleted between when the append - operation was interrupted and when recovery is attempted, the gzip file will - still be restored, but without the appended data. - - When compressing data, the information in the first two items above plus the - foo.add file are sufficient to recover an interrupted compress operation. - The extra field has the necessary information to find the end of the - compressed data, and contains both the crc and length of just the compressed - data and of the complete set of data including the contents of the foo.add - file. - - Again, the foo.add file is maintained during the compress operation in case - of an interruption. If in the unlikely event the foo.add file with the data - to be compressed is missing due to some external force, a gzip file with - just the previous compressed data will be reconstructed. In this case, all - of the data that was to be compressed is lost (approximately one megabyte). - This will not occur if all that happened was an interruption of the compress - operation. - - The third state that is marked is the replacement of the old dictionary with - the new dictionary after a compress operation. Once compression is - complete, the gzip file is marked as being in the replace state. This - completes the gzip file, so an interrupt after being so marked does not - result in recompression. Then the dictionary file is replaced, and the gzip - file is marked as completed. This state prevents the possibility of - restarting compression with the wrong dictionary file. - - All three operations are wrapped by a lock/unlock procedure. In order to - gain exclusive access to the log files, first a foo.lock file must be - exclusively created. When all operations are complete, the lock is - released by deleting the foo.lock file. If when attempting to create the - lock file, it already exists and the modify time of the lock file is more - than five minutes old (set by the PATIENCE define below), then the old - lock file is considered stale and deleted, and the exclusive creation of - the lock file is retried. To assure that there are no false assessments - of the staleness of the lock file, the operations periodically touch the - lock file to update the modified date. - - Following is the definition of the extra field with all of the information - required to enable the above append and compress operations and their - recovery if interrupted. Multi-byte values are stored little endian - (consistent with the gzip format). File pointers are eight bytes long. - The crc's and lengths for the gzip trailer are four bytes long. (Note that - the length at the end of a gzip file is used for error checking only, and - for large files is actually the length modulo 2^32.) The stored block - length is two bytes long. The gzip extra field two-byte identification is - "ap" for append. It is assumed that writing the extra field to the file is - an "atomic" operation. That is, either all of the extra field is written - to the file, or none of it is, if the operation is interrupted right at the - point of updating the extra field. This is a reasonable assumption, since - the extra field is within the first 52 bytes of the file, which is smaller - than any expected block size for a mass storage device (usually 512 bytes or - larger). - - Extra field (35 bytes): - - Pointer to first stored block length -- this points to the two-byte length - of the first stored block, which is followed by the two-byte, one's - complement of that length. The stored block length is preceded by the - three-bit header of the stored block, which is the actual start of the - stored block in the deflate format. See the bit offset field below. - - Pointer to the last stored block length. This is the same as above, but - for the last stored block of the uncompressed data in the gzip file. - Initially this is the same as the first stored block length pointer. - When the stored block gets to 16K (see the MAX_STORE define), then a new - stored block as added, at which point the last stored block length pointer - is different from the first stored block length pointer. When they are - different, the first bit of the last stored block header is eight bits, or - one byte back from the block length. - - Compressed data crc and length. This is the crc and length of the data - that is in the compressed portion of the deflate stream. These are used - only in the event that the foo.add file containing the data to compress is - lost after a compress operation is interrupted. - - Total data crc and length. This is the crc and length of all of the data - stored in the gzip file, compressed and uncompressed. It is used to - reconstruct the gzip trailer when compressing, as well as when recovering - interrupted operations. - - Final stored block length. This is used to quickly find where to append, - and allows the restoration of the original final stored block state when - an append operation is interrupted. - - First stored block start as the number of bits back from the final stored - block first length byte. This value is in the range of 3..10, and is - stored as the low three bits of the final byte of the extra field after - subtracting three (0..7). This allows the last-block bit of the stored - block header to be updated when a new stored block is added, for the case - when the first stored block and the last stored block are the same. (When - they are different, the numbers of bits back is known to be eight.) This - also allows for new compressed data to be appended to the old compressed - data in the compress operation, overwriting the previous first stored - block, or for the compressed data to be terminated and a valid gzip file - reconstructed on the off chance that a compression operation was - interrupted and the data to compress in the foo.add file was deleted. - - The operation in process. This is the next two bits in the last byte (the - bits under the mask 0x18). The are interpreted as 0: nothing in process, - 1: append in process, 2: compress in process, 3: replace in process. - - The top three bits of the last byte in the extra field are reserved and - are currently set to zero. - - Main procedure: - - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of - the system open() call. If the modify time of an existing lock file is - more than PATIENCE seconds old, then the lock file is deleted and the - exclusive create is retried. - - Load the extra field from the foo.gz file, and see if an operation was in - progress but not completed. If so, apply the recovery procedure below. - - Perform the append procedure with the provided data. - - If the uncompressed data in the foo.gz file is 1MB or more, apply the - compress procedure. - - Delete the foo.lock file. - - Append procedure: - - Put what to append in the foo.add file so that the operation can be - restarted if this procedure is interrupted. - - Mark the foo.gz extra field with the append operation in progress. - + Restore the original last-block bit and stored block length of the last - stored block from the information in the extra field, in case a previous - append operation was interrupted. - - Append the provided data to the last stored block, creating new stored - blocks as needed and updating the stored blocks last-block bits and - lengths. - - Update the crc and length with the new data, and write the gzip trailer. - - Write over the extra field (with a single write operation) with the new - pointers, lengths, and crc's, and mark the gzip file as not in process. - Though there is still a foo.add file, it will be ignored since nothing - is in process. If a foo.add file is leftover from a previously - completed operation, it is truncated when writing new data to it. - - Delete the foo.add file. - - Compress and replace procedures: - - Read all of the uncompressed data in the stored blocks in foo.gz and write - it to foo.add. Also write foo.temp with the last 32K of that data to - provide a dictionary for the next invocation of this procedure. - - Rewrite the extra field marking foo.gz with a compression in process. - * If there is no data provided to compress (due to a missing foo.add file - when recovering), reconstruct and truncate the foo.gz file to contain - only the previous compressed data and proceed to the step after the next - one. Otherwise ... - - Compress the data with the dictionary in foo.dict, and write to the - foo.gz file starting at the bit immediately following the last previously - compressed block. If there is no foo.dict, proceed anyway with the - compression at slightly reduced efficiency. (For the foo.dict file to be - missing requires some external failure beyond simply the interruption of - a compress operation.) During this process, the foo.lock file is - periodically touched to assure that that file is not considered stale by - another process before we're done. The deflation is terminated with a - non-last empty static block (10 bits long), that is then located and - written over by a last-bit-set empty stored block. - - Append the crc and length of the data in the gzip file (previously - calculated during the append operations). - - Write over the extra field with the updated stored block offsets, bits - back, crc's, and lengths, and mark foo.gz as in process for a replacement - of the dictionary. - @ Delete the foo.add file. - - Replace foo.dict with foo.temp. - - Write over the extra field, marking foo.gz as complete. - - Recovery procedure: - - If not a replace recovery, read in the foo.add file, and provide that data - to the appropriate recovery below. If there is no foo.add file, provide - a zero data length to the recovery. In that case, the append recovery - restores the foo.gz to the previous compressed + uncompressed data state. - For the the compress recovery, a missing foo.add file results in foo.gz - being restored to the previous compressed-only data state. - - Append recovery: - - Pick up append at + step above - - Compress recovery: - - Pick up compress at * step above - - Replace recovery: - - Pick up compress at @ step above - - Log the repair with a date stamp in foo.repairs - */ - -#include -#include /* rename, fopen, fprintf, fclose */ -#include /* malloc, free */ -#include /* strlen, strrchr, strcpy, strncpy, strcmp */ -#include /* open */ -#include /* lseek, read, write, close, unlink, sleep, */ - /* ftruncate, fsync */ -#include /* errno */ -#include /* time, ctime */ -#include /* stat */ -#include /* utimes */ -#include "zlib.h" /* crc32 */ - -#include "gzlog.h" /* header for external access */ - -#define local static -typedef unsigned int uint; -typedef unsigned long ulong; - -/* Macro for debugging to deterministically force recovery operations */ -#ifdef GZLOG_DEBUG - #include /* longjmp */ - jmp_buf gzlog_jump; /* where to go back to */ - int gzlog_bail = 0; /* which point to bail at (1..8) */ - int gzlog_count = -1; /* number of times through to wait */ -# define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \ - longjmp(gzlog_jump, gzlog_bail); } while (0) -#else -# define BAIL(n) -#endif - -/* how old the lock file can be in seconds before considering it stale */ -#define PATIENCE 300 - -/* maximum stored block size in Kbytes -- must be in 1..63 */ -#define MAX_STORE 16 - -/* number of stored Kbytes to trigger compression (must be >= 32 to allow - dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to - discard the stored block headers contribution of five bytes each) */ -#define TRIGGER 1024 - -/* size of a deflate dictionary (this cannot be changed) */ -#define DICT 32768U - -/* values for the operation (2 bits) */ -#define NO_OP 0 -#define APPEND_OP 1 -#define COMPRESS_OP 2 -#define REPLACE_OP 3 - -/* macros to extract little-endian integers from an unsigned byte buffer */ -#define PULL2(p) ((p)[0]+((uint)((p)[1])<<8)) -#define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16)) -#define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32)) - -/* macros to store integers into a byte buffer in little-endian order */ -#define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0) -#define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0) -#define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0) - -/* internal structure for log information */ -#define LOGID "\106\035\172" /* should be three non-zero characters */ -struct log { - char id[4]; /* contains LOGID to detect inadvertent overwrites */ - int fd; /* file descriptor for .gz file, opened read/write */ - char *path; /* allocated path, e.g. "/var/log/foo" or "foo" */ - char *end; /* end of path, for appending suffices such as ".gz" */ - off_t first; /* offset of first stored block first length byte */ - int back; /* location of first block id in bits back from first */ - uint stored; /* bytes currently in last stored block */ - off_t last; /* offset of last stored block first length byte */ - ulong ccrc; /* crc of compressed data */ - ulong clen; /* length (modulo 2^32) of compressed data */ - ulong tcrc; /* crc of total data */ - ulong tlen; /* length (modulo 2^32) of total data */ - time_t lock; /* last modify time of our lock file */ -}; - -/* gzip header for gzlog */ -local unsigned char log_gzhead[] = { - 0x1f, 0x8b, /* magic gzip id */ - 8, /* compression method is deflate */ - 4, /* there is an extra field (no file name) */ - 0, 0, 0, 0, /* no modification time provided */ - 0, 0xff, /* no extra flags, no OS specified */ - 39, 0, 'a', 'p', 35, 0 /* extra field with "ap" subfield */ - /* 35 is EXTRA, 39 is EXTRA + 4 */ -}; - -#define HEAD sizeof(log_gzhead) /* should be 16 */ - -/* initial gzip extra field content (52 == HEAD + EXTRA + 1) */ -local unsigned char log_gzext[] = { - 52, 0, 0, 0, 0, 0, 0, 0, /* offset of first stored block length */ - 52, 0, 0, 0, 0, 0, 0, 0, /* offset of last stored block length */ - 0, 0, 0, 0, 0, 0, 0, 0, /* compressed data crc and length */ - 0, 0, 0, 0, 0, 0, 0, 0, /* total data crc and length */ - 0, 0, /* final stored block data length */ - 5 /* op is NO_OP, last bit 8 bits back */ -}; - -#define EXTRA sizeof(log_gzext) /* should be 35 */ - -/* initial gzip data and trailer */ -local unsigned char log_gzbody[] = { - 1, 0, 0, 0xff, 0xff, /* empty stored block (last) */ - 0, 0, 0, 0, /* crc */ - 0, 0, 0, 0 /* uncompressed length */ -}; - -#define BODY sizeof(log_gzbody) - -/* Exclusively create foo.lock in order to negotiate exclusive access to the - foo.* files. If the modify time of an existing lock file is greater than - PATIENCE seconds in the past, then consider the lock file to have been - abandoned, delete it, and try the exclusive create again. Save the lock - file modify time for verification of ownership. Return 0 on success, or -1 - on failure, usually due to an access restriction or invalid path. Note that - if stat() or unlink() fails, it may be due to another process noticing the - abandoned lock file a smidge sooner and deleting it, so those are not - flagged as an error. */ -local int log_lock(struct log *log) -{ - int fd; - struct stat st; - - strcpy(log->end, ".lock"); - while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) { - if (errno != EEXIST) - return -1; - if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) { - unlink(log->path); - continue; - } - sleep(2); /* relinquish the CPU for two seconds while waiting */ - } - close(fd); - if (stat(log->path, &st) == 0) - log->lock = st.st_mtime; - return 0; -} - -/* Update the modify time of the lock file to now, in order to prevent another - task from thinking that the lock is stale. Save the lock file modify time - for verification of ownership. */ -local void log_touch(struct log *log) -{ - struct stat st; - - strcpy(log->end, ".lock"); - utimes(log->path, NULL); - if (stat(log->path, &st) == 0) - log->lock = st.st_mtime; -} - -/* Check the log file modify time against what is expected. Return true if - this is not our lock. If it is our lock, touch it to keep it. */ -local int log_check(struct log *log) -{ - struct stat st; - - strcpy(log->end, ".lock"); - if (stat(log->path, &st) || st.st_mtime != log->lock) - return 1; - log_touch(log); - return 0; -} - -/* Unlock a previously acquired lock, but only if it's ours. */ -local void log_unlock(struct log *log) -{ - if (log_check(log)) - return; - strcpy(log->end, ".lock"); - unlink(log->path); - log->lock = 0; -} - -/* Check the gzip header and read in the extra field, filling in the values in - the log structure. Return op on success or -1 if the gzip header was not as - expected. op is the current operation in progress last written to the extra - field. This assumes that the gzip file has already been opened, with the - file descriptor log->fd. */ -local int log_head(struct log *log) -{ - int op; - unsigned char buf[HEAD + EXTRA]; - - if (lseek(log->fd, 0, SEEK_SET) < 0 || - read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA || - memcmp(buf, log_gzhead, HEAD)) { - return -1; - } - log->first = PULL8(buf + HEAD); - log->last = PULL8(buf + HEAD + 8); - log->ccrc = PULL4(buf + HEAD + 16); - log->clen = PULL4(buf + HEAD + 20); - log->tcrc = PULL4(buf + HEAD + 24); - log->tlen = PULL4(buf + HEAD + 28); - log->stored = PULL2(buf + HEAD + 32); - log->back = 3 + (buf[HEAD + 34] & 7); - op = (buf[HEAD + 34] >> 3) & 3; - return op; -} - -/* Write over the extra field contents, marking the operation as op. Use fsync - to assure that the device is written to, and in the requested order. This - operation, and only this operation, is assumed to be atomic in order to - assure that the log is recoverable in the event of an interruption at any - point in the process. Return -1 if the write to foo.gz failed. */ -local int log_mark(struct log *log, int op) -{ - int ret; - unsigned char ext[EXTRA]; - - PUT8(ext, log->first); - PUT8(ext + 8, log->last); - PUT4(ext + 16, log->ccrc); - PUT4(ext + 20, log->clen); - PUT4(ext + 24, log->tcrc); - PUT4(ext + 28, log->tlen); - PUT2(ext + 32, log->stored); - ext[34] = log->back - 3 + (op << 3); - fsync(log->fd); - ret = lseek(log->fd, HEAD, SEEK_SET) < 0 || - write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0; - fsync(log->fd); - return ret; -} - -/* Rewrite the last block header bits and subsequent zero bits to get to a byte - boundary, setting the last block bit if last is true, and then write the - remainder of the stored block header (length and one's complement). Leave - the file pointer after the end of the last stored block data. Return -1 if - there is a read or write failure on the foo.gz file */ -local int log_last(struct log *log, int last) -{ - int back, len, mask; - unsigned char buf[6]; - - /* determine the locations of the bytes and bits to modify */ - back = log->last == log->first ? log->back : 8; - len = back > 8 ? 2 : 1; /* bytes back from log->last */ - mask = 0x80 >> ((back - 1) & 7); /* mask for block last-bit */ - - /* get the byte to modify (one or two back) into buf[0] -- don't need to - read the byte if the last-bit is eight bits back, since in that case - the entire byte will be modified */ - buf[0] = 0; - if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 || - read(log->fd, buf, 1) != 1)) - return -1; - - /* change the last-bit of the last stored block as requested -- note - that all bits above the last-bit are set to zero, per the type bits - of a stored block being 00 and per the convention that the bits to - bring the stream to a byte boundary are also zeros */ - buf[1] = 0; - buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0); - - /* write the modified stored block header and lengths, move the file - pointer to after the last stored block data */ - PUT2(buf + 2, log->stored); - PUT2(buf + 4, log->stored ^ 0xffff); - return lseek(log->fd, log->last - len, SEEK_SET) < 0 || - write(log->fd, buf + 2 - len, len + 4) != len + 4 || - lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0; -} - -/* Append len bytes from data to the locked and open log file. len may be zero - if recovering and no .add file was found. In that case, the previous state - of the foo.gz file is restored. The data is appended uncompressed in - deflate stored blocks. Return -1 if there was an error reading or writing - the foo.gz file. */ -local int log_append(struct log *log, unsigned char *data, size_t len) -{ - uint put; - off_t end; - unsigned char buf[8]; - - /* set the last block last-bit and length, in case recovering an - interrupted append, then position the file pointer to append to the - block */ - if (log_last(log, 1)) - return -1; - - /* append, adding stored blocks and updating the offset of the last stored - block as needed, and update the total crc and length */ - while (len) { - /* append as much as we can to the last block */ - put = (MAX_STORE << 10) - log->stored; - if (put > len) - put = (uint)len; - if (put) { - if (write(log->fd, data, put) != put) - return -1; - BAIL(1); - log->tcrc = crc32(log->tcrc, data, put); - log->tlen += put; - log->stored += put; - data += put; - len -= put; - } - - /* if we need to, add a new empty stored block */ - if (len) { - /* mark current block as not last */ - if (log_last(log, 0)) - return -1; - - /* point to new, empty stored block */ - log->last += 4 + log->stored + 1; - log->stored = 0; - } - - /* mark last block as last, update its length */ - if (log_last(log, 1)) - return -1; - BAIL(2); - } - - /* write the new crc and length trailer, and truncate just in case (could - be recovering from partial append with a missing foo.add file) */ - PUT4(buf, log->tcrc); - PUT4(buf + 4, log->tlen); - if (write(log->fd, buf, 8) != 8 || - (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) - return -1; - - /* write the extra field, marking the log file as done, delete .add file */ - if (log_mark(log, NO_OP)) - return -1; - strcpy(log->end, ".add"); - unlink(log->path); /* ignore error, since may not exist */ - return 0; -} - -/* Replace the foo.dict file with the foo.temp file. Also delete the foo.add - file, since the compress operation may have been interrupted before that was - done. Returns 1 if memory could not be allocated, or -1 if reading or - writing foo.gz fails, or if the rename fails for some reason other than - foo.temp not existing. foo.temp not existing is a permitted error, since - the replace operation may have been interrupted after the rename is done, - but before foo.gz is marked as complete. */ -local int log_replace(struct log *log) -{ - int ret; - char *dest; - - /* delete foo.add file */ - strcpy(log->end, ".add"); - unlink(log->path); /* ignore error, since may not exist */ - BAIL(3); - - /* rename foo.name to foo.dict, replacing foo.dict if it exists */ - strcpy(log->end, ".dict"); - dest = malloc(strlen(log->path) + 1); - if (dest == NULL) - return -2; - strcpy(dest, log->path); - strcpy(log->end, ".temp"); - ret = rename(log->path, dest); - free(dest); - if (ret && errno != ENOENT) - return -1; - BAIL(4); - - /* mark the foo.gz file as done */ - return log_mark(log, NO_OP); -} - -/* Compress the len bytes at data and append the compressed data to the - foo.gz deflate data immediately after the previous compressed data. This - overwrites the previous uncompressed data, which was stored in foo.add - and is the data provided in data[0..len-1]. If this operation is - interrupted, it picks up at the start of this routine, with the foo.add - file read in again. If there is no data to compress (len == 0), then we - simply terminate the foo.gz file after the previously compressed data, - appending a final empty stored block and the gzip trailer. Return -1 if - reading or writing the log.gz file failed, or -2 if there was a memory - allocation failure. */ -local int log_compress(struct log *log, unsigned char *data, size_t len) -{ - int fd; - uint got, max; - ssize_t dict; - off_t end; - z_stream strm; - unsigned char buf[DICT]; - - /* compress and append compressed data */ - if (len) { - /* set up for deflate, allocating memory */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, - Z_DEFAULT_STRATEGY) != Z_OK) - return -2; - - /* read in dictionary (last 32K of data that was compressed) */ - strcpy(log->end, ".dict"); - fd = open(log->path, O_RDONLY, 0); - if (fd >= 0) { - dict = read(fd, buf, DICT); - close(fd); - if (dict < 0) { - deflateEnd(&strm); - return -1; - } - if (dict) - deflateSetDictionary(&strm, buf, (uint)dict); - } - log_touch(log); - - /* prime deflate with last bits of previous block, position write - pointer to write those bits and overwrite what follows */ - if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1), - SEEK_SET) < 0 || - read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) { - deflateEnd(&strm); - return -1; - } - deflatePrime(&strm, (8 - log->back) & 7, *buf); - - /* compress, finishing with a partial non-last empty static block */ - strm.next_in = data; - max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */ - do { - strm.avail_in = len > max ? max : (uint)len; - len -= strm.avail_in; - do { - strm.avail_out = DICT; - strm.next_out = buf; - deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH); - got = DICT - strm.avail_out; - if (got && write(log->fd, buf, got) != got) { - deflateEnd(&strm); - return -1; - } - log_touch(log); - } while (strm.avail_out == 0); - } while (len); - deflateEnd(&strm); - BAIL(5); - - /* find start of empty static block -- scanning backwards the first one - bit is the second bit of the block, if the last byte is zero, then - we know the byte before that has a one in the top bit, since an - empty static block is ten bits long */ - if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 || - read(log->fd, buf, 1) != 1) - return -1; - log->first++; - if (*buf) { - log->back = 1; - while ((*buf & ((uint)1 << (8 - log->back++))) == 0) - ; /* guaranteed to terminate, since *buf != 0 */ - } - else - log->back = 10; - - /* update compressed crc and length */ - log->ccrc = log->tcrc; - log->clen = log->tlen; - } - else { - /* no data to compress -- fix up existing gzip stream */ - log->tcrc = log->ccrc; - log->tlen = log->clen; - } - - /* complete and truncate gzip stream */ - log->last = log->first; - log->stored = 0; - PUT4(buf, log->tcrc); - PUT4(buf + 4, log->tlen); - if (log_last(log, 1) || write(log->fd, buf, 8) != 8 || - (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) - return -1; - BAIL(6); - - /* mark as being in the replace operation */ - if (log_mark(log, REPLACE_OP)) - return -1; - - /* execute the replace operation and mark the file as done */ - return log_replace(log); -} - -/* log a repair record to the .repairs file */ -local void log_log(struct log *log, int op, char *record) -{ - time_t now; - FILE *rec; - - now = time(NULL); - strcpy(log->end, ".repairs"); - rec = fopen(log->path, "a"); - if (rec == NULL) - return; - fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ? - "append" : (op == COMPRESS_OP ? "compress" : "replace"), record); - fclose(rec); - return; -} - -/* Recover the interrupted operation op. First read foo.add for recovering an - append or compress operation. Return -1 if there was an error reading or - writing foo.gz or reading an existing foo.add, or -2 if there was a memory - allocation failure. */ -local int log_recover(struct log *log, int op) -{ - int fd, ret = 0; - unsigned char *data = NULL; - size_t len = 0; - struct stat st; - - /* log recovery */ - log_log(log, op, "start"); - - /* load foo.add file if expected and present */ - if (op == APPEND_OP || op == COMPRESS_OP) { - strcpy(log->end, ".add"); - if (stat(log->path, &st) == 0 && st.st_size) { - len = (size_t)(st.st_size); - if ((off_t)len != st.st_size || - (data = malloc(st.st_size)) == NULL) { - log_log(log, op, "allocation failure"); - return -2; - } - if ((fd = open(log->path, O_RDONLY, 0)) < 0) { - log_log(log, op, ".add file read failure"); - return -1; - } - ret = (size_t)read(fd, data, len) != len; - close(fd); - if (ret) { - log_log(log, op, ".add file read failure"); - return -1; - } - log_log(log, op, "loaded .add file"); - } - else - log_log(log, op, "missing .add file!"); - } - - /* recover the interrupted operation */ - switch (op) { - case APPEND_OP: - ret = log_append(log, data, len); - break; - case COMPRESS_OP: - ret = log_compress(log, data, len); - break; - case REPLACE_OP: - ret = log_replace(log); - } - - /* log status */ - log_log(log, op, ret ? "failure" : "complete"); - - /* clean up */ - if (data != NULL) - free(data); - return ret; -} - -/* Close the foo.gz file (if open) and release the lock. */ -local void log_close(struct log *log) -{ - if (log->fd >= 0) - close(log->fd); - log->fd = -1; - log_unlock(log); -} - -/* Open foo.gz, verify the header, and load the extra field contents, after - first creating the foo.lock file to gain exclusive access to the foo.* - files. If foo.gz does not exist or is empty, then write the initial header, - extra, and body content of an empty foo.gz log file. If there is an error - creating the lock file due to access restrictions, or an error reading or - writing the foo.gz file, or if the foo.gz file is not a proper log file for - this object (e.g. not a gzip file or does not contain the expected extra - field), then return true. If there is an error, the lock is released. - Otherwise, the lock is left in place. */ -local int log_open(struct log *log) -{ - int op; - - /* release open file resource if left over -- can occur if lock lost - between gzlog_open() and gzlog_write() */ - if (log->fd >= 0) - close(log->fd); - log->fd = -1; - - /* negotiate exclusive access */ - if (log_lock(log) < 0) - return -1; - - /* open the log file, foo.gz */ - strcpy(log->end, ".gz"); - log->fd = open(log->path, O_RDWR | O_CREAT, 0644); - if (log->fd < 0) { - log_close(log); - return -1; - } - - /* if new, initialize foo.gz with an empty log, delete old dictionary */ - if (lseek(log->fd, 0, SEEK_END) == 0) { - if (write(log->fd, log_gzhead, HEAD) != HEAD || - write(log->fd, log_gzext, EXTRA) != EXTRA || - write(log->fd, log_gzbody, BODY) != BODY) { - log_close(log); - return -1; - } - strcpy(log->end, ".dict"); - unlink(log->path); - } - - /* verify log file and load extra field information */ - if ((op = log_head(log)) < 0) { - log_close(log); - return -1; - } - - /* check for interrupted process and if so, recover */ - if (op != NO_OP && log_recover(log, op)) { - log_close(log); - return -1; - } - - /* touch the lock file to prevent another process from grabbing it */ - log_touch(log); - return 0; -} - -/* See gzlog.h for the description of the external methods below */ -gzlog *gzlog_open(char *path) -{ - size_t n; - struct log *log; - - /* check arguments */ - if (path == NULL || *path == 0) - return NULL; - - /* allocate and initialize log structure */ - log = malloc(sizeof(struct log)); - if (log == NULL) - return NULL; - strcpy(log->id, LOGID); - log->fd = -1; - - /* save path and end of path for name construction */ - n = strlen(path); - log->path = malloc(n + 9); /* allow for ".repairs" */ - if (log->path == NULL) { - free(log); - return NULL; - } - strcpy(log->path, path); - log->end = log->path + n; - - /* gain exclusive access and verify log file -- may perform a - recovery operation if needed */ - if (log_open(log)) { - free(log->path); - free(log); - return NULL; - } - - /* return pointer to log structure */ - return log; -} - -/* gzlog_compress() return values: - 0: all good - -1: file i/o error (usually access issue) - -2: memory allocation failure - -3: invalid log pointer argument */ -int gzlog_compress(gzlog *logd) -{ - int fd, ret; - uint block; - size_t len, next; - unsigned char *data, buf[5]; - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - - /* see if we lost the lock -- if so get it again and reload the extra - field information (it probably changed), recover last operation if - necessary */ - if (log_check(log) && log_open(log)) - return -1; - - /* create space for uncompressed data */ - len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) + - log->stored; - if ((data = malloc(len)) == NULL) - return -2; - - /* do statement here is just a cheap trick for error handling */ - do { - /* read in the uncompressed data */ - if (lseek(log->fd, log->first - 1, SEEK_SET) < 0) - break; - next = 0; - while (next < len) { - if (read(log->fd, buf, 5) != 5) - break; - block = PULL2(buf + 1); - if (next + block > len || - read(log->fd, (char *)data + next, block) != block) - break; - next += block; - } - if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored) - break; - log_touch(log); - - /* write the uncompressed data to the .add file */ - strcpy(log->end, ".add"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - break; - ret = (size_t)write(fd, data, len) != len; - if (ret | close(fd)) - break; - log_touch(log); - - /* write the dictionary for the next compress to the .temp file */ - strcpy(log->end, ".temp"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - break; - next = DICT > len ? len : DICT; - ret = (size_t)write(fd, (char *)data + len - next, next) != next; - if (ret | close(fd)) - break; - log_touch(log); - - /* roll back to compressed data, mark the compress in progress */ - log->last = log->first; - log->stored = 0; - if (log_mark(log, COMPRESS_OP)) - break; - BAIL(7); - - /* compress and append the data (clears mark) */ - ret = log_compress(log, data, len); - free(data); - return ret; - } while (0); - - /* broke out of do above on i/o error */ - free(data); - return -1; -} - -/* gzlog_write() return values: - 0: all good - -1: file i/o error (usually access issue) - -2: memory allocation failure - -3: invalid log pointer argument */ -int gzlog_write(gzlog *logd, void *data, size_t len) -{ - int fd, ret; - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - if (data == NULL || len <= 0) - return 0; - - /* see if we lost the lock -- if so get it again and reload the extra - field information (it probably changed), recover last operation if - necessary */ - if (log_check(log) && log_open(log)) - return -1; - - /* create and write .add file */ - strcpy(log->end, ".add"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - return -1; - ret = (size_t)write(fd, data, len) != len; - if (ret | close(fd)) - return -1; - log_touch(log); - - /* mark log file with append in progress */ - if (log_mark(log, APPEND_OP)) - return -1; - BAIL(8); - - /* append data (clears mark) */ - if (log_append(log, data, len)) - return -1; - - /* check to see if it's time to compress -- if not, then done */ - if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER) - return 0; - - /* time to compress */ - return gzlog_compress(log); -} - -/* gzlog_close() return values: - 0: ok - -3: invalid log pointer argument */ -int gzlog_close(gzlog *logd) -{ - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - - /* close the log file and release the lock */ - log_close(log); - - /* free structure and return */ - if (log->path != NULL) - free(log->path); - strcpy(log->id, "bad"); - free(log); - return 0; -} diff --git a/deps/zlib/examples/gzlog.h b/deps/zlib/examples/gzlog.h deleted file mode 100644 index 86f0cecba5b402..00000000000000 --- a/deps/zlib/examples/gzlog.h +++ /dev/null @@ -1,91 +0,0 @@ -/* gzlog.h - Copyright (C) 2004, 2008, 2012 Mark Adler, all rights reserved - version 2.2, 14 Aug 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* Version History: - 1.0 26 Nov 2004 First version - 2.0 25 Apr 2008 Complete redesign for recovery of interrupted operations - Interface changed slightly in that now path is a prefix - Compression now occurs as needed during gzlog_write() - gzlog_write() now always leaves the log file as valid gzip - 2.1 8 Jul 2012 Fix argument checks in gzlog_compress() and gzlog_write() - 2.2 14 Aug 2012 Clean up signed comparisons - */ - -/* - The gzlog object allows writing short messages to a gzipped log file, - opening the log file locked for small bursts, and then closing it. The log - object works by appending stored (uncompressed) data to the gzip file until - 1 MB has been accumulated. At that time, the stored data is compressed, and - replaces the uncompressed data in the file. The log file is truncated to - its new size at that time. After each write operation, the log file is a - valid gzip file that can decompressed to recover what was written. - - The gzlog operations can be interupted at any point due to an application or - system crash, and the log file will be recovered the next time the log is - opened with gzlog_open(). - */ - -#ifndef GZLOG_H -#define GZLOG_H - -/* gzlog object type */ -typedef void gzlog; - -/* Open a gzlog object, creating the log file if it does not exist. Return - NULL on error. Note that gzlog_open() could take a while to complete if it - has to wait to verify that a lock is stale (possibly for five minutes), or - if there is significant contention with other instantiations of this object - when locking the resource. path is the prefix of the file names created by - this object. If path is "foo", then the log file will be "foo.gz", and - other auxiliary files will be created and destroyed during the process: - "foo.dict" for a compression dictionary, "foo.temp" for a temporary (next) - dictionary, "foo.add" for data being added or compressed, "foo.lock" for the - lock file, and "foo.repairs" to log recovery operations performed due to - interrupted gzlog operations. A gzlog_open() followed by a gzlog_close() - will recover a previously interrupted operation, if any. */ -gzlog *gzlog_open(char *path); - -/* Write to a gzlog object. Return zero on success, -1 if there is a file i/o - error on any of the gzlog files (this should not happen if gzlog_open() - succeeded, unless the device has run out of space or leftover auxiliary - files have permissions or ownership that prevent their use), -2 if there is - a memory allocation failure, or -3 if the log argument is invalid (e.g. if - it was not created by gzlog_open()). This function will write data to the - file uncompressed, until 1 MB has been accumulated, at which time that data - will be compressed. The log file will be a valid gzip file upon successful - return. */ -int gzlog_write(gzlog *log, void *data, size_t len); - -/* Force compression of any uncompressed data in the log. This should be used - sparingly, if at all. The main application would be when a log file will - not be appended to again. If this is used to compress frequently while - appending, it will both significantly increase the execution time and - reduce the compression ratio. The return codes are the same as for - gzlog_write(). */ -int gzlog_compress(gzlog *log); - -/* Close a gzlog object. Return zero on success, -3 if the log argument is - invalid. The log object is freed, and so cannot be referenced again. */ -int gzlog_close(gzlog *log); - -#endif diff --git a/deps/zlib/examples/zlib_how.html b/deps/zlib/examples/zlib_how.html deleted file mode 100644 index 444ff1c9a32e85..00000000000000 --- a/deps/zlib/examples/zlib_how.html +++ /dev/null @@ -1,545 +0,0 @@ - - - - -zlib Usage Example - - - -

zlib Usage Example

-We often get questions about how the deflate() and inflate() functions should be used. -Users wonder when they should provide more input, when they should use more output, -what to do with a Z_BUF_ERROR, how to make sure the process terminates properly, and -so on. So for those who have read zlib.h (a few times), and -would like further edification, below is an annotated example in C of simple routines to compress and decompress -from an input file to an output file using deflate() and inflate() respectively. The -annotations are interspersed between lines of the code. So please read between the lines. -We hope this helps explain some of the intricacies of zlib. -

-Without further adieu, here is the program zpipe.c: -


-/* zpipe.c: example of proper use of zlib's inflate() and deflate()
-   Not copyrighted -- provided to the public domain
-   Version 1.4  11 December 2005  Mark Adler */
-
-/* Version history:
-   1.0  30 Oct 2004  First version
-   1.1   8 Nov 2004  Add void casting for unused return values
-                     Use switch statement for inflate() return values
-   1.2   9 Nov 2004  Add assertions to document zlib guarantees
-   1.3   6 Apr 2005  Remove incorrect assertion in inf()
-   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
-                     Avoid some compiler warnings for input and output buffers
- */
-
-We now include the header files for the required definitions. From -stdio.h we use fopen(), fread(), fwrite(), -feof(), ferror(), and fclose() for file i/o, and -fputs() for error messages. From string.h we use -strcmp() for command line argument processing. -From assert.h we use the assert() macro. -From zlib.h -we use the basic compression functions deflateInit(), -deflate(), and deflateEnd(), and the basic decompression -functions inflateInit(), inflate(), and -inflateEnd(). -

-#include <stdio.h>
-#include <string.h>
-#include <assert.h>
-#include "zlib.h"
-
-This is an ugly hack required to avoid corruption of the input and output data on -Windows/MS-DOS systems. Without this, those systems would assume that the input and output -files are text, and try to convert the end-of-line characters from one standard to -another. That would corrupt binary data, and in particular would render the compressed data unusable. -This sets the input and output to binary which suppresses the end-of-line conversions. -SET_BINARY_MODE() will be used later on stdin and stdout, at the beginning of main(). -

-#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
-#  include <fcntl.h>
-#  include <io.h>
-#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
-#else
-#  define SET_BINARY_MODE(file)
-#endif
-
-CHUNK is simply the buffer size for feeding data to and pulling data -from the zlib routines. Larger buffer sizes would be more efficient, -especially for inflate(). If the memory is available, buffers sizes -on the order of 128K or 256K bytes should be used. -

-#define CHUNK 16384
-
-The def() routine compresses data from an input file to an output file. The output data -will be in the zlib format, which is different from the gzip or zip -formats. The zlib format has a very small header of only two bytes to identify it as -a zlib stream and to provide decoding information, and a four-byte trailer with a fast -check value to verify the integrity of the uncompressed data after decoding. -

-/* Compress from file source to file dest until EOF on source.
-   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
-   allocated for processing, Z_STREAM_ERROR if an invalid compression
-   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
-   version of the library linked do not match, or Z_ERRNO if there is
-   an error reading or writing the files. */
-int def(FILE *source, FILE *dest, int level)
-{
-
-Here are the local variables for def(). ret will be used for zlib -return codes. flush will keep track of the current flushing state for deflate(), -which is either no flushing, or flush to completion after the end of the input file is reached. -have is the amount of data returned from deflate(). The strm structure -is used to pass information to and from the zlib routines, and to maintain the -deflate() state. in and out are the input and output buffers for -deflate(). -

-    int ret, flush;
-    unsigned have;
-    z_stream strm;
-    unsigned char in[CHUNK];
-    unsigned char out[CHUNK];
-
-The first thing we do is to initialize the zlib state for compression using -deflateInit(). This must be done before the first use of deflate(). -The zalloc, zfree, and opaque fields in the strm -structure must be initialized before calling deflateInit(). Here they are -set to the zlib constant Z_NULL to request that zlib use -the default memory allocation routines. An application may also choose to provide -custom memory allocation routines here. deflateInit() will allocate on the -order of 256K bytes for the internal state. -(See zlib Technical Details.) -

-deflateInit() is called with a pointer to the structure to be initialized and -the compression level, which is an integer in the range of -1 to 9. Lower compression -levels result in faster execution, but less compression. Higher levels result in -greater compression, but slower execution. The zlib constant Z_DEFAULT_COMPRESSION, -equal to -1, -provides a good compromise between compression and speed and is equivalent to level 6. -Level 0 actually does no compression at all, and in fact expands the data slightly to produce -the zlib format (it is not a byte-for-byte copy of the input). -More advanced applications of zlib -may use deflateInit2() here instead. Such an application may want to reduce how -much memory will be used, at some price in compression. Or it may need to request a -gzip header and trailer instead of a zlib header and trailer, or raw -encoding with no header or trailer at all. -

-We must check the return value of deflateInit() against the zlib constant -Z_OK to make sure that it was able to -allocate memory for the internal state, and that the provided arguments were valid. -deflateInit() will also check that the version of zlib that the zlib.h -file came from matches the version of zlib actually linked with the program. This -is especially important for environments in which zlib is a shared library. -

-Note that an application can initialize multiple, independent zlib streams, which can -operate in parallel. The state information maintained in the structure allows the zlib -routines to be reentrant. -


-    /* allocate deflate state */
-    strm.zalloc = Z_NULL;
-    strm.zfree = Z_NULL;
-    strm.opaque = Z_NULL;
-    ret = deflateInit(&strm, level);
-    if (ret != Z_OK)
-        return ret;
-
-With the pleasantries out of the way, now we can get down to business. The outer do-loop -reads all of the input file and exits at the bottom of the loop once end-of-file is reached. -This loop contains the only call of deflate(). So we must make sure that all of the -input data has been processed and that all of the output data has been generated and consumed -before we fall out of the loop at the bottom. -

-    /* compress until end of file */
-    do {
-
-We start off by reading data from the input file. The number of bytes read is put directly -into avail_in, and a pointer to those bytes is put into next_in. We also -check to see if end-of-file on the input has been reached. If we are at the end of file, then flush is set to the -zlib constant Z_FINISH, which is later passed to deflate() to -indicate that this is the last chunk of input data to compress. We need to use feof() -to check for end-of-file as opposed to seeing if fewer than CHUNK bytes have been read. The -reason is that if the input file length is an exact multiple of CHUNK, we will miss -the fact that we got to the end-of-file, and not know to tell deflate() to finish -up the compressed stream. If we are not yet at the end of the input, then the zlib -constant Z_NO_FLUSH will be passed to deflate to indicate that we are still -in the middle of the uncompressed data. -

-If there is an error in reading from the input file, the process is aborted with -deflateEnd() being called to free the allocated zlib state before returning -the error. We wouldn't want a memory leak, now would we? deflateEnd() can be called -at any time after the state has been initialized. Once that's done, deflateInit() (or -deflateInit2()) would have to be called to start a new compression process. There is -no point here in checking the deflateEnd() return code. The deallocation can't fail. -


-        strm.avail_in = fread(in, 1, CHUNK, source);
-        if (ferror(source)) {
-            (void)deflateEnd(&strm);
-            return Z_ERRNO;
-        }
-        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
-        strm.next_in = in;
-
-The inner do-loop passes our chunk of input data to deflate(), and then -keeps calling deflate() until it is done producing output. Once there is no more -new output, deflate() is guaranteed to have consumed all of the input, i.e., -avail_in will be zero. -

-        /* run deflate() on input until output buffer not full, finish
-           compression if all of source has been read in */
-        do {
-
-Output space is provided to deflate() by setting avail_out to the number -of available output bytes and next_out to a pointer to that space. -

-            strm.avail_out = CHUNK;
-            strm.next_out = out;
-
-Now we call the compression engine itself, deflate(). It takes as many of the -avail_in bytes at next_in as it can process, and writes as many as -avail_out bytes to next_out. Those counters and pointers are then -updated past the input data consumed and the output data written. It is the amount of -output space available that may limit how much input is consumed. -Hence the inner loop to make sure that -all of the input is consumed by providing more output space each time. Since avail_in -and next_in are updated by deflate(), we don't have to mess with those -between deflate() calls until it's all used up. -

-The parameters to deflate() are a pointer to the strm structure containing -the input and output information and the internal compression engine state, and a parameter -indicating whether and how to flush data to the output. Normally deflate will consume -several K bytes of input data before producing any output (except for the header), in order -to accumulate statistics on the data for optimum compression. It will then put out a burst of -compressed data, and proceed to consume more input before the next burst. Eventually, -deflate() -must be told to terminate the stream, complete the compression with provided input data, and -write out the trailer check value. deflate() will continue to compress normally as long -as the flush parameter is Z_NO_FLUSH. Once the Z_FINISH parameter is provided, -deflate() will begin to complete the compressed output stream. However depending on how -much output space is provided, deflate() may have to be called several times until it -has provided the complete compressed stream, even after it has consumed all of the input. The flush -parameter must continue to be Z_FINISH for those subsequent calls. -

-There are other values of the flush parameter that are used in more advanced applications. You can -force deflate() to produce a burst of output that encodes all of the input data provided -so far, even if it wouldn't have otherwise, for example to control data latency on a link with -compressed data. You can also ask that deflate() do that as well as erase any history up to -that point so that what follows can be decompressed independently, for example for random access -applications. Both requests will degrade compression by an amount depending on how often such -requests are made. -

-deflate() has a return value that can indicate errors, yet we do not check it here. Why -not? Well, it turns out that deflate() can do no wrong here. Let's go through -deflate()'s return values and dispense with them one by one. The possible values are -Z_OK, Z_STREAM_END, Z_STREAM_ERROR, or Z_BUF_ERROR. Z_OK -is, well, ok. Z_STREAM_END is also ok and will be returned for the last call of -deflate(). This is already guaranteed by calling deflate() with Z_FINISH -until it has no more output. Z_STREAM_ERROR is only possible if the stream is not -initialized properly, but we did initialize it properly. There is no harm in checking for -Z_STREAM_ERROR here, for example to check for the possibility that some -other part of the application inadvertently clobbered the memory containing the zlib state. -Z_BUF_ERROR will be explained further below, but -suffice it to say that this is simply an indication that deflate() could not consume -more input or produce more output. deflate() can be called again with more output space -or more available input, which it will be in this code. -


-            ret = deflate(&strm, flush);    /* no bad return value */
-            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
-
-Now we compute how much output deflate() provided on the last call, which is the -difference between how much space was provided before the call, and how much output space -is still available after the call. Then that data, if any, is written to the output file. -We can then reuse the output buffer for the next call of deflate(). Again if there -is a file i/o error, we call deflateEnd() before returning to avoid a memory leak. -

-            have = CHUNK - strm.avail_out;
-            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
-                (void)deflateEnd(&strm);
-                return Z_ERRNO;
-            }
-
-The inner do-loop is repeated until the last deflate() call fails to fill the -provided output buffer. Then we know that deflate() has done as much as it can with -the provided input, and that all of that input has been consumed. We can then fall out of this -loop and reuse the input buffer. -

-The way we tell that deflate() has no more output is by seeing that it did not fill -the output buffer, leaving avail_out greater than zero. However suppose that -deflate() has no more output, but just so happened to exactly fill the output buffer! -avail_out is zero, and we can't tell that deflate() has done all it can. -As far as we know, deflate() -has more output for us. So we call it again. But now deflate() produces no output -at all, and avail_out remains unchanged as CHUNK. That deflate() call -wasn't able to do anything, either consume input or produce output, and so it returns -Z_BUF_ERROR. (See, I told you I'd cover this later.) However this is not a problem at -all. Now we finally have the desired indication that deflate() is really done, -and so we drop out of the inner loop to provide more input to deflate(). -

-With flush set to Z_FINISH, this final set of deflate() calls will -complete the output stream. Once that is done, subsequent calls of deflate() would return -Z_STREAM_ERROR if the flush parameter is not Z_FINISH, and do no more processing -until the state is reinitialized. -

-Some applications of zlib have two loops that call deflate() -instead of the single inner loop we have here. The first loop would call -without flushing and feed all of the data to deflate(). The second loop would call -deflate() with no more -data and the Z_FINISH parameter to complete the process. As you can see from this -example, that can be avoided by simply keeping track of the current flush state. -


-        } while (strm.avail_out == 0);
-        assert(strm.avail_in == 0);     /* all input will be used */
-
-Now we check to see if we have already processed all of the input file. That information was -saved in the flush variable, so we see if that was set to Z_FINISH. If so, -then we're done and we fall out of the outer loop. We're guaranteed to get Z_STREAM_END -from the last deflate() call, since we ran it until the last chunk of input was -consumed and all of the output was generated. -

-        /* done when last data in file processed */
-    } while (flush != Z_FINISH);
-    assert(ret == Z_STREAM_END);        /* stream will be complete */
-
-The process is complete, but we still need to deallocate the state to avoid a memory leak -(or rather more like a memory hemorrhage if you didn't do this). Then -finally we can return with a happy return value. -

-    /* clean up and return */
-    (void)deflateEnd(&strm);
-    return Z_OK;
-}
-
-Now we do the same thing for decompression in the inf() routine. inf() -decompresses what is hopefully a valid zlib stream from the input file and writes the -uncompressed data to the output file. Much of the discussion above for def() -applies to inf() as well, so the discussion here will focus on the differences between -the two. -

-/* Decompress from file source to file dest until stream ends or EOF.
-   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
-   allocated for processing, Z_DATA_ERROR if the deflate data is
-   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
-   the version of the library linked do not match, or Z_ERRNO if there
-   is an error reading or writing the files. */
-int inf(FILE *source, FILE *dest)
-{
-
-The local variables have the same functionality as they do for def(). The -only difference is that there is no flush variable, since inflate() -can tell from the zlib stream itself when the stream is complete. -

-    int ret;
-    unsigned have;
-    z_stream strm;
-    unsigned char in[CHUNK];
-    unsigned char out[CHUNK];
-
-The initialization of the state is the same, except that there is no compression level, -of course, and two more elements of the structure are initialized. avail_in -and next_in must be initialized before calling inflateInit(). This -is because the application has the option to provide the start of the zlib stream in -order for inflateInit() to have access to information about the compression -method to aid in memory allocation. In the current implementation of zlib -(up through versions 1.2.x), the method-dependent memory allocations are deferred to the first call of -inflate() anyway. However those fields must be initialized since later versions -of zlib that provide more compression methods may take advantage of this interface. -In any case, no decompression is performed by inflateInit(), so the -avail_out and next_out fields do not need to be initialized before calling. -

-Here avail_in is set to zero and next_in is set to Z_NULL to -indicate that no input data is being provided. -


-    /* allocate inflate state */
-    strm.zalloc = Z_NULL;
-    strm.zfree = Z_NULL;
-    strm.opaque = Z_NULL;
-    strm.avail_in = 0;
-    strm.next_in = Z_NULL;
-    ret = inflateInit(&strm);
-    if (ret != Z_OK)
-        return ret;
-
-The outer do-loop decompresses input until inflate() indicates -that it has reached the end of the compressed data and has produced all of the uncompressed -output. This is in contrast to def() which processes all of the input file. -If end-of-file is reached before the compressed data self-terminates, then the compressed -data is incomplete and an error is returned. -

-    /* decompress until deflate stream ends or end of file */
-    do {
-
-We read input data and set the strm structure accordingly. If we've reached the -end of the input file, then we leave the outer loop and report an error, since the -compressed data is incomplete. Note that we may read more data than is eventually consumed -by inflate(), if the input file continues past the zlib stream. -For applications where zlib streams are embedded in other data, this routine would -need to be modified to return the unused data, or at least indicate how much of the input -data was not used, so the application would know where to pick up after the zlib stream. -

-        strm.avail_in = fread(in, 1, CHUNK, source);
-        if (ferror(source)) {
-            (void)inflateEnd(&strm);
-            return Z_ERRNO;
-        }
-        if (strm.avail_in == 0)
-            break;
-        strm.next_in = in;
-
-The inner do-loop has the same function it did in def(), which is to -keep calling inflate() until has generated all of the output it can with the -provided input. -

-        /* run inflate() on input until output buffer not full */
-        do {
-
-Just like in def(), the same output space is provided for each call of inflate(). -

-            strm.avail_out = CHUNK;
-            strm.next_out = out;
-
-Now we run the decompression engine itself. There is no need to adjust the flush parameter, since -the zlib format is self-terminating. The main difference here is that there are -return values that we need to pay attention to. Z_DATA_ERROR -indicates that inflate() detected an error in the zlib compressed data format, -which means that either the data is not a zlib stream to begin with, or that the data was -corrupted somewhere along the way since it was compressed. The other error to be processed is -Z_MEM_ERROR, which can occur since memory allocation is deferred until inflate() -needs it, unlike deflate(), whose memory is allocated at the start by deflateInit(). -

-Advanced applications may use -deflateSetDictionary() to prime deflate() with a set of likely data to improve the -first 32K or so of compression. This is noted in the zlib header, so inflate() -requests that that dictionary be provided before it can start to decompress. Without the dictionary, -correct decompression is not possible. For this routine, we have no idea what the dictionary is, -so the Z_NEED_DICT indication is converted to a Z_DATA_ERROR. -

-inflate() can also return Z_STREAM_ERROR, which should not be possible here, -but could be checked for as noted above for def(). Z_BUF_ERROR does not need to be -checked for here, for the same reasons noted for def(). Z_STREAM_END will be -checked for later. -


-            ret = inflate(&strm, Z_NO_FLUSH);
-            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
-            switch (ret) {
-            case Z_NEED_DICT:
-                ret = Z_DATA_ERROR;     /* and fall through */
-            case Z_DATA_ERROR:
-            case Z_MEM_ERROR:
-                (void)inflateEnd(&strm);
-                return ret;
-            }
-
-The output of inflate() is handled identically to that of deflate(). -

-            have = CHUNK - strm.avail_out;
-            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
-                (void)inflateEnd(&strm);
-                return Z_ERRNO;
-            }
-
-The inner do-loop ends when inflate() has no more output as indicated -by not filling the output buffer, just as for deflate(). In this case, we cannot -assert that strm.avail_in will be zero, since the deflate stream may end before the file -does. -

-        } while (strm.avail_out == 0);
-
-The outer do-loop ends when inflate() reports that it has reached the -end of the input zlib stream, has completed the decompression and integrity -check, and has provided all of the output. This is indicated by the inflate() -return value Z_STREAM_END. The inner loop is guaranteed to leave ret -equal to Z_STREAM_END if the last chunk of the input file read contained the end -of the zlib stream. So if the return value is not Z_STREAM_END, the -loop continues to read more input. -

-        /* done when inflate() says it's done */
-    } while (ret != Z_STREAM_END);
-
-At this point, decompression successfully completed, or we broke out of the loop due to no -more data being available from the input file. If the last inflate() return value -is not Z_STREAM_END, then the zlib stream was incomplete and a data error -is returned. Otherwise, we return with a happy return value. Of course, inflateEnd() -is called first to avoid a memory leak. -

-    /* clean up and return */
-    (void)inflateEnd(&strm);
-    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
-}
-
-That ends the routines that directly use zlib. The following routines make this -a command-line program by running data through the above routines from stdin to -stdout, and handling any errors reported by def() or inf(). -

-zerr() is used to interpret the possible error codes from def() -and inf(), as detailed in their comments above, and print out an error message. -Note that these are only a subset of the possible return values from deflate() -and inflate(). -


-/* report a zlib or i/o error */
-void zerr(int ret)
-{
-    fputs("zpipe: ", stderr);
-    switch (ret) {
-    case Z_ERRNO:
-        if (ferror(stdin))
-            fputs("error reading stdin\n", stderr);
-        if (ferror(stdout))
-            fputs("error writing stdout\n", stderr);
-        break;
-    case Z_STREAM_ERROR:
-        fputs("invalid compression level\n", stderr);
-        break;
-    case Z_DATA_ERROR:
-        fputs("invalid or incomplete deflate data\n", stderr);
-        break;
-    case Z_MEM_ERROR:
-        fputs("out of memory\n", stderr);
-        break;
-    case Z_VERSION_ERROR:
-        fputs("zlib version mismatch!\n", stderr);
-    }
-}
-
-Here is the main() routine used to test def() and inf(). The -zpipe command is simply a compression pipe from stdin to stdout, if -no arguments are given, or it is a decompression pipe if zpipe -d is used. If any other -arguments are provided, no compression or decompression is performed. Instead a usage -message is displayed. Examples are zpipe < foo.txt > foo.txt.z to compress, and -zpipe -d < foo.txt.z > foo.txt to decompress. -

-/* compress or decompress from stdin to stdout */
-int main(int argc, char **argv)
-{
-    int ret;
-
-    /* avoid end-of-line conversions */
-    SET_BINARY_MODE(stdin);
-    SET_BINARY_MODE(stdout);
-
-    /* do compression if no arguments */
-    if (argc == 1) {
-        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
-        if (ret != Z_OK)
-            zerr(ret);
-        return ret;
-    }
-
-    /* do decompression if -d specified */
-    else if (argc == 2 && strcmp(argv[1], "-d") == 0) {
-        ret = inf(stdin, stdout);
-        if (ret != Z_OK)
-            zerr(ret);
-        return ret;
-    }
-
-    /* otherwise, report usage */
-    else {
-        fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr);
-        return 1;
-    }
-}
-
-
-Copyright (c) 2004, 2005 by Mark Adler
Last modified 11 December 2005
- - diff --git a/deps/zlib/examples/zpipe.c b/deps/zlib/examples/zpipe.c deleted file mode 100644 index 83535d1693580f..00000000000000 --- a/deps/zlib/examples/zpipe.c +++ /dev/null @@ -1,205 +0,0 @@ -/* zpipe.c: example of proper use of zlib's inflate() and deflate() - Not copyrighted -- provided to the public domain - Version 1.4 11 December 2005 Mark Adler */ - -/* Version history: - 1.0 30 Oct 2004 First version - 1.1 8 Nov 2004 Add void casting for unused return values - Use switch statement for inflate() return values - 1.2 9 Nov 2004 Add assertions to document zlib guarantees - 1.3 6 Apr 2005 Remove incorrect assertion in inf() - 1.4 11 Dec 2005 Add hack to avoid MSDOS end-of-line conversions - Avoid some compiler warnings for input and output buffers - */ - -#include -#include -#include -#include "zlib.h" - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#define CHUNK 16384 - -/* Compress from file source to file dest until EOF on source. - def() returns Z_OK on success, Z_MEM_ERROR if memory could not be - allocated for processing, Z_STREAM_ERROR if an invalid compression - level is supplied, Z_VERSION_ERROR if the version of zlib.h and the - version of the library linked do not match, or Z_ERRNO if there is - an error reading or writing the files. */ -int def(FILE *source, FILE *dest, int level) -{ - int ret, flush; - unsigned have; - z_stream strm; - unsigned char in[CHUNK]; - unsigned char out[CHUNK]; - - /* allocate deflate state */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - ret = deflateInit(&strm, level); - if (ret != Z_OK) - return ret; - - /* compress until end of file */ - do { - strm.avail_in = fread(in, 1, CHUNK, source); - if (ferror(source)) { - (void)deflateEnd(&strm); - return Z_ERRNO; - } - flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; - strm.next_in = in; - - /* run deflate() on input until output buffer not full, finish - compression if all of source has been read in */ - do { - strm.avail_out = CHUNK; - strm.next_out = out; - ret = deflate(&strm, flush); /* no bad return value */ - assert(ret != Z_STREAM_ERROR); /* state not clobbered */ - have = CHUNK - strm.avail_out; - if (fwrite(out, 1, have, dest) != have || ferror(dest)) { - (void)deflateEnd(&strm); - return Z_ERRNO; - } - } while (strm.avail_out == 0); - assert(strm.avail_in == 0); /* all input will be used */ - - /* done when last data in file processed */ - } while (flush != Z_FINISH); - assert(ret == Z_STREAM_END); /* stream will be complete */ - - /* clean up and return */ - (void)deflateEnd(&strm); - return Z_OK; -} - -/* Decompress from file source to file dest until stream ends or EOF. - inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be - allocated for processing, Z_DATA_ERROR if the deflate data is - invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and - the version of the library linked do not match, or Z_ERRNO if there - is an error reading or writing the files. */ -int inf(FILE *source, FILE *dest) -{ - int ret; - unsigned have; - z_stream strm; - unsigned char in[CHUNK]; - unsigned char out[CHUNK]; - - /* allocate inflate state */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); - if (ret != Z_OK) - return ret; - - /* decompress until deflate stream ends or end of file */ - do { - strm.avail_in = fread(in, 1, CHUNK, source); - if (ferror(source)) { - (void)inflateEnd(&strm); - return Z_ERRNO; - } - if (strm.avail_in == 0) - break; - strm.next_in = in; - - /* run inflate() on input until output buffer not full */ - do { - strm.avail_out = CHUNK; - strm.next_out = out; - ret = inflate(&strm, Z_NO_FLUSH); - assert(ret != Z_STREAM_ERROR); /* state not clobbered */ - switch (ret) { - case Z_NEED_DICT: - ret = Z_DATA_ERROR; /* and fall through */ - case Z_DATA_ERROR: - case Z_MEM_ERROR: - (void)inflateEnd(&strm); - return ret; - } - have = CHUNK - strm.avail_out; - if (fwrite(out, 1, have, dest) != have || ferror(dest)) { - (void)inflateEnd(&strm); - return Z_ERRNO; - } - } while (strm.avail_out == 0); - - /* done when inflate() says it's done */ - } while (ret != Z_STREAM_END); - - /* clean up and return */ - (void)inflateEnd(&strm); - return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; -} - -/* report a zlib or i/o error */ -void zerr(int ret) -{ - fputs("zpipe: ", stderr); - switch (ret) { - case Z_ERRNO: - if (ferror(stdin)) - fputs("error reading stdin\n", stderr); - if (ferror(stdout)) - fputs("error writing stdout\n", stderr); - break; - case Z_STREAM_ERROR: - fputs("invalid compression level\n", stderr); - break; - case Z_DATA_ERROR: - fputs("invalid or incomplete deflate data\n", stderr); - break; - case Z_MEM_ERROR: - fputs("out of memory\n", stderr); - break; - case Z_VERSION_ERROR: - fputs("zlib version mismatch!\n", stderr); - } -} - -/* compress or decompress from stdin to stdout */ -int main(int argc, char **argv) -{ - int ret; - - /* avoid end-of-line conversions */ - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - - /* do compression if no arguments */ - if (argc == 1) { - ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK) - zerr(ret); - return ret; - } - - /* do decompression if -d specified */ - else if (argc == 2 && strcmp(argv[1], "-d") == 0) { - ret = inf(stdin, stdout); - if (ret != Z_OK) - zerr(ret); - return ret; - } - - /* otherwise, report usage */ - else { - fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr); - return 1; - } -} diff --git a/deps/zlib/examples/zran.c b/deps/zlib/examples/zran.c deleted file mode 100644 index 4fec6594a6648e..00000000000000 --- a/deps/zlib/examples/zran.c +++ /dev/null @@ -1,409 +0,0 @@ -/* zran.c -- example of zlib/gzip stream indexing and random access - * Copyright (C) 2005, 2012 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - Version 1.1 29 Sep 2012 Mark Adler */ - -/* Version History: - 1.0 29 May 2005 First version - 1.1 29 Sep 2012 Fix memory reallocation error - */ - -/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary() - for random access of a compressed file. A file containing a zlib or gzip - stream is provided on the command line. The compressed stream is decoded in - its entirety, and an index built with access points about every SPAN bytes - in the uncompressed output. The compressed file is left open, and can then - be read randomly, having to decompress on the average SPAN/2 uncompressed - bytes before getting to the desired block of data. - - An access point can be created at the start of any deflate block, by saving - the starting file offset and bit of that block, and the 32K bytes of - uncompressed data that precede that block. Also the uncompressed offset of - that block is saved to provide a referece for locating a desired starting - point in the uncompressed stream. build_index() works by decompressing the - input zlib or gzip stream a block at a time, and at the end of each block - deciding if enough uncompressed data has gone by to justify the creation of - a new access point. If so, that point is saved in a data structure that - grows as needed to accommodate the points. - - To use the index, an offset in the uncompressed data is provided, for which - the latest access point at or preceding that offset is located in the index. - The input file is positioned to the specified location in the index, and if - necessary the first few bits of the compressed data is read from the file. - inflate is initialized with those bits and the 32K of uncompressed data, and - the decompression then proceeds until the desired offset in the file is - reached. Then the decompression continues to read the desired uncompressed - data from the file. - - Another approach would be to generate the index on demand. In that case, - requests for random access reads from the compressed data would try to use - the index, but if a read far enough past the end of the index is required, - then further index entries would be generated and added. - - There is some fair bit of overhead to starting inflation for the random - access, mainly copying the 32K byte dictionary. So if small pieces of the - file are being accessed, it would make sense to implement a cache to hold - some lookahead and avoid many calls to extract() for small lengths. - - Another way to build an index would be to use inflateCopy(). That would - not be constrained to have access points at block boundaries, but requires - more memory per access point, and also cannot be saved to file due to the - use of pointers in the state. The approach here allows for storage of the - index in a file. - */ - -#include -#include -#include -#include "zlib.h" - -#define local static - -#define SPAN 1048576L /* desired distance between access points */ -#define WINSIZE 32768U /* sliding window size */ -#define CHUNK 16384 /* file input buffer size */ - -/* access point entry */ -struct point { - off_t out; /* corresponding offset in uncompressed data */ - off_t in; /* offset in input file of first full byte */ - int bits; /* number of bits (1-7) from byte at in - 1, or 0 */ - unsigned char window[WINSIZE]; /* preceding 32K of uncompressed data */ -}; - -/* access point list */ -struct access { - int have; /* number of list entries filled in */ - int size; /* number of list entries allocated */ - struct point *list; /* allocated list */ -}; - -/* Deallocate an index built by build_index() */ -local void free_index(struct access *index) -{ - if (index != NULL) { - free(index->list); - free(index); - } -} - -/* Add an entry to the access point list. If out of memory, deallocate the - existing list and return NULL. */ -local struct access *addpoint(struct access *index, int bits, - off_t in, off_t out, unsigned left, unsigned char *window) -{ - struct point *next; - - /* if list is empty, create it (start with eight points) */ - if (index == NULL) { - index = malloc(sizeof(struct access)); - if (index == NULL) return NULL; - index->list = malloc(sizeof(struct point) << 3); - if (index->list == NULL) { - free(index); - return NULL; - } - index->size = 8; - index->have = 0; - } - - /* if list is full, make it bigger */ - else if (index->have == index->size) { - index->size <<= 1; - next = realloc(index->list, sizeof(struct point) * index->size); - if (next == NULL) { - free_index(index); - return NULL; - } - index->list = next; - } - - /* fill in entry and increment how many we have */ - next = index->list + index->have; - next->bits = bits; - next->in = in; - next->out = out; - if (left) - memcpy(next->window, window + WINSIZE - left, left); - if (left < WINSIZE) - memcpy(next->window + left, window, WINSIZE - left); - index->have++; - - /* return list, possibly reallocated */ - return index; -} - -/* Make one entire pass through the compressed stream and build an index, with - access points about every span bytes of uncompressed output -- span is - chosen to balance the speed of random access against the memory requirements - of the list, about 32K bytes per access point. Note that data after the end - of the first zlib or gzip stream in the file is ignored. build_index() - returns the number of access points on success (>= 1), Z_MEM_ERROR for out - of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a - file read error. On success, *built points to the resulting index. */ -local int build_index(FILE *in, off_t span, struct access **built) -{ - int ret; - off_t totin, totout; /* our own total counters to avoid 4GB limit */ - off_t last; /* totout value of last access point */ - struct access *index; /* access points being generated */ - z_stream strm; - unsigned char input[CHUNK]; - unsigned char window[WINSIZE]; - - /* initialize inflate */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */ - if (ret != Z_OK) - return ret; - - /* inflate the input, maintain a sliding window, and build an index -- this - also validates the integrity of the compressed data using the check - information at the end of the gzip or zlib stream */ - totin = totout = last = 0; - index = NULL; /* will be allocated by first addpoint() */ - strm.avail_out = 0; - do { - /* get some compressed data from input file */ - strm.avail_in = fread(input, 1, CHUNK, in); - if (ferror(in)) { - ret = Z_ERRNO; - goto build_index_error; - } - if (strm.avail_in == 0) { - ret = Z_DATA_ERROR; - goto build_index_error; - } - strm.next_in = input; - - /* process all of that, or until end of stream */ - do { - /* reset sliding window if necessary */ - if (strm.avail_out == 0) { - strm.avail_out = WINSIZE; - strm.next_out = window; - } - - /* inflate until out of input, output, or at end of block -- - update the total input and output counters */ - totin += strm.avail_in; - totout += strm.avail_out; - ret = inflate(&strm, Z_BLOCK); /* return at end of block */ - totin -= strm.avail_in; - totout -= strm.avail_out; - if (ret == Z_NEED_DICT) - ret = Z_DATA_ERROR; - if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) - goto build_index_error; - if (ret == Z_STREAM_END) - break; - - /* if at end of block, consider adding an index entry (note that if - data_type indicates an end-of-block, then all of the - uncompressed data from that block has been delivered, and none - of the compressed data after that block has been consumed, - except for up to seven bits) -- the totout == 0 provides an - entry point after the zlib or gzip header, and assures that the - index always has at least one access point; we avoid creating an - access point after the last block by checking bit 6 of data_type - */ - if ((strm.data_type & 128) && !(strm.data_type & 64) && - (totout == 0 || totout - last > span)) { - index = addpoint(index, strm.data_type & 7, totin, - totout, strm.avail_out, window); - if (index == NULL) { - ret = Z_MEM_ERROR; - goto build_index_error; - } - last = totout; - } - } while (strm.avail_in != 0); - } while (ret != Z_STREAM_END); - - /* clean up and return index (release unused entries in list) */ - (void)inflateEnd(&strm); - index->list = realloc(index->list, sizeof(struct point) * index->have); - index->size = index->have; - *built = index; - return index->size; - - /* return error */ - build_index_error: - (void)inflateEnd(&strm); - if (index != NULL) - free_index(index); - return ret; -} - -/* Use the index to read len bytes from offset into buf, return bytes read or - negative for error (Z_DATA_ERROR or Z_MEM_ERROR). If data is requested past - the end of the uncompressed data, then extract() will return a value less - than len, indicating how much as actually read into buf. This function - should not return a data error unless the file was modified since the index - was generated. extract() may also return Z_ERRNO if there is an error on - reading or seeking the input file. */ -local int extract(FILE *in, struct access *index, off_t offset, - unsigned char *buf, int len) -{ - int ret, skip; - z_stream strm; - struct point *here; - unsigned char input[CHUNK]; - unsigned char discard[WINSIZE]; - - /* proceed only if something reasonable to do */ - if (len < 0) - return 0; - - /* find where in stream to start */ - here = index->list; - ret = index->have; - while (--ret && here[1].out <= offset) - here++; - - /* initialize file and inflate state to start there */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -15); /* raw inflate */ - if (ret != Z_OK) - return ret; - ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET); - if (ret == -1) - goto extract_ret; - if (here->bits) { - ret = getc(in); - if (ret == -1) { - ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR; - goto extract_ret; - } - (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits)); - } - (void)inflateSetDictionary(&strm, here->window, WINSIZE); - - /* skip uncompressed bytes until offset reached, then satisfy request */ - offset -= here->out; - strm.avail_in = 0; - skip = 1; /* while skipping to offset */ - do { - /* define where to put uncompressed data, and how much */ - if (offset == 0 && skip) { /* at offset now */ - strm.avail_out = len; - strm.next_out = buf; - skip = 0; /* only do this once */ - } - if (offset > WINSIZE) { /* skip WINSIZE bytes */ - strm.avail_out = WINSIZE; - strm.next_out = discard; - offset -= WINSIZE; - } - else if (offset != 0) { /* last skip */ - strm.avail_out = (unsigned)offset; - strm.next_out = discard; - offset = 0; - } - - /* uncompress until avail_out filled, or end of stream */ - do { - if (strm.avail_in == 0) { - strm.avail_in = fread(input, 1, CHUNK, in); - if (ferror(in)) { - ret = Z_ERRNO; - goto extract_ret; - } - if (strm.avail_in == 0) { - ret = Z_DATA_ERROR; - goto extract_ret; - } - strm.next_in = input; - } - ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */ - if (ret == Z_NEED_DICT) - ret = Z_DATA_ERROR; - if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) - goto extract_ret; - if (ret == Z_STREAM_END) - break; - } while (strm.avail_out != 0); - - /* if reach end of stream, then don't keep trying to get more */ - if (ret == Z_STREAM_END) - break; - - /* do until offset reached and requested data read, or stream ends */ - } while (skip); - - /* compute number of uncompressed bytes read after offset */ - ret = skip ? 0 : len - strm.avail_out; - - /* clean up and return bytes read or error */ - extract_ret: - (void)inflateEnd(&strm); - return ret; -} - -/* Demonstrate the use of build_index() and extract() by processing the file - provided on the command line, and the extracting 16K from about 2/3rds of - the way through the uncompressed output, and writing that to stdout. */ -int main(int argc, char **argv) -{ - int len; - off_t offset; - FILE *in; - struct access *index = NULL; - unsigned char buf[CHUNK]; - - /* open input file */ - if (argc != 2) { - fprintf(stderr, "usage: zran file.gz\n"); - return 1; - } - in = fopen(argv[1], "rb"); - if (in == NULL) { - fprintf(stderr, "zran: could not open %s for reading\n", argv[1]); - return 1; - } - - /* build index */ - len = build_index(in, SPAN, &index); - if (len < 0) { - fclose(in); - switch (len) { - case Z_MEM_ERROR: - fprintf(stderr, "zran: out of memory\n"); - break; - case Z_DATA_ERROR: - fprintf(stderr, "zran: compressed data error in %s\n", argv[1]); - break; - case Z_ERRNO: - fprintf(stderr, "zran: read error on %s\n", argv[1]); - break; - default: - fprintf(stderr, "zran: error %d while building index\n", len); - } - return 1; - } - fprintf(stderr, "zran: built index with %d access points\n", len); - - /* use index by reading some bytes from an arbitrary offset */ - offset = (index->list[index->have - 1].out << 1) / 3; - len = extract(in, index, offset, buf, CHUNK); - if (len < 0) - fprintf(stderr, "zran: extraction failed: %s error\n", - len == Z_MEM_ERROR ? "out of memory" : "input corrupted"); - else { - fwrite(buf, 1, len, stdout); - fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset); - } - - /* clean up and exit */ - free_index(index); - fclose(in); - return 0; -} diff --git a/deps/zlib/fill_window_sse.c b/deps/zlib/fill_window_sse.c new file mode 100644 index 00000000000000..ed1e5d1d6735b1 --- /dev/null +++ b/deps/zlib/fill_window_sse.c @@ -0,0 +1,177 @@ +/* + * Fill Window with SSE2-optimized hash shifting + * + * Copyright (C) 2013 Intel Corporation + * Authors: + * Arjan van de Ven + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include +#include "deflate.h" + +#define UPDATE_HASH(s,h,i) \ + {\ + if (s->level < 6) { \ + h = (3483 * (s->window[i]) +\ + 23081* (s->window[i+1]) +\ + 6954 * (s->window[i+2]) +\ + 20947* (s->window[i+3])) & s->hash_mask;\ + } else {\ + h = (25881* (s->window[i]) +\ + 24674* (s->window[i+1]) +\ + 25811* (s->window[i+2])) & s->hash_mask;\ + }\ + }\ + +extern int deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); + +void fill_window_sse(deflate_state *s) +{ + const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); + + register unsigned n; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + p -= 8; + do { + __m128i value, result; + + value = _mm_loadu_si128((__m128i *)p); + result = _mm_subs_epu16(value, xmm_wsize); + _mm_storeu_si128((__m128i *)p, result); + + p -= 8; + n -= 8; + } while (n > 0); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + p -= 8; + do { + __m128i value, result; + + value = _mm_loadu_si128((__m128i *)p); + result = _mm_subs_epu16(value, xmm_wsize); + _mm_storeu_si128((__m128i *)p, result); + + p -= 8; + n -= 8; + } while (n > 0); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = deflate_read_buf(s->strm, + s->window + s->strstart + s->lookahead, + more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + uInt str = s->strstart; + s->ins_h = s->window[str]; + if (str >= 1) + UPDATE_HASH(s, s->ins_h, str + 1 - (MIN_MATCH-1)); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} diff --git a/deps/zlib/google/BUILD.gn b/deps/zlib/google/BUILD.gn new file mode 100644 index 00000000000000..4024836205f64c --- /dev/null +++ b/deps/zlib/google/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build_overrides/build.gni") + +if (build_with_chromium) { + static_library("zip") { + sources = [ + "zip.cc", + "zip.h", + "zip_internal.cc", + "zip_internal.h", + "zip_reader.cc", + "zip_reader.h", + "zip_writer.cc", + "zip_writer.h", + ] + deps = [ + "//base", + "//third_party/zlib:minizip", + ] + } + + static_library("compression_utils") { + sources = [ + "compression_utils.cc", + "compression_utils.h", + ] + deps = [ + ":compression_utils_portable", + "//base", + "//third_party/zlib", + ] + } +} + +# This allows other users of Chromium's zlib library, but don't use Chromium's +# //base, to reuse some boilerplate code. +static_library("compression_utils_portable") { + sources = [ + "compression_utils_portable.cc", + "compression_utils_portable.h", + ] + deps = [ + "//third_party/zlib", + ] +} diff --git a/deps/zlib/google/DEPS b/deps/zlib/google/DEPS new file mode 100644 index 00000000000000..144fbd149295b3 --- /dev/null +++ b/deps/zlib/google/DEPS @@ -0,0 +1,5 @@ +include_rules = [ + '+base', + '+build', + '+testing', +] diff --git a/deps/zlib/google/OWNERS b/deps/zlib/google/OWNERS new file mode 100644 index 00000000000000..1ca25314631124 --- /dev/null +++ b/deps/zlib/google/OWNERS @@ -0,0 +1,5 @@ +satorux@chromium.org + +# compression_utils* +asvitkine@chromium.org +isherman@chromium.org diff --git a/deps/zlib/google/compression_utils.cc b/deps/zlib/google/compression_utils.cc new file mode 100644 index 00000000000000..9f63a840167d47 --- /dev/null +++ b/deps/zlib/google/compression_utils.cc @@ -0,0 +1,116 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/compression_utils.h" + +#include "base/bit_cast.h" +#include "base/logging.h" +#include "base/process/memory.h" +#include "base/strings/string_piece.h" +#include "base/sys_byteorder.h" + +#include "third_party/zlib/google/compression_utils_portable.h" + +namespace compression { + +bool GzipCompress(base::StringPiece input, + char* output_buffer, + size_t output_buffer_size, + size_t* compressed_size, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + static_assert(sizeof(Bytef) == 1, ""); + + // uLongf can be larger than size_t. + uLongf compressed_size_long = static_cast(output_buffer_size); + if (zlib_internal::GzipCompressHelper( + bit_cast(output_buffer), &compressed_size_long, + bit_cast(input.data()), + static_cast(input.size()), malloc_fn, free_fn) != Z_OK) { + return false; + } + // No overflow, as compressed_size_long <= output.size() which is a size_t. + *compressed_size = static_cast(compressed_size_long); + return true; +} + +bool GzipCompress(base::StringPiece input, std::string* output) { + // Not using std::vector<> because allocation failures are recoverable, + // which is hidden by std::vector<>. + static_assert(sizeof(Bytef) == 1, ""); + const uLongf input_size = static_cast(input.size()); + + uLongf compressed_data_size = + zlib_internal::GzipExpectedCompressedSize(input_size); + + Bytef* compressed_data; + if (!base::UncheckedMalloc(compressed_data_size, + reinterpret_cast(&compressed_data))) { + return false; + } + + if (zlib_internal::GzipCompressHelper(compressed_data, &compressed_data_size, + bit_cast(input.data()), + input_size, nullptr, nullptr) != Z_OK) { + free(compressed_data); + return false; + } + + Bytef* resized_data = + reinterpret_cast(realloc(compressed_data, compressed_data_size)); + if (!resized_data) { + free(compressed_data); + return false; + } + output->assign(resized_data, resized_data + compressed_data_size); + DCHECK_EQ(input_size, GetUncompressedSize(*output)); + + free(resized_data); + return true; +} + +bool GzipUncompress(const std::string& input, std::string* output) { + std::string uncompressed_output; + uLongf uncompressed_size = static_cast(GetUncompressedSize(input)); + if (uncompressed_size > uncompressed_output.max_size()) + return false; + + uncompressed_output.resize(uncompressed_size); + if (zlib_internal::GzipUncompressHelper( + bit_cast(uncompressed_output.data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK) { + output->swap(uncompressed_output); + return true; + } + return false; +} + +bool GzipUncompress(base::StringPiece input, base::StringPiece output) { + uLongf uncompressed_size = GetUncompressedSize(input); + if (uncompressed_size > output.size()) + return false; + return zlib_internal::GzipUncompressHelper( + bit_cast(output.data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK; +} + +bool GzipUncompress(base::StringPiece input, std::string* output) { + // Disallow in-place usage, i.e., |input| using |*output| as underlying data. + DCHECK_NE(input.data(), output->data()); + uLongf uncompressed_size = GetUncompressedSize(input); + output->resize(uncompressed_size); + return zlib_internal::GzipUncompressHelper( + bit_cast(output->data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK; +} + +uint32_t GetUncompressedSize(base::StringPiece compressed_data) { + return zlib_internal::GetGzipUncompressedSize( + bit_cast(compressed_data.data()), compressed_data.length()); +} + +} // namespace compression diff --git a/deps/zlib/google/compression_utils.h b/deps/zlib/google/compression_utils.h new file mode 100644 index 00000000000000..516220719ff43c --- /dev/null +++ b/deps/zlib/google/compression_utils.h @@ -0,0 +1,56 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ + +#include + +#include "base/strings/string_piece.h" + +namespace compression { + +// Compresses the data in |input| using gzip, storing the result in +// |output_buffer|, of size |output_buffer_size|. If the buffer is large enough +// and compression succeeds, |compressed_size| points to the compressed data +// size after the call. +// |malloc_fn| and |free_fn| are pointers to malloc() and free()-like functions, +// or nullptr to use the standard ones. +// Returns true for success. +bool GzipCompress(base::StringPiece input, + char* output_buffer, + size_t output_buffer_size, + size_t* compressed_size, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +// Compresses the data in |input| using gzip, storing the result in |output|. +// |input| and |output| are allowed to point to the same string (in-place +// operation). +// Returns true for success. +bool GzipCompress(base::StringPiece input, std::string* output); + +// Uncompresses the data in |input| using gzip, storing the result in |output|. +// |input| and |output| are allowed to be the same string (in-place operation). +// Returns true for success. +bool GzipUncompress(const std::string& input, std::string* output); + +// Like the above method, but uses base::StringPiece to avoid allocations if +// needed. |output|'s size must be at least as large as the return value from +// GetUncompressedSize. +// Returns true for success. +bool GzipUncompress(base::StringPiece input, base::StringPiece output); + +// Uncompresses the data in |input| using gzip, and writes the results to +// |output|, which must NOT be the underlying string of |input|, and is resized +// if necessary. +// Returns true for success. +bool GzipUncompress(base::StringPiece input, std::string* output); + +// Returns the uncompressed size from GZIP-compressed |compressed_data|. +uint32_t GetUncompressedSize(base::StringPiece compressed_data); + +} // namespace compression + +#endif // THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ diff --git a/deps/zlib/google/compression_utils_portable.cc b/deps/zlib/google/compression_utils_portable.cc new file mode 100644 index 00000000000000..191e349e31ad30 --- /dev/null +++ b/deps/zlib/google/compression_utils_portable.cc @@ -0,0 +1,205 @@ +/* compression_utils_portable.cc + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "third_party/zlib/google/compression_utils_portable.h" + +#include +#include +#include + +namespace zlib_internal { + +// The difference in bytes between a zlib header and a gzip header. +const size_t kGzipZlibHeaderDifferenceBytes = 16; + +// Pass an integer greater than the following get a gzip header instead of a +// zlib header when calling deflateInit2() and inflateInit2(). +const int kWindowBitsToGetGzipHeader = 16; + +// This describes the amount of memory zlib uses to compress data. It can go +// from 1 to 9, with 8 being the default. For details, see: +// http://www.zlib.net/manual.html (search for memLevel). +const int kZlibMemoryLevel = 8; + +// The expected compressed size is based on the input size factored by +// internal Zlib constants (e.g. window size, etc) plus the wrapper +// header size. +uLongf GzipExpectedCompressedSize(uLongf input_size) { + return kGzipZlibHeaderDifferenceBytes + compressBound(input_size); +} + +// The expected decompressed size is stored in the last +// 4 bytes of |input| in LE. See https://tools.ietf.org/html/rfc1952#page-5 +uint32_t GetGzipUncompressedSize(const Bytef* compressed_data, size_t length) { + uint32_t size; + if (length < sizeof(size)) + return 0; + + memcpy(&size, &compressed_data[length - sizeof(size)], sizeof(size)); +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + return size; +#else + return __builtin_bswap32(size); +#endif +} + +// The number of window bits determines the type of wrapper to use - see +// https://cs.chromium.org/chromium/src/third_party/zlib/zlib.h?l=566 +inline int ZlibStreamWrapperType(WrapperType type) { + if (type == ZLIB) // zlib DEFLATE stream wrapper + return MAX_WBITS; + if (type == GZIP) // gzip DEFLATE stream wrapper + return MAX_WBITS + kWindowBitsToGetGzipHeader; + if (type == ZRAW) // no wrapper, use raw DEFLATE + return -MAX_WBITS; + return 0; +} + +int GzipCompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + return CompressHelper(GZIP, dest, dest_length, source, source_length, + Z_DEFAULT_COMPRESSION, malloc_fn, free_fn); +} + +// This code is taken almost verbatim from third_party/zlib/compress.c. The only +// difference is deflateInit2() is called which allows different window bits to +// be set. > 16 causes a gzip header to be emitted rather than a zlib header, +// and negative causes no header to emitted. +// +// Compression level can be a number from 1-9, with 1 being the fastest, 9 being +// the best compression. The default, which the GZIP helper uses, is 6. +int CompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + int compression_level, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + if (compression_level < 1 || compression_level > 9) { + compression_level = Z_DEFAULT_COMPRESSION; + } + + z_stream stream; + + // FIXME(cavalcantii): z_const is not defined as 'const'. + stream.next_in = static_cast(const_cast(source)); + stream.avail_in = static_cast(source_length); + stream.next_out = dest; + stream.avail_out = static_cast(*dest_length); + if (static_cast(stream.avail_out) != *dest_length) + return Z_BUF_ERROR; + + // Cannot convert capturing lambdas to function pointers directly, hence the + // structure. + struct MallocFreeFunctions { + void* (*malloc_fn)(size_t); + void (*free_fn)(void*); + } malloc_free = {malloc_fn, free_fn}; + + if (malloc_fn) { + if (!free_fn) + return Z_BUF_ERROR; + + auto zalloc = [](void* opaque, uInt items, uInt size) { + return reinterpret_cast(opaque)->malloc_fn(items * + size); + }; + auto zfree = [](void* opaque, void* address) { + return reinterpret_cast(opaque)->free_fn(address); + }; + + stream.zalloc = static_cast(zalloc); + stream.zfree = static_cast(zfree); + stream.opaque = static_cast(&malloc_free); + } else { + stream.zalloc = static_cast(0); + stream.zfree = static_cast(0); + stream.opaque = static_cast(0); + } + + int err = deflateInit2(&stream, compression_level, Z_DEFLATED, + ZlibStreamWrapperType(wrapper_type), kZlibMemoryLevel, + Z_DEFAULT_STRATEGY); + if (err != Z_OK) + return err; + + // This has to exist outside of the if statement to prevent it going off the + // stack before deflate(), which will use this object. + gz_header gzip_header; + if (wrapper_type == GZIP) { + memset(&gzip_header, 0, sizeof(gzip_header)); + err = deflateSetHeader(&stream, &gzip_header); + if (err != Z_OK) + return err; + } + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *dest_length = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +int GzipUncompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length) { + return UncompressHelper(GZIP, dest, dest_length, source, source_length); +} + +// This code is taken almost verbatim from third_party/zlib/uncompr.c. The only +// difference is inflateInit2() is called which allows different window bits to +// be set. > 16 causes a gzip header to be emitted rather than a zlib header, +// and negative causes no header to emitted. +int UncompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length) { + z_stream stream; + + // FIXME(cavalcantii): z_const is not defined as 'const'. + stream.next_in = static_cast(const_cast(source)); + stream.avail_in = static_cast(source_length); + if (static_cast(stream.avail_in) != source_length) + return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = static_cast(*dest_length); + if (static_cast(stream.avail_out) != *dest_length) + return Z_BUF_ERROR; + + stream.zalloc = static_cast(0); + stream.zfree = static_cast(0); + + int err = inflateInit2(&stream, ZlibStreamWrapperType(wrapper_type)); + if (err != Z_OK) + return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *dest_length = stream.total_out; + + err = inflateEnd(&stream); + return err; +} + +} // namespace zlib_internal diff --git a/deps/zlib/google/compression_utils_portable.h b/deps/zlib/google/compression_utils_portable.h new file mode 100644 index 00000000000000..cd004e86cf515c --- /dev/null +++ b/deps/zlib/google/compression_utils_portable.h @@ -0,0 +1,59 @@ +/* compression_utils_portable.h + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifndef THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ + +#include + +#if defined(USE_SYSTEM_ZLIB) +#include +#else +#include "third_party/zlib/zlib.h" +#endif + +namespace zlib_internal { + +enum WrapperType { + ZLIB, + GZIP, + ZRAW, +}; + +uLongf GzipExpectedCompressedSize(uLongf input_size); + +uint32_t GetGzipUncompressedSize(const Bytef* compressed_data, size_t length); + +int GzipCompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +int CompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + int compression_level, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +int GzipUncompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length); + +int UncompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length); + +} // namespace zlib_internal + +#endif // THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ diff --git a/deps/zlib/google/compression_utils_unittest.cc b/deps/zlib/google/compression_utils_unittest.cc new file mode 100644 index 00000000000000..b0e04b8c973633 --- /dev/null +++ b/deps/zlib/google/compression_utils_unittest.cc @@ -0,0 +1,104 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/compression_utils.h" + +#include +#include + +#include + +#include "base/logging.h" +#include "base/stl_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace compression { + +namespace { + +// The data to be compressed by gzip. This is the hex representation of "hello +// world". +const uint8_t kData[] = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, + 0x77, 0x6f, 0x72, 0x6c, 0x64}; + +// This is the string representation of gzip compressed string above. It was +// obtained by running echo -n "hello world" | gzip -c | hexdump -e '8 1 ", +// 0x%x"' followed by 0'ing out the OS byte (10th byte) in the header. This is +// so that the test passes on all platforms (that run various OS'es). +const uint8_t kCompressedData[] = { + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcb, + 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x01, + 0x00, 0x85, 0x11, 0x4a, 0x0d, 0x0b, 0x00, 0x00, 0x00}; + +} // namespace + +TEST(CompressionUtilsTest, GzipCompression) { + std::string data(reinterpret_cast(kData), base::size(kData)); + std::string compressed_data; + EXPECT_TRUE(GzipCompress(data, &compressed_data)); + std::string golden_compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + EXPECT_EQ(golden_compressed_data, compressed_data); +} + +TEST(CompressionUtilsTest, GzipUncompression) { + std::string compressed_data(reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + std::string golden_data(reinterpret_cast(kData), + base::size(kData)); + EXPECT_EQ(golden_data, uncompressed_data); +} + +TEST(CompressionUtilsTest, GzipUncompressionFromStringPieceToString) { + base::StringPiece compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + std::string golden_data(reinterpret_cast(kData), + base::size(kData)); + EXPECT_EQ(golden_data, uncompressed_data); +} + +// Checks that compressing/decompressing input > 256 bytes works as expected. +TEST(CompressionUtilsTest, LargeInput) { + const size_t kSize = 32 * 1024; + + // Generate a data string of |kSize| for testing. + std::string data; + data.resize(kSize); + for (size_t i = 0; i < kSize; ++i) + data[i] = static_cast(i & 0xFF); + + std::string compressed_data; + EXPECT_TRUE(GzipCompress(data, &compressed_data)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + EXPECT_EQ(data, uncompressed_data); +} + +TEST(CompressionUtilsTest, InPlace) { + const std::string original_data(reinterpret_cast(kData), + base::size(kData)); + const std::string golden_compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string data(original_data); + EXPECT_TRUE(GzipCompress(data, &data)); + EXPECT_EQ(golden_compressed_data, data); + EXPECT_TRUE(GzipUncompress(data, &data)); + EXPECT_EQ(original_data, data); +} + +} // namespace compression diff --git a/deps/zlib/google/test/data/create_test_zip.sh b/deps/zlib/google/test/data/create_test_zip.sh new file mode 100644 index 00000000000000..f4cc635c2cf7a4 --- /dev/null +++ b/deps/zlib/google/test/data/create_test_zip.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +# +# Run this script in its directory to recreate test.zip, test_nocompress.zip, +# and test_encrypted.zip + +rm test.zip +rm test_nocompress.zip +rm test_encrypted.zip +pushd test +zip -r ../test.zip . +zip -r -0 ../test_nocompress.zip . +zip -P "fake_password" -r ../test_encrypted.zip . +popd diff --git a/deps/zlib/google/test/data/evil.zip b/deps/zlib/google/test/data/evil.zip new file mode 100644 index 00000000000000..8fb908a96abdf0 Binary files /dev/null and b/deps/zlib/google/test/data/evil.zip differ diff --git a/deps/zlib/google/test/data/evil_via_absolute_file_name.zip b/deps/zlib/google/test/data/evil_via_absolute_file_name.zip new file mode 100644 index 00000000000000..2415f81b63751b Binary files /dev/null and b/deps/zlib/google/test/data/evil_via_absolute_file_name.zip differ diff --git a/deps/zlib/google/test/data/evil_via_invalid_utf8.zip b/deps/zlib/google/test/data/evil_via_invalid_utf8.zip new file mode 100644 index 00000000000000..94b633e0aa5c2c Binary files /dev/null and b/deps/zlib/google/test/data/evil_via_invalid_utf8.zip differ diff --git a/deps/zlib/google/test/data/test.zip b/deps/zlib/google/test/data/test.zip new file mode 100644 index 00000000000000..4bafe30898eb9c Binary files /dev/null and b/deps/zlib/google/test/data/test.zip differ diff --git a/deps/zlib/google/test/data/test/foo.txt b/deps/zlib/google/test/data/test/foo.txt new file mode 100644 index 00000000000000..257cc5642cb1a0 --- /dev/null +++ b/deps/zlib/google/test/data/test/foo.txt @@ -0,0 +1 @@ +foo diff --git a/deps/zlib/google/test/data/test/foo/bar.txt b/deps/zlib/google/test/data/test/foo/bar.txt new file mode 100644 index 00000000000000..5716ca5987cbf9 --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar.txt @@ -0,0 +1 @@ +bar diff --git a/deps/zlib/google/test/data/test/foo/bar/.hidden b/deps/zlib/google/test/data/test/foo/bar/.hidden new file mode 100644 index 00000000000000..136c05e0d0290e --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/.hidden @@ -0,0 +1 @@ +hidden diff --git a/deps/zlib/google/test/data/test/foo/bar/baz.txt b/deps/zlib/google/test/data/test/foo/bar/baz.txt new file mode 100644 index 00000000000000..76018072e09c5d --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/baz.txt @@ -0,0 +1 @@ +baz diff --git a/deps/zlib/google/test/data/test/foo/bar/quux.txt b/deps/zlib/google/test/data/test/foo/bar/quux.txt new file mode 100644 index 00000000000000..479787951d98bf --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/quux.txt @@ -0,0 +1,39 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sem urna, semper ac, adipiscing sed, varius eget, quam. Fusce ipsum dolor, condimentum et, ornare in, consequat ac, nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla feugiat justo ac enim. Ut vehicula dapibus elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam lacus sem, viverra in, laoreet quis, cursus non, odio. Maecenas in elit. Pellentesque vitae dui. Ut dictum tellus et orci. Sed consectetur. Fusce tincidunt. Cras vulputate adipiscing metus. Aliquam lacinia. Vestibulum leo. Donec enim. Etiam imperdiet libero. Nam tellus ante, lobortis eget, dapibus vel, accumsan ultricies, nibh. In ultrices mauris at est. + +Phasellus ac elit sit amet felis aliquet venenatis. Sed porta libero at massa. Fusce blandit diam eget lorem. Nullam velit diam, fermentum eget, scelerisque non, faucibus a, tellus. Ut accumsan eros vitae velit. Proin vehicula aliquam felis. Proin ligula augue, gravida a, fermentum sit amet, sodales ac, purus. Phasellus sagittis scelerisque tellus. Ut gravida metus quis enim. Curabitur malesuada orci in massa. Pellentesque nibh turpis, adipiscing vel, rutrum quis, rhoncus vel, dolor. Pellentesque suscipit, arcu in egestas semper, lorem sapien vehicula nunc, non scelerisque lectus ante at diam. Etiam varius leo. Sed dictum, ante sed imperdiet ornare, felis leo lobortis eros, eu tincidunt lorem tellus sit amet mi. Mauris nisl elit, placerat non, scelerisque id, congue non, ligula. Nulla eget mi eu dolor scelerisque tempor. Fusce non lorem vel nibh mattis blandit. + +Vivamus sit amet urna quis eros varius condimentum. Phasellus placerat ligula ac felis. Vivamus tempor, metus id fermentum feugiat, justo ligula malesuada nisl, ut vulputate nisi arcu in eros. Vestibulum non erat in massa laoreet luctus. Praesent tempor, tortor eget sodales condimentum, purus odio gravida tellus, pellentesque euismod enim diam id augue. Duis malesuada lacus eu felis. Suspendisse tristique faucibus arcu. Etiam ac sapien. Aenean dolor enim, semper auctor, dapibus cursus, varius et, arcu. Aenean pede nunc, varius nec, pulvinar a, accumsan id, dui. Nulla a risus eget nibh pharetra rutrum. Quisque adipiscing adipiscing neque. Praesent faucibus lacus eu nulla. Vestibulum nec nunc vel quam cursus sollicitudin. Nam at quam at neque pharetra elementum. Sed ornare ullamcorper nibh. + +Aliquam aliquam vulputate diam. Ut molestie pharetra neque. Pellentesque sodales blandit nibh. Donec eget mauris eget mauris blandit pharetra. Etiam imperdiet commodo tellus. Nulla felis justo, vestibulum hendrerit, posuere vitae, viverra ut, risus. Pellentesque auctor, ante egestas suscipit vestibulum, sem dolor posuere urna, pellentesque dignissim ante orci a lectus. Suspendisse potenti. Sed et pede pretium arcu porttitor porta. Nullam nec nulla. Fusce lacinia, massa ac fermentum congue, dui quam varius mauris, vitae ullamcorper pede lacus at nisl. Suspendisse aliquam pede a sapien. Morbi pellentesque, mi id mattis aliquet, nisl erat tincidunt lorem, eu bibendum nunc nisi nec erat. Suspendisse commodo dapibus dolor. Quisque id risus. Nullam gravida est tempor lectus. + +Morbi mattis. Cras sagittis. Sed eleifend odio sit amet nibh. Cras sit amet massa. Donec congue nulla vel augue. Maecenas fermentum turpis at diam. In lobortis. Phasellus aliquet. Etiam eu diam. Integer accumsan. Integer sagittis tempor mi. Aliquam interdum lectus id augue. Donec vel eros. Donec vitae orci a sapien imperdiet consectetur. + +Maecenas est lorem, luctus vel, fringilla sed, rutrum nec, nisl. Donec sapien. Vestibulum at metus. Praesent erat. Nulla semper metus a lacus. Morbi ultrices. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus odio. Ut mauris. Fusce et risus. Proin at mauris a eros imperdiet mollis. Sed adipiscing hendrerit nisl. Curabitur libero. Donec nulla. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + +Nullam non lacus. Vivamus rhoncus dolor sit amet ipsum. Vivamus volutpat eleifend odio. Vestibulum nunc. In at magna a pede gravida vulputate. Praesent ligula tellus, rhoncus elementum, pulvinar a, condimentum vitae, libero. Donec ornare dui. Proin non lorem quis massa placerat interdum. Nam justo. Aliquam rutrum dignissim mi. Mauris tellus. Proin dui felis, lacinia quis, volutpat a, blandit sed, neque. Etiam non dolor eu justo interdum tristique. Morbi volutpat, elit vitae rutrum iaculis, augue mi accumsan metus, sed porttitor felis mi sed felis. + +Nulla quam lectus, pharetra non, sodales sit amet, pretium quis, massa. Aliquam orci. Duis id massa. Pellentesque porttitor nibh id quam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec convallis, pede vitae volutpat consequat, justo lorem ultricies nisi, ut scelerisque leo lorem in tellus. Cras bibendum. Sed hendrerit placerat tortor. Sed felis. Aliquam erat volutpat. Praesent rhoncus nisi. Vestibulum justo felis, tincidunt luctus, suscipit sed, tincidunt ut, lorem. Proin non risus ac mi mattis volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam pellentesque nisl sit amet sapien rutrum porta. + +Phasellus ut pede non odio ultricies egestas. Aenean nibh. Mauris magna felis, posuere non, tempus et, bibendum ut, felis. Donec vel ipsum ac nisi dapibus lobortis. Sed congue ligula at est. Vivamus elit est, rhoncus vitae, tempus at, consectetur nec, elit. Duis vehicula tellus vitae sem. Suspendisse rhoncus felis sit amet magna. Maecenas vulputate risus in diam. Nunc sollicitudin risus eget quam. Nam pretium purus eleifend dolor. Integer erat nulla, mattis eu, sollicitudin sed, sagittis nec, metus. + +Donec ante felis, ultrices nec, pellentesque nec, elementum et, nunc. Pellentesque in tortor sit amet urna aliquet tincidunt. Praesent ultrices. Sed tincidunt. Donec turpis enim, feugiat eu, cursus ut, viverra ut, odio. Morbi in orci quis enim vehicula lobortis. Proin in neque. Pellentesque venenatis neque sit amet augue. Proin suscipit nibh. Praesent et diam. + +In eget ligula quis libero vulputate eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc non urna vitae mi vulputate adipiscing. Nulla vitae arcu. Nullam ut nisl ac enim pulvinar auctor. Suspendisse tortor pede, consectetur in, volutpat at, condimentum vel, ligula. Pellentesque nisi est, vulputate vitae, hendrerit id, venenatis sit amet, urna. Nunc lobortis. Sed rhoncus, tortor vitae pellentesque facilisis, massa ante interdum massa, feugiat faucibus pede nunc et tellus. Quisque auctor sollicitudin nibh. Aliquam congue. Praesent ullamcorper mi id lacus. Nullam ac risus et velit ullamcorper vehicula. Vestibulum consectetur convallis neque. Donec dapibus, ante a rutrum interdum, mi dui auctor lacus, quis posuere eros diam eu nisl. Integer nec velit vel purus eleifend condimentum. Cras quis nunc. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. + +Sed euismod, metus eu consectetur dictum, felis eros sodales pede, ac pellentesque lacus orci sed velit. Praesent a justo. Aliquam massa dolor, condimentum non, dapibus quis, vestibulum a, purus. Duis gravida porta dolor. Nullam sit amet mi sagittis massa pretium ultricies. Ut fringilla. Aliquam venenatis feugiat dui. Pellentesque tempor, leo et ullamcorper placerat, felis libero blandit nisl, sit amet pharetra nisl erat sit amet dolor. In sem erat, porta rhoncus, auctor ac, convallis feugiat, dui. Sed tempus metus at erat. Cras gravida. Cras urna nisi, fermentum non, sodales sed, adipiscing sed, nulla. + +Donec pellentesque, velit sit amet ultricies dictum, sem quam posuere arcu, tristique mollis nibh dui ac libero. Vestibulum consectetur velit sed dolor. Nullam ornare sodales nisi. Sed facilisis sollicitudin arcu. Proin vitae lectus vel nulla auctor faucibus. Aenean nec nisl sit amet risus faucibus tincidunt. Ut sed nisl. Vivamus vehicula ligula a nunc. Curabitur mauris. Integer est felis, fermentum aliquam, dignissim id, gravida id, purus. Nullam porta felis eget ante. Phasellus lacinia, odio et elementum viverra, dui neque tempus massa, ac adipiscing lectus velit vitae turpis. Integer scelerisque neque in tortor. Duis et elit. Mauris elementum urna sed risus. Nunc aliquet, ipsum ac venenatis elementum, sapien orci vulputate lacus, eu lobortis sapien lorem non enim. Donec enim sapien, gravida vitae, vestibulum et, mattis dapibus, sem. Phasellus mi. + +Cras a lorem nec diam aliquet viverra. Aliquam sed leo sit amet neque porta venenatis. Nulla facilisi. Duis lectus felis, fermentum quis, sagittis a, vestibulum consectetur, orci. Suspendisse sodales odio vitae lectus. Curabitur nunc. Phasellus cursus diam sit amet ipsum. Aenean cursus tellus eget nunc. Vivamus mattis urna a lorem. Mauris vitae mi. Morbi luctus molestie pede. Vestibulum lobortis lacus sed lacus. Aliquam nisl libero, pellentesque sed, facilisis ut, varius vehicula, lacus. Mauris orci. Pellentesque sed risus id quam sodales lobortis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed facilisis, odio vitae laoreet auctor, nulla dui sagittis lectus, sit amet viverra orci arcu et lectus. Pellentesque ut sem. Maecenas a est. + +Suspendisse tincidunt. Sed bibendum molestie ligula. Suspendisse massa mauris, cursus a, luctus eget, posuere sed, nulla. Fusce vitae urna. Duis fermentum. Donec a neque ac pede lobortis mollis. Donec massa ligula, facilisis et, dapibus sed, ultrices non, sem. Phasellus diam. Maecenas velit arcu, viverra ut, gravida ac, tincidunt eget, nunc. Sed sit amet enim non dui tristique lacinia. Vivamus eu orci. Duis metus. Nulla facilisi. Phasellus at lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus mauris. Duis dictum, erat eu scelerisque sollicitudin, mi augue tincidunt lorem, vel lacinia lectus nibh quis dui. Ut ornare dignissim elit. Phasellus posuere ligula vel justo. + +Sed neque. Quisque porttitor lorem vel arcu. Praesent a mi et risus suscipit egestas. Proin est lectus, rhoncus sit amet, aliquet non, fermentum ut, nulla. Aenean erat nisl, rutrum dictum, placerat vel, malesuada ac, arcu. Suspendisse posuere, ante sed consequat gravida, velit mi dignissim sem, et pretium dui diam in elit. Sed dictum nulla. Duis tristique tincidunt eros. Morbi velit. Donec a lorem. Aliquam cursus. Vivamus dapibus varius neque. Quisque eget diam. Nulla facilisi. Pellentesque eu sapien. Curabitur egestas cursus risus. Proin odio tortor, interdum eget, fringilla venenatis, luctus et, turpis. Phasellus nulla lorem, ullamcorper ut, elementum rhoncus, ultrices sed, ipsum. Nam volutpat. + +Quisque eu purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur non nulla. Donec dignissim porta lorem. Mauris ornare venenatis odio. Aenean eu lectus at eros porta molestie. Vivamus neque. Morbi aliquam. Nulla tincidunt enim id ligula. Nunc gravida felis consectetur dolor. Phasellus tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla nec libero quis ipsum auctor vehicula. Maecenas consectetur tempor turpis. Integer commodo. In hac habitasse platea dictumst. Donec nec justo quis sem placerat gravida. Donec sollicitudin, turpis sit amet bibendum elementum, nisl ligula venenatis ipsum, vel sollicitudin justo arcu eu leo. Phasellus aliquet faucibus libero. + +Nam molestie nulla eu risus. Fusce id erat. Maecenas volutpat nunc eu ligula. Sed tortor est, imperdiet quis, viverra et, ornare in, ipsum. Praesent aliquet. Nulla suscipit. In posuere enim in odio. Nullam ante ipsum, imperdiet id, convallis id, hendrerit id, libero. Donec convallis libero ut felis. Curabitur venenatis placerat justo. Vestibulum mauris arcu, scelerisque et, dapibus vel, scelerisque a, lectus. Sed sit amet orci id felis tristique tincidunt. Curabitur adipiscing, nulla vel pretium tristique, tellus ipsum lacinia eros, vitae venenatis pede lectus sit amet neque. Nulla feugiat. Aenean euismod, nunc vel rutrum mattis, lorem purus venenatis sapien, sed facilisis pede enim at elit. Vivamus viverra. Cras vitae purus ac felis fringilla condimentum. Nullam ac nisi vitae massa faucibus aliquet. + +Etiam ut nibh nec neque elementum iaculis. Maecenas facilisis nulla at lorem. Pellentesque elit sapien, ultricies at, dignissim nec, cursus eu, pede. Morbi gravida, ipsum eget malesuada eleifend, est arcu pulvinar nisl, et fermentum urna felis sed tellus. Mauris fermentum sollicitudin neque. Nunc at odio. Pellentesque et turpis. Cras congue congue nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam feugiat dapibus tellus. Aenean aliquam, mi id interdum feugiat, nunc lorem laoreet massa, ac semper urna sem vel purus. Quisque bibendum tellus ut est. + +Morbi aliquam lectus sit amet nisi. Praesent urna purus, porttitor vitae, accumsan in, sollicitudin at, lorem. Donec diam dui, hendrerit eget, tincidunt ut, ultrices vehicula, dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat. Pellentesque iaculis iaculis lacus. Fusce auctor. Morbi vulputate purus at felis. Maecenas a pede nec metus vulputate ullamcorper. Cras non lectus. Suspendisse lacinia. diff --git a/deps/zlib/google/test/data/test_encrypted.zip b/deps/zlib/google/test/data/test_encrypted.zip new file mode 100644 index 00000000000000..5e2a75759a1914 Binary files /dev/null and b/deps/zlib/google/test/data/test_encrypted.zip differ diff --git a/deps/zlib/google/test/data/test_mismatch_size.zip b/deps/zlib/google/test/data/test_mismatch_size.zip new file mode 100644 index 00000000000000..b83c66fe79125c Binary files /dev/null and b/deps/zlib/google/test/data/test_mismatch_size.zip differ diff --git a/deps/zlib/google/test/data/test_nocompress.zip b/deps/zlib/google/test/data/test_nocompress.zip new file mode 100644 index 00000000000000..25d66c287e2c75 Binary files /dev/null and b/deps/zlib/google/test/data/test_nocompress.zip differ diff --git a/deps/zlib/google/zip.cc b/deps/zlib/google/zip.cc new file mode 100644 index 00000000000000..907e5da72e974d --- /dev/null +++ b/deps/zlib/google/zip.cc @@ -0,0 +1,271 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip.h" + +#include +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_enumerator.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/strings/string_util.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip_internal.h" +#include "third_party/zlib/google/zip_reader.h" +#include "third_party/zlib/google/zip_writer.h" + +namespace zip { +namespace { + +bool IsHiddenFile(const base::FilePath& file_path) { + return file_path.BaseName().value()[0] == '.'; +} + +bool ExcludeNoFilesFilter(const base::FilePath& file_path) { + return true; +} + +bool ExcludeHiddenFilesFilter(const base::FilePath& file_path) { + return !IsHiddenFile(file_path); +} + +// Creates a directory at |extract_dir|/|entry_path|, including any parents. +bool CreateDirectory(const base::FilePath& extract_dir, + const base::FilePath& entry_path) { + return base::CreateDirectory(extract_dir.Append(entry_path)); +} + +// Creates a WriterDelegate that can write a file at |extract_dir|/|entry_path|. +std::unique_ptr CreateFilePathWriterDelegate( + const base::FilePath& extract_dir, + const base::FilePath& entry_path) { + return std::make_unique( + extract_dir.Append(entry_path)); +} + +class DirectFileAccessor : public FileAccessor { + public: + explicit DirectFileAccessor(base::FilePath src_dir) : src_dir_(src_dir) {} + ~DirectFileAccessor() override = default; + + std::vector OpenFilesForReading( + const std::vector& paths) override { + std::vector files; + for (const auto& path : paths) { + base::File file; + if (base::PathExists(path) && !base::DirectoryExists(path)) { + file = base::File(path, base::File::FLAG_OPEN | base::File::FLAG_READ); + } + files.push_back(std::move(file)); + } + return files; + } + + bool DirectoryExists(const base::FilePath& file) override { + return base::DirectoryExists(file); + } + + std::vector ListDirectoryContent( + const base::FilePath& dir) override { + std::vector files; + base::FileEnumerator file_enumerator( + dir, false /* recursive */, + base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES); + for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); + path = file_enumerator.Next()) { + files.push_back(DirectoryContentEntry(path, base::DirectoryExists(path))); + } + return files; + } + + base::Time GetLastModifiedTime(const base::FilePath& path) override { + base::File::Info file_info; + if (!base::GetFileInfo(path, &file_info)) { + LOG(ERROR) << "Failed to retrieve file modification time for " + << path.value(); + } + return file_info.last_modified; + } + + private: + base::FilePath src_dir_; + + DISALLOW_COPY_AND_ASSIGN(DirectFileAccessor); +}; + +} // namespace + +ZipParams::ZipParams(const base::FilePath& src_dir, + const base::FilePath& dest_file) + : src_dir_(src_dir), + dest_file_(dest_file), + file_accessor_(new DirectFileAccessor(src_dir)) {} + +#if defined(OS_POSIX) +// Does not take ownership of |fd|. +ZipParams::ZipParams(const base::FilePath& src_dir, int dest_fd) + : src_dir_(src_dir), + dest_fd_(dest_fd), + file_accessor_(new DirectFileAccessor(src_dir)) {} +#endif + +bool Zip(const ZipParams& params) { + // Using a pointer to avoid copies of a potentially large array. + const std::vector* files_to_add = ¶ms.files_to_zip(); + std::vector all_files; + if (files_to_add->empty()) { + // Include all files from the src_dir (modulo the src_dir itself and + // filtered and hidden files). + + files_to_add = &all_files; + // Using a list so we can call push_back while iterating. + std::list entries; + entries.push_back(FileAccessor::DirectoryContentEntry( + params.src_dir(), true /* is directory*/)); + const FilterCallback& filter_callback = params.filter_callback(); + for (auto iter = entries.begin(); iter != entries.end(); ++iter) { + const base::FilePath& entry_path = iter->path; + if (iter != entries.begin() && // Don't filter the root dir. + ((!params.include_hidden_files() && IsHiddenFile(entry_path)) || + (filter_callback && !filter_callback.Run(entry_path)))) { + continue; + } + + if (iter != entries.begin()) { // Exclude the root dir from the ZIP file. + // Make the path relative for AddEntryToZip. + base::FilePath relative_path; + bool success = + params.src_dir().AppendRelativePath(entry_path, &relative_path); + DCHECK(success); + all_files.push_back(relative_path); + } + + if (iter->is_directory) { + std::vector subentries = + params.file_accessor()->ListDirectoryContent(entry_path); + entries.insert(entries.end(), subentries.begin(), subentries.end()); + } + } + } + + std::unique_ptr zip_writer; +#if defined(OS_POSIX) + if (params.dest_fd() != base::kInvalidPlatformFile) { + DCHECK(params.dest_file().empty()); + zip_writer = internal::ZipWriter::CreateWithFd( + params.dest_fd(), params.src_dir(), params.file_accessor()); + if (!zip_writer) + return false; + } +#endif + if (!zip_writer) { + zip_writer = internal::ZipWriter::Create( + params.dest_file(), params.src_dir(), params.file_accessor()); + if (!zip_writer) + return false; + } + return zip_writer->WriteEntries(*files_to_add); +} + +bool Unzip(const base::FilePath& src_file, const base::FilePath& dest_dir) { + return UnzipWithFilterCallback( + src_file, dest_dir, base::BindRepeating(&ExcludeNoFilesFilter), true); +} + +bool UnzipWithFilterCallback(const base::FilePath& src_file, + const base::FilePath& dest_dir, + const FilterCallback& filter_cb, + bool log_skipped_files) { + base::File file(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ); + if (!file.IsValid()) { + DLOG(WARNING) << "Failed to open " << src_file.value(); + return false; + } + return UnzipWithFilterAndWriters( + file.GetPlatformFile(), + base::BindRepeating(&CreateFilePathWriterDelegate, dest_dir), + base::BindRepeating(&CreateDirectory, dest_dir), filter_cb, + log_skipped_files); +} + +bool UnzipWithFilterAndWriters(const base::PlatformFile& src_file, + const WriterFactory& writer_factory, + const DirectoryCreator& directory_creator, + const FilterCallback& filter_cb, + bool log_skipped_files) { + ZipReader reader; + if (!reader.OpenFromPlatformFile(src_file)) { + DLOG(WARNING) << "Failed to open src_file " << src_file; + return false; + } + while (reader.HasMore()) { + if (!reader.OpenCurrentEntryInZip()) { + DLOG(WARNING) << "Failed to open the current file in zip"; + return false; + } + const base::FilePath& entry_path = reader.current_entry_info()->file_path(); + if (reader.current_entry_info()->is_unsafe()) { + DLOG(WARNING) << "Found an unsafe file in zip " << entry_path; + return false; + } + if (filter_cb.Run(entry_path)) { + if (reader.current_entry_info()->is_directory()) { + if (!directory_creator.Run(entry_path)) + return false; + } else { + std::unique_ptr writer = writer_factory.Run(entry_path); + if (!reader.ExtractCurrentEntry(writer.get(), + std::numeric_limits::max())) { + DLOG(WARNING) << "Failed to extract " << entry_path; + return false; + } + } + } else if (log_skipped_files) { + DLOG(WARNING) << "Skipped file " << entry_path; + } + + if (!reader.AdvanceToNextEntry()) { + DLOG(WARNING) << "Failed to advance to the next file"; + return false; + } + } + return true; +} + +bool ZipWithFilterCallback(const base::FilePath& src_dir, + const base::FilePath& dest_file, + const FilterCallback& filter_cb) { + DCHECK(base::DirectoryExists(src_dir)); + ZipParams params(src_dir, dest_file); + params.set_filter_callback(filter_cb); + return Zip(params); +} + +bool Zip(const base::FilePath& src_dir, const base::FilePath& dest_file, + bool include_hidden_files) { + if (include_hidden_files) { + return ZipWithFilterCallback(src_dir, dest_file, + base::BindRepeating(&ExcludeNoFilesFilter)); + } else { + return ZipWithFilterCallback( + src_dir, dest_file, base::BindRepeating(&ExcludeHiddenFilesFilter)); + } +} + +#if defined(OS_POSIX) +bool ZipFiles(const base::FilePath& src_dir, + const std::vector& src_relative_paths, + int dest_fd) { + DCHECK(base::DirectoryExists(src_dir)); + ZipParams params(src_dir, dest_fd); + params.set_files_to_zip(src_relative_paths); + return Zip(params); +} +#endif // defined(OS_POSIX) + +} // namespace zip diff --git a/deps/zlib/google/zip.h b/deps/zlib/google/zip.h new file mode 100644 index 00000000000000..4f64a8aca883a8 --- /dev/null +++ b/deps/zlib/google/zip.h @@ -0,0 +1,181 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ + +#include + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/files/platform_file.h" +#include "base/time/time.h" +#include "build/build_config.h" + +namespace base { +class File; +} + +namespace zip { + +class WriterDelegate; + +// Abstraction for file access operation required by Zip(). +// Can be passed to the ZipParams for providing custom access to the files, +// for example over IPC. +// If none is provided, the files are accessed directly. +// All parameters paths are expected to be absolute. +class FileAccessor { + public: + virtual ~FileAccessor() = default; + + struct DirectoryContentEntry { + DirectoryContentEntry(const base::FilePath& path, bool is_directory) + : path(path), is_directory(is_directory) {} + base::FilePath path; + bool is_directory = false; + }; + + // Opens files specified in |paths|. + // Directories should be mapped to invalid files. + virtual std::vector OpenFilesForReading( + const std::vector& paths) = 0; + + virtual bool DirectoryExists(const base::FilePath& path) = 0; + virtual std::vector ListDirectoryContent( + const base::FilePath& dir_path) = 0; + virtual base::Time GetLastModifiedTime(const base::FilePath& path) = 0; +}; + +class ZipParams { + public: + ZipParams(const base::FilePath& src_dir, const base::FilePath& dest_file); +#if defined(OS_POSIX) + // Does not take ownership of |dest_fd|. + ZipParams(const base::FilePath& src_dir, int dest_fd); + + int dest_fd() const { return dest_fd_; } +#endif + + const base::FilePath& src_dir() const { return src_dir_; } + + const base::FilePath& dest_file() const { return dest_file_; } + + // Restricts the files actually zipped to the paths listed in + // |src_relative_paths|. They must be relative to the |src_dir| passed in the + // constructor and will be used as the file names in the created zip file. All + // source paths must be under |src_dir| in the file system hierarchy. + void set_files_to_zip(const std::vector& src_relative_paths) { + src_files_ = src_relative_paths; + } + const std::vector& files_to_zip() const { return src_files_; } + + using FilterCallback = base::RepeatingCallback; + void set_filter_callback(FilterCallback filter_callback) { + filter_callback_ = filter_callback; + } + const FilterCallback& filter_callback() const { return filter_callback_; } + + void set_include_hidden_files(bool include_hidden_files) { + include_hidden_files_ = include_hidden_files; + } + bool include_hidden_files() const { return include_hidden_files_; } + + // Sets a custom file accessor for file operations. Default is to directly + // access the files (with fopen and the rest). + // Useful in cases where running in a sandbox process and file access has to + // go through IPC, for example. + void set_file_accessor(std::unique_ptr file_accessor) { + file_accessor_ = std::move(file_accessor); + } + FileAccessor* file_accessor() const { return file_accessor_.get(); } + + private: + base::FilePath src_dir_; + + base::FilePath dest_file_; +#if defined(OS_POSIX) + int dest_fd_ = base::kInvalidPlatformFile; +#endif + + // The relative paths to the files that should be included in the zip file. If + // this is empty, all files in |src_dir_| are included. + std::vector src_files_; + + // Filter used to exclude files from the ZIP file. Only effective when + // |src_files_| is empty. + FilterCallback filter_callback_; + + // Whether hidden files should be included in the ZIP file. Only effective + // when |src_files_| is empty. + bool include_hidden_files_ = true; + + // Abstraction around file system access used to read files. An implementation + // that accesses files directly is provided by default. + std::unique_ptr file_accessor_; +}; + +// Zip files specified into a ZIP archives. The source files and ZIP destination +// files (as well as other settings) are specified in |params|. +bool Zip(const ZipParams& params); + +// Zip the contents of src_dir into dest_file. src_path must be a directory. +// An entry will *not* be created in the zip for the root folder -- children +// of src_dir will be at the root level of the created zip. For each file in +// src_dir, include it only if the callback |filter_cb| returns true. Otherwise +// omit it. +using FilterCallback = base::RepeatingCallback; +bool ZipWithFilterCallback(const base::FilePath& src_dir, + const base::FilePath& dest_file, + const FilterCallback& filter_cb); + +// Convenience method for callers who don't need to set up the filter callback. +// If |include_hidden_files| is true, files starting with "." are included. +// Otherwise they are omitted. +bool Zip(const base::FilePath& src_dir, const base::FilePath& dest_file, + bool include_hidden_files); + +#if defined(OS_POSIX) +// Zips files listed in |src_relative_paths| to destination specified by file +// descriptor |dest_fd|, without taking ownership of |dest_fd|. The paths listed +// in |src_relative_paths| are relative to the |src_dir| and will be used as the +// file names in the created zip file. All source paths must be under |src_dir| +// in the file system hierarchy. +bool ZipFiles(const base::FilePath& src_dir, + const std::vector& src_relative_paths, + int dest_fd); +#endif // defined(OS_POSIX) + +// Unzip the contents of zip_file into dest_dir. +// For each file in zip_file, include it only if the callback |filter_cb| +// returns true. Otherwise omit it. +// If |log_skipped_files| is true, files skipped during extraction are printed +// to debug log. +using FilterCallback = base::RepeatingCallback; +bool UnzipWithFilterCallback(const base::FilePath& zip_file, + const base::FilePath& dest_dir, + const FilterCallback& filter_cb, + bool log_skipped_files); + +// Unzip the contents of zip_file, using the writers provided by writer_factory. +// For each file in zip_file, include it only if the callback |filter_cb| +// returns true. Otherwise omit it. +// If |log_skipped_files| is true, files skipped during extraction are printed +// to debug log. +typedef base::RepeatingCallback( + const base::FilePath&)> + WriterFactory; +typedef base::RepeatingCallback DirectoryCreator; +bool UnzipWithFilterAndWriters(const base::PlatformFile& zip_file, + const WriterFactory& writer_factory, + const DirectoryCreator& directory_creator, + const FilterCallback& filter_cb, + bool log_skipped_files); + +// Unzip the contents of zip_file into dest_dir. +bool Unzip(const base::FilePath& zip_file, const base::FilePath& dest_dir); + +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ diff --git a/deps/zlib/google/zip_internal.cc b/deps/zlib/google/zip_internal.cc new file mode 100644 index 00000000000000..314740f5447c03 --- /dev/null +++ b/deps/zlib/google/zip_internal.cc @@ -0,0 +1,379 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_internal.h" + +#include + +#include + +#include "base/logging.h" +#include "base/strings/utf_string_conversions.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#if defined(OS_WIN) +#include "third_party/zlib/contrib/minizip/iowin32.h" +#elif defined(OS_POSIX) +#include "third_party/zlib/contrib/minizip/ioapi.h" +#endif // defined(OS_POSIX) +#endif // defined(USE_SYSTEM_MINIZIP) + +namespace { + +#if defined(OS_WIN) +typedef struct { + HANDLE hf; + int error; +} WIN32FILE_IOWIN; + +// This function is derived from third_party/minizip/iowin32.c. +// Its only difference is that it treats the char* as UTF8 and +// uses the Unicode version of CreateFile. +void* ZipOpenFunc(void *opaque, const char* filename, int mode) { + DWORD desired_access = 0, creation_disposition = 0; + DWORD share_mode = 0, flags_and_attributes = 0; + HANDLE file = 0; + void* ret = NULL; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) { + desired_access = GENERIC_READ; + creation_disposition = OPEN_EXISTING; + share_mode = FILE_SHARE_READ; + } else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) { + desired_access = GENERIC_WRITE | GENERIC_READ; + creation_disposition = OPEN_EXISTING; + } else if (mode & ZLIB_FILEFUNC_MODE_CREATE) { + desired_access = GENERIC_WRITE | GENERIC_READ; + creation_disposition = CREATE_ALWAYS; + } + + base::string16 filename16 = base::UTF8ToUTF16(filename); + if ((filename != NULL) && (desired_access != 0)) { + file = CreateFile(filename16.c_str(), desired_access, share_mode, + NULL, creation_disposition, flags_and_attributes, NULL); + } + + if (file == INVALID_HANDLE_VALUE) + file = NULL; + + if (file != NULL) { + WIN32FILE_IOWIN file_ret; + file_ret.hf = file; + file_ret.error = 0; + ret = malloc(sizeof(WIN32FILE_IOWIN)); + if (ret == NULL) + CloseHandle(file); + else + *(static_cast(ret)) = file_ret; + } + return ret; +} +#endif + +#if defined(OS_POSIX) +// Callback function for zlib that opens a file stream from a file descriptor. +// Since we do not own the file descriptor, dup it so that we can fdopen/fclose +// a file stream. +void* FdOpenFileFunc(void* opaque, const char* filename, int mode) { + FILE* file = NULL; + const char* mode_fopen = NULL; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename != NULL) && (mode_fopen != NULL)) { + int fd = dup(*static_cast(opaque)); + if (fd != -1) + file = fdopen(fd, mode_fopen); + } + + return file; +} + +int FdCloseFileFunc(void* opaque, void* stream) { + fclose(static_cast(stream)); + free(opaque); // malloc'ed in FillFdOpenFileFunc() + return 0; +} + +// Fills |pzlib_filecunc_def| appropriately to handle the zip file +// referred to by |fd|. +void FillFdOpenFileFunc(zlib_filefunc_def* pzlib_filefunc_def, int fd) { + fill_fopen_filefunc(pzlib_filefunc_def); + pzlib_filefunc_def->zopen_file = FdOpenFileFunc; + pzlib_filefunc_def->zclose_file = FdCloseFileFunc; + int* ptr_fd = static_cast(malloc(sizeof(fd))); + *ptr_fd = fd; + pzlib_filefunc_def->opaque = ptr_fd; +} +#endif // defined(OS_POSIX) + +#if defined(OS_WIN) +// Callback function for zlib that opens a file stream from a Windows handle. +// Does not take ownership of the handle. +void* HandleOpenFileFunc(void* opaque, const char* filename, int mode) { + WIN32FILE_IOWIN file_ret; + file_ret.hf = static_cast(opaque); + file_ret.error = 0; + if (file_ret.hf == INVALID_HANDLE_VALUE) + return NULL; + + void* ret = malloc(sizeof(WIN32FILE_IOWIN)); + if (ret != NULL) + *(static_cast(ret)) = file_ret; + return ret; +} + +int HandleCloseFileFunc(void* opaque, void* stream) { + free(stream); // malloc'ed in HandleOpenFileFunc() + return 0; +} +#endif + +// A struct that contains data required for zlib functions to extract files from +// a zip archive stored in memory directly. The following I/O API functions +// expect their opaque parameters refer to this struct. +struct ZipBuffer { + const char* data; // weak + size_t length; + size_t offset; +}; + +// Opens the specified file. When this function returns a non-NULL pointer, zlib +// uses this pointer as a stream parameter while compressing or uncompressing +// data. (Returning NULL represents an error.) This function initializes the +// given opaque parameter and returns it because this parameter stores all +// information needed for uncompressing data. (This function does not support +// writing compressed data and it returns NULL for this case.) +void* OpenZipBuffer(void* opaque, const char* /*filename*/, int mode) { + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) { + NOTREACHED(); + return NULL; + } + ZipBuffer* buffer = static_cast(opaque); + if (!buffer || !buffer->data || !buffer->length) + return NULL; + buffer->offset = 0; + return opaque; +} + +// Reads compressed data from the specified stream. This function copies data +// refered by the opaque parameter and returns the size actually copied. +uLong ReadZipBuffer(void* opaque, void* /*stream*/, void* buf, uLong size) { + ZipBuffer* buffer = static_cast(opaque); + DCHECK_LE(buffer->offset, buffer->length); + size_t remaining_bytes = buffer->length - buffer->offset; + if (!buffer || !buffer->data || !remaining_bytes) + return 0; + size = std::min(size, static_cast(remaining_bytes)); + memcpy(buf, &buffer->data[buffer->offset], size); + buffer->offset += size; + return size; +} + +// Writes compressed data to the stream. This function always returns zero +// because this implementation is only for reading compressed data. +uLong WriteZipBuffer(void* /*opaque*/, + void* /*stream*/, + const void* /*buf*/, + uLong /*size*/) { + NOTREACHED(); + return 0; +} + +// Returns the offset from the beginning of the data. +long GetOffsetOfZipBuffer(void* opaque, void* /*stream*/) { + ZipBuffer* buffer = static_cast(opaque); + if (!buffer) + return -1; + return static_cast(buffer->offset); +} + +// Moves the current offset to the specified position. +long SeekZipBuffer(void* opaque, void* /*stream*/, uLong offset, int origin) { + ZipBuffer* buffer = static_cast(opaque); + if (!buffer) + return -1; + if (origin == ZLIB_FILEFUNC_SEEK_CUR) { + buffer->offset = std::min(buffer->offset + static_cast(offset), + buffer->length); + return 0; + } + if (origin == ZLIB_FILEFUNC_SEEK_END) { + buffer->offset = (buffer->length > offset) ? buffer->length - offset : 0; + return 0; + } + if (origin == ZLIB_FILEFUNC_SEEK_SET) { + buffer->offset = std::min(buffer->length, static_cast(offset)); + return 0; + } + NOTREACHED(); + return -1; +} + +// Closes the input offset and deletes all resources used for compressing or +// uncompressing data. This function deletes the ZipBuffer object referred by +// the opaque parameter since zlib deletes the unzFile object and it does not +// use this object any longer. +int CloseZipBuffer(void* opaque, void* /*stream*/) { + if (opaque) + free(opaque); + return 0; +} + +// Returns the last error happened when reading or writing data. This function +// always returns zero, which means there are not any errors. +int GetErrorOfZipBuffer(void* /*opaque*/, void* /*stream*/) { + return 0; +} + +// Returns a zip_fileinfo struct with the time represented by |file_time|. +zip_fileinfo TimeToZipFileInfo(const base::Time& file_time) { + base::Time::Exploded file_time_parts; + file_time.LocalExplode(&file_time_parts); + + zip_fileinfo zip_info = {}; + if (file_time_parts.year >= 1980) { + // This if check works around the handling of the year value in + // contrib/minizip/zip.c in function zip64local_TmzDateToDosDate + // It assumes that dates below 1980 are in the double digit format. + // Hence the fail safe option is to leave the date unset. Some programs + // might show the unset date as 1980-0-0 which is invalid. + zip_info.tmz_date.tm_year = file_time_parts.year; + zip_info.tmz_date.tm_mon = file_time_parts.month - 1; + zip_info.tmz_date.tm_mday = file_time_parts.day_of_month; + zip_info.tmz_date.tm_hour = file_time_parts.hour; + zip_info.tmz_date.tm_min = file_time_parts.minute; + zip_info.tmz_date.tm_sec = file_time_parts.second; + } + + return zip_info; +} +} // namespace + +namespace zip { +namespace internal { + +unzFile OpenForUnzipping(const std::string& file_name_utf8) { + zlib_filefunc_def* zip_func_ptrs = NULL; +#if defined(OS_WIN) + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = ZipOpenFunc; + zip_func_ptrs = &zip_funcs; +#endif + return unzOpen2(file_name_utf8.c_str(), zip_func_ptrs); +} + +#if defined(OS_POSIX) +unzFile OpenFdForUnzipping(int zip_fd) { + zlib_filefunc_def zip_funcs; + FillFdOpenFileFunc(&zip_funcs, zip_fd); + // Passing dummy "fd" filename to zlib. + return unzOpen2("fd", &zip_funcs); +} +#endif + +#if defined(OS_WIN) +unzFile OpenHandleForUnzipping(HANDLE zip_handle) { + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = HandleOpenFileFunc; + zip_funcs.zclose_file = HandleCloseFileFunc; + zip_funcs.opaque = zip_handle; + return unzOpen2("fd", &zip_funcs); +} +#endif + +// static +unzFile PrepareMemoryForUnzipping(const std::string& data) { + if (data.empty()) + return NULL; + + ZipBuffer* buffer = static_cast(malloc(sizeof(ZipBuffer))); + if (!buffer) + return NULL; + buffer->data = data.data(); + buffer->length = data.length(); + buffer->offset = 0; + + zlib_filefunc_def zip_functions; + zip_functions.zopen_file = OpenZipBuffer; + zip_functions.zread_file = ReadZipBuffer; + zip_functions.zwrite_file = WriteZipBuffer; + zip_functions.ztell_file = GetOffsetOfZipBuffer; + zip_functions.zseek_file = SeekZipBuffer; + zip_functions.zclose_file = CloseZipBuffer; + zip_functions.zerror_file = GetErrorOfZipBuffer; + zip_functions.opaque = static_cast(buffer); + return unzOpen2(NULL, &zip_functions); +} + +zipFile OpenForZipping(const std::string& file_name_utf8, int append_flag) { + zlib_filefunc_def* zip_func_ptrs = NULL; +#if defined(OS_WIN) + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = ZipOpenFunc; + zip_func_ptrs = &zip_funcs; +#endif + return zipOpen2(file_name_utf8.c_str(), + append_flag, + NULL, // global comment + zip_func_ptrs); +} + +#if defined(OS_POSIX) +zipFile OpenFdForZipping(int zip_fd, int append_flag) { + zlib_filefunc_def zip_funcs; + FillFdOpenFileFunc(&zip_funcs, zip_fd); + // Passing dummy "fd" filename to zlib. + return zipOpen2("fd", append_flag, NULL, &zip_funcs); +} +#endif + +bool ZipOpenNewFileInZip(zipFile zip_file, + const std::string& str_path, + base::Time last_modified_time) { + // Section 4.4.4 http://www.pkware.com/documents/casestudies/APPNOTE.TXT + // Setting the Language encoding flag so the file is told to be in utf-8. + const uLong LANGUAGE_ENCODING_FLAG = 0x1 << 11; + + zip_fileinfo file_info = TimeToZipFileInfo(last_modified_time); + if (ZIP_OK != zipOpenNewFileInZip4(zip_file, // file + str_path.c_str(), // filename + &file_info, // zip_fileinfo + NULL, // extrafield_local, + 0u, // size_extrafield_local + NULL, // extrafield_global + 0u, // size_extrafield_global + NULL, // comment + Z_DEFLATED, // method + Z_DEFAULT_COMPRESSION, // level + 0, // raw + -MAX_WBITS, // windowBits + DEF_MEM_LEVEL, // memLevel + Z_DEFAULT_STRATEGY, // strategy + NULL, // password + 0, // crcForCrypting + 0, // versionMadeBy + LANGUAGE_ENCODING_FLAG)) { // flagBase + DLOG(ERROR) << "Could not open zip file entry " << str_path; + return false; + } + return true; +} + +} // namespace internal +} // namespace zip diff --git a/deps/zlib/google/zip_internal.h b/deps/zlib/google/zip_internal.h new file mode 100644 index 00000000000000..49fb902a7408e7 --- /dev/null +++ b/deps/zlib/google/zip_internal.h @@ -0,0 +1,74 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ + +#include + +#include "base/time/time.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include +#endif + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#endif + +namespace base { +class FilePath; +} + +// Utility functions and constants used internally for the zip file +// library in the directory. Don't use them outside of the library. +namespace zip { +namespace internal { + +// Opens the given file name in UTF-8 for unzipping, with some setup for +// Windows. +unzFile OpenForUnzipping(const std::string& file_name_utf8); + +#if defined(OS_POSIX) +// Opens the file referred to by |zip_fd| for unzipping. +unzFile OpenFdForUnzipping(int zip_fd); +#endif + +#if defined(OS_WIN) +// Opens the file referred to by |zip_handle| for unzipping. +unzFile OpenHandleForUnzipping(HANDLE zip_handle); +#endif + +// Creates a custom unzFile object which reads data from the specified string. +// This custom unzFile object overrides the I/O API functions of zlib so it can +// read data from the specified string. +unzFile PrepareMemoryForUnzipping(const std::string& data); + +// Opens the given file name in UTF-8 for zipping, with some setup for +// Windows. |append_flag| will be passed to zipOpen2(). +zipFile OpenForZipping(const std::string& file_name_utf8, int append_flag); + +#if defined(OS_POSIX) +// Opens the file referred to by |zip_fd| for zipping. |append_flag| will be +// passed to zipOpen2(). +zipFile OpenFdForZipping(int zip_fd, int append_flag); +#endif + +// Wrapper around zipOpenNewFileInZip4 which passes most common options. +bool ZipOpenNewFileInZip(zipFile zip_file, + const std::string& str_path, + base::Time last_modified_time); + +const int kZipMaxPath = 256; +const int kZipBufSize = 8192; + +} // namespace internal +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ diff --git a/deps/zlib/google/zip_reader.cc b/deps/zlib/google/zip_reader.cc new file mode 100644 index 00000000000000..8b4bb4aee782bf --- /dev/null +++ b/deps/zlib/google/zip_reader.cc @@ -0,0 +1,502 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_reader.h" + +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/single_thread_task_runner.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip_internal.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#if defined(OS_WIN) +#include "third_party/zlib/contrib/minizip/iowin32.h" +#endif // defined(OS_WIN) +#endif // defined(USE_SYSTEM_MINIZIP) + +namespace zip { + +namespace { + +// StringWriterDelegate -------------------------------------------------------- + +// A writer delegate that writes no more than |max_read_bytes| to a given +// std::string. +class StringWriterDelegate : public WriterDelegate { + public: + StringWriterDelegate(size_t max_read_bytes, std::string* output); + ~StringWriterDelegate() override; + + // WriterDelegate methods: + + // Returns true. + bool PrepareOutput() override; + + // Appends |num_bytes| bytes from |data| to the output string. Returns false + // if |num_bytes| will cause the string to exceed |max_read_bytes|. + bool WriteBytes(const char* data, int num_bytes) override; + + void SetTimeModified(const base::Time& time) override; + + private: + size_t max_read_bytes_; + std::string* output_; + + DISALLOW_COPY_AND_ASSIGN(StringWriterDelegate); +}; + +StringWriterDelegate::StringWriterDelegate(size_t max_read_bytes, + std::string* output) + : max_read_bytes_(max_read_bytes), + output_(output) { +} + +StringWriterDelegate::~StringWriterDelegate() { +} + +bool StringWriterDelegate::PrepareOutput() { + return true; +} + +bool StringWriterDelegate::WriteBytes(const char* data, int num_bytes) { + if (output_->size() + num_bytes > max_read_bytes_) + return false; + output_->append(data, num_bytes); + return true; +} + +void StringWriterDelegate::SetTimeModified(const base::Time& time) { + // Do nothing. +} + +} // namespace + +// TODO(satorux): The implementation assumes that file names in zip files +// are encoded in UTF-8. This is true for zip files created by Zip() +// function in zip.h, but not true for user-supplied random zip files. +ZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip, + const unz_file_info& raw_file_info) + : file_path_(base::FilePath::FromUTF8Unsafe(file_name_in_zip)), + is_directory_(false), + is_unsafe_(false), + is_encrypted_(false) { + original_size_ = raw_file_info.uncompressed_size; + + // Directory entries in zip files end with "/". + is_directory_ = base::EndsWith(file_name_in_zip, "/", + base::CompareCase::INSENSITIVE_ASCII); + + // Check the file name here for directory traversal issues. + is_unsafe_ = file_path_.ReferencesParent(); + + // We also consider that the file name is unsafe, if it's invalid UTF-8. + base::string16 file_name_utf16; + if (!base::UTF8ToUTF16(file_name_in_zip.data(), file_name_in_zip.size(), + &file_name_utf16)) { + is_unsafe_ = true; + } + + // We also consider that the file name is unsafe, if it's absolute. + // On Windows, IsAbsolute() returns false for paths starting with "/". + if (file_path_.IsAbsolute() || + base::StartsWith(file_name_in_zip, "/", + base::CompareCase::INSENSITIVE_ASCII)) + is_unsafe_ = true; + + // Whether the file is encrypted is bit 0 of the flag. + is_encrypted_ = raw_file_info.flag & 1; + + // Construct the last modified time. The timezone info is not present in + // zip files, so we construct the time as local time. + base::Time::Exploded exploded_time = {}; // Zero-clear. + exploded_time.year = raw_file_info.tmu_date.tm_year; + // The month in zip file is 0-based, whereas ours is 1-based. + exploded_time.month = raw_file_info.tmu_date.tm_mon + 1; + exploded_time.day_of_month = raw_file_info.tmu_date.tm_mday; + exploded_time.hour = raw_file_info.tmu_date.tm_hour; + exploded_time.minute = raw_file_info.tmu_date.tm_min; + exploded_time.second = raw_file_info.tmu_date.tm_sec; + exploded_time.millisecond = 0; + + if (!base::Time::FromLocalExploded(exploded_time, &last_modified_)) + last_modified_ = base::Time::UnixEpoch(); +} + +ZipReader::ZipReader() { + Reset(); +} + +ZipReader::~ZipReader() { + Close(); +} + +bool ZipReader::Open(const base::FilePath& zip_file_path) { + DCHECK(!zip_file_); + + // Use of "Unsafe" function does not look good, but there is no way to do + // this safely on Linux. See file_util.h for details. + zip_file_ = internal::OpenForUnzipping(zip_file_path.AsUTF8Unsafe()); + if (!zip_file_) { + return false; + } + + return OpenInternal(); +} + +bool ZipReader::OpenFromPlatformFile(base::PlatformFile zip_fd) { + DCHECK(!zip_file_); + +#if defined(OS_POSIX) + zip_file_ = internal::OpenFdForUnzipping(zip_fd); +#elif defined(OS_WIN) + zip_file_ = internal::OpenHandleForUnzipping(zip_fd); +#endif + if (!zip_file_) { + return false; + } + + return OpenInternal(); +} + +bool ZipReader::OpenFromString(const std::string& data) { + zip_file_ = internal::PrepareMemoryForUnzipping(data); + if (!zip_file_) + return false; + return OpenInternal(); +} + +void ZipReader::Close() { + if (zip_file_) { + unzClose(zip_file_); + } + Reset(); +} + +bool ZipReader::HasMore() { + return !reached_end_; +} + +bool ZipReader::AdvanceToNextEntry() { + DCHECK(zip_file_); + + // Should not go further if we already reached the end. + if (reached_end_) + return false; + + unz_file_pos position = {}; + if (unzGetFilePos(zip_file_, &position) != UNZ_OK) + return false; + const int current_entry_index = position.num_of_file; + // If we are currently at the last entry, then the next position is the + // end of the zip file, so mark that we reached the end. + if (current_entry_index + 1 == num_entries_) { + reached_end_ = true; + } else { + DCHECK_LT(current_entry_index + 1, num_entries_); + if (unzGoToNextFile(zip_file_) != UNZ_OK) { + return false; + } + } + current_entry_info_.reset(); + return true; +} + +bool ZipReader::OpenCurrentEntryInZip() { + DCHECK(zip_file_); + + unz_file_info raw_file_info = {}; + char raw_file_name_in_zip[internal::kZipMaxPath] = {}; + const int result = unzGetCurrentFileInfo(zip_file_, + &raw_file_info, + raw_file_name_in_zip, + sizeof(raw_file_name_in_zip) - 1, + NULL, // extraField. + 0, // extraFieldBufferSize. + NULL, // szComment. + 0); // commentBufferSize. + if (result != UNZ_OK) + return false; + if (raw_file_name_in_zip[0] == '\0') + return false; + current_entry_info_.reset( + new EntryInfo(raw_file_name_in_zip, raw_file_info)); + return true; +} + +bool ZipReader::ExtractCurrentEntry(WriterDelegate* delegate, + uint64_t num_bytes_to_extract) const { + DCHECK(zip_file_); + + const int open_result = unzOpenCurrentFile(zip_file_); + if (open_result != UNZ_OK) + return false; + + if (!delegate->PrepareOutput()) + return false; + std::unique_ptr buf(new char[internal::kZipBufSize]); + + uint64_t remaining_capacity = num_bytes_to_extract; + bool entire_file_extracted = false; + + while (remaining_capacity > 0) { + const int num_bytes_read = + unzReadCurrentFile(zip_file_, buf.get(), internal::kZipBufSize); + + if (num_bytes_read == 0) { + entire_file_extracted = true; + break; + } else if (num_bytes_read < 0) { + // If num_bytes_read < 0, then it's a specific UNZ_* error code. + break; + } else if (num_bytes_read > 0) { + uint64_t num_bytes_to_write = std::min( + remaining_capacity, base::checked_cast(num_bytes_read)); + if (!delegate->WriteBytes(buf.get(), num_bytes_to_write)) + break; + if (remaining_capacity == base::checked_cast(num_bytes_read)) { + // Ensures function returns true if the entire file has been read. + entire_file_extracted = + (unzReadCurrentFile(zip_file_, buf.get(), 1) == 0); + } + CHECK_GE(remaining_capacity, num_bytes_to_write); + remaining_capacity -= num_bytes_to_write; + } + } + + unzCloseCurrentFile(zip_file_); + + if (entire_file_extracted && + current_entry_info()->last_modified() != base::Time::UnixEpoch()) { + delegate->SetTimeModified(current_entry_info()->last_modified()); + } + + return entire_file_extracted; +} + +void ZipReader::ExtractCurrentEntryToFilePathAsync( + const base::FilePath& output_file_path, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback) { + DCHECK(zip_file_); + DCHECK(current_entry_info_.get()); + + // If this is a directory, just create it and return. + if (current_entry_info()->is_directory()) { + if (base::CreateDirectory(output_file_path)) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, std::move(success_callback)); + } else { + DVLOG(1) << "Unzip failed: unable to create directory."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, std::move(failure_callback)); + } + return; + } + + if (unzOpenCurrentFile(zip_file_) != UNZ_OK) { + DVLOG(1) << "Unzip failed: unable to open current zip entry."; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + base::FilePath output_dir_path = output_file_path.DirName(); + if (!base::CreateDirectory(output_dir_path)) { + DVLOG(1) << "Unzip failed: unable to create containing directory."; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + const int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; + base::File output_file(output_file_path, flags); + + if (!output_file.IsValid()) { + DVLOG(1) << "Unzip failed: unable to create platform file at " + << output_file_path.value(); + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(), + Passed(std::move(output_file)), + std::move(success_callback), std::move(failure_callback), + progress_callback, 0 /* initial offset */)); +} + +bool ZipReader::ExtractCurrentEntryToString(uint64_t max_read_bytes, + std::string* output) const { + DCHECK(output); + DCHECK(zip_file_); + + if (max_read_bytes == 0) { + output->clear(); + return true; + } + + if (current_entry_info()->is_directory()) { + output->clear(); + return true; + } + + // The original_size() is the best hint for the real size, so it saves + // doing reallocations for the common case when the uncompressed size is + // correct. However, we need to assume that the uncompressed size could be + // incorrect therefore this function needs to read as much data as possible. + std::string contents; + contents.reserve( + static_cast(std::min(base::checked_cast(max_read_bytes), + current_entry_info()->original_size()))); + + StringWriterDelegate writer(max_read_bytes, &contents); + if (!ExtractCurrentEntry(&writer, max_read_bytes)) { + if (contents.length() < max_read_bytes) { + // There was an error in extracting entry. If ExtractCurrentEntry() + // returns false, the entire file was not read - in which case + // contents.length() should equal |max_read_bytes| unless an error + // occurred which caused extraction to be aborted. + output->clear(); + } else { + // |num_bytes| is less than the length of current entry. + output->swap(contents); + } + return false; + } + output->swap(contents); + return true; +} + +bool ZipReader::OpenInternal() { + DCHECK(zip_file_); + + unz_global_info zip_info = {}; // Zero-clear. + if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) { + return false; + } + num_entries_ = zip_info.number_entry; + if (num_entries_ < 0) + return false; + + // We are already at the end if the zip file is empty. + reached_end_ = (num_entries_ == 0); + return true; +} + +void ZipReader::Reset() { + zip_file_ = NULL; + num_entries_ = 0; + reached_end_ = false; + current_entry_info_.reset(); +} + +void ZipReader::ExtractChunk(base::File output_file, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback, + const int64_t offset) { + char buffer[internal::kZipBufSize]; + + const int num_bytes_read = unzReadCurrentFile(zip_file_, + buffer, + internal::kZipBufSize); + + if (num_bytes_read == 0) { + unzCloseCurrentFile(zip_file_); + std::move(success_callback).Run(); + } else if (num_bytes_read < 0) { + DVLOG(1) << "Unzip failed: error while reading zipfile " + << "(" << num_bytes_read << ")"; + std::move(failure_callback).Run(); + } else { + if (num_bytes_read != output_file.Write(offset, buffer, num_bytes_read)) { + DVLOG(1) << "Unzip failed: unable to write all bytes to target."; + std::move(failure_callback).Run(); + return; + } + + int64_t current_progress = offset + num_bytes_read; + + progress_callback.Run(current_progress); + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(), + Passed(std::move(output_file)), + std::move(success_callback), std::move(failure_callback), + progress_callback, current_progress)); + } +} + +// FileWriterDelegate ---------------------------------------------------------- + +FileWriterDelegate::FileWriterDelegate(base::File* file) : file_(file) {} + +FileWriterDelegate::FileWriterDelegate(std::unique_ptr file) + : file_(file.get()), owned_file_(std::move(file)) {} + +FileWriterDelegate::~FileWriterDelegate() { + if (!file_->SetLength(file_length_)) { + DVPLOG(1) << "Failed updating length of written file"; + } +} + +bool FileWriterDelegate::PrepareOutput() { + return file_->Seek(base::File::FROM_BEGIN, 0) >= 0; +} + +bool FileWriterDelegate::WriteBytes(const char* data, int num_bytes) { + int bytes_written = file_->WriteAtCurrentPos(data, num_bytes); + if (bytes_written > 0) + file_length_ += bytes_written; + return bytes_written == num_bytes; +} + +void FileWriterDelegate::SetTimeModified(const base::Time& time) { + file_->SetTimes(base::Time::Now(), time); +} + +// FilePathWriterDelegate ------------------------------------------------------ + +FilePathWriterDelegate::FilePathWriterDelegate( + const base::FilePath& output_file_path) + : output_file_path_(output_file_path) {} + +FilePathWriterDelegate::~FilePathWriterDelegate() {} + +bool FilePathWriterDelegate::PrepareOutput() { + // We can't rely on parent directory entries being specified in the + // zip, so we make sure they are created. + if (!base::CreateDirectory(output_file_path_.DirName())) + return false; + + file_.Initialize(output_file_path_, + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + return file_.IsValid(); +} + +bool FilePathWriterDelegate::WriteBytes(const char* data, int num_bytes) { + return num_bytes == file_.WriteAtCurrentPos(data, num_bytes); +} + +void FilePathWriterDelegate::SetTimeModified(const base::Time& time) { + file_.Close(); + base::TouchFile(output_file_path_, base::Time::Now(), time); +} + +} // namespace zip diff --git a/deps/zlib/google/zip_reader.h b/deps/zlib/google/zip_reader.h new file mode 100644 index 00000000000000..d442d428591e50 --- /dev/null +++ b/deps/zlib/google/zip_reader.h @@ -0,0 +1,301 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ + +#include +#include + +#include +#include + +#include "base/callback.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#endif + +namespace zip { + +// A delegate interface used to stream out an entry; see +// ZipReader::ExtractCurrentEntry. +class WriterDelegate { + public: + virtual ~WriterDelegate() {} + + // Invoked once before any data is streamed out to pave the way (e.g., to open + // the output file). Return false on failure to cancel extraction. + virtual bool PrepareOutput() = 0; + + // Invoked to write the next chunk of data. Return false on failure to cancel + // extraction. + virtual bool WriteBytes(const char* data, int num_bytes) = 0; + + // Sets the last-modified time of the data. + virtual void SetTimeModified(const base::Time& time) = 0; +}; + +// This class is used for reading zip files. A typical use case of this +// class is to scan entries in a zip file and extract them. The code will +// look like: +// +// ZipReader reader; +// reader.Open(zip_file_path); +// while (reader.HasMore()) { +// reader.OpenCurrentEntryInZip(); +// const base::FilePath& entry_path = +// reader.current_entry_info()->file_path(); +// auto writer = CreateFilePathWriterDelegate(extract_dir, entry_path); +// reader.ExtractCurrentEntry(writer, std::numeric_limits::max()); +// reader.AdvanceToNextEntry(); +// } +// +// For simplicity, error checking is omitted in the example code above. The +// production code should check return values from all of these functions. +// +class ZipReader { + public: + // A callback that is called when the operation is successful. + using SuccessCallback = base::OnceClosure; + // A callback that is called when the operation fails. + using FailureCallback = base::OnceClosure; + // A callback that is called periodically during the operation with the number + // of bytes that have been processed so far. + using ProgressCallback = base::RepeatingCallback; + + // This class represents information of an entry (file or directory) in + // a zip file. + class EntryInfo { + public: + EntryInfo(const std::string& filename_in_zip, + const unz_file_info& raw_file_info); + + // Returns the file path. The path is usually relative like + // "foo/bar.txt", but if it's absolute, is_unsafe() returns true. + const base::FilePath& file_path() const { return file_path_; } + + // Returns the size of the original file (i.e. after uncompressed). + // Returns 0 if the entry is a directory. + // Note: this value should not be trusted, because it is stored as metadata + // in the zip archive and can be different from the real uncompressed size. + int64_t original_size() const { return original_size_; } + + // Returns the last modified time. If the time stored in the zip file was + // not valid, the unix epoch will be returned. + // + // The time stored in the zip archive uses the MS-DOS date and time format. + // http://msdn.microsoft.com/en-us/library/ms724247(v=vs.85).aspx + // As such the following limitations apply: + // * only years from 1980 to 2107 can be represented. + // * the time stamp has a 2 second resolution. + // * there's no timezone information, so the time is interpreted as local. + base::Time last_modified() const { return last_modified_; } + + // Returns true if the entry is a directory. + bool is_directory() const { return is_directory_; } + + // Returns true if the entry is unsafe, like having ".." or invalid + // UTF-8 characters in its file name, or the file path is absolute. + bool is_unsafe() const { return is_unsafe_; } + + // Returns true if the entry is encrypted. + bool is_encrypted() const { return is_encrypted_; } + + private: + const base::FilePath file_path_; + int64_t original_size_; + base::Time last_modified_; + bool is_directory_; + bool is_unsafe_; + bool is_encrypted_; + DISALLOW_COPY_AND_ASSIGN(EntryInfo); + }; + + ZipReader(); + ~ZipReader(); + + // Opens the zip file specified by |zip_file_path|. Returns true on + // success. + bool Open(const base::FilePath& zip_file_path); + + // Opens the zip file referred to by the platform file |zip_fd|, without + // taking ownership of |zip_fd|. Returns true on success. + bool OpenFromPlatformFile(base::PlatformFile zip_fd); + + // Opens the zip data stored in |data|. This class uses a weak reference to + // the given sring while extracting files, i.e. the caller should keep the + // string until it finishes extracting files. + bool OpenFromString(const std::string& data); + + // Closes the currently opened zip file. This function is called in the + // destructor of the class, so you usually don't need to call this. + void Close(); + + // Returns true if there is at least one entry to read. This function is + // used to scan entries with AdvanceToNextEntry(), like: + // + // while (reader.HasMore()) { + // // Do something with the current file here. + // reader.AdvanceToNextEntry(); + // } + bool HasMore(); + + // Advances the next entry. Returns true on success. + bool AdvanceToNextEntry(); + + // Opens the current entry in the zip file. On success, returns true and + // updates the the current entry state (i.e. current_entry_info() is + // updated). This function should be called before operations over the + // current entry like ExtractCurrentEntryToFile(). + // + // Note that there is no CloseCurrentEntryInZip(). The the current entry + // state is reset automatically as needed. + bool OpenCurrentEntryInZip(); + + // Extracts |num_bytes_to_extract| bytes of the current entry to |delegate|, + // starting from the beginning of the entry. Return value specifies whether + // the entire file was extracted. + bool ExtractCurrentEntry(WriterDelegate* delegate, + uint64_t num_bytes_to_extract) const; + + // Asynchronously extracts the current entry to the given output file path. + // If the current entry is a directory it just creates the directory + // synchronously instead. OpenCurrentEntryInZip() must be called beforehand. + // success_callback will be called on success and failure_callback will be + // called on failure. progress_callback will be called at least once. + // Callbacks will be posted to the current MessageLoop in-order. + void ExtractCurrentEntryToFilePathAsync( + const base::FilePath& output_file_path, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback); + + // Extracts the current entry into memory. If the current entry is a + // directory, the |output| parameter is set to the empty string. If the + // current entry is a file, the |output| parameter is filled with its + // contents. OpenCurrentEntryInZip() must be called beforehand. Note: the + // |output| parameter can be filled with a big amount of data, avoid passing + // it around by value, but by reference or pointer. Note: the value returned + // by EntryInfo::original_size() cannot be trusted, so the real size of the + // uncompressed contents can be different. |max_read_bytes| limits the ammount + // of memory used to carry the entry. Returns true if the entire content is + // read. If the entry is bigger than |max_read_bytes|, returns false and + // |output| is filled with |max_read_bytes| of data. If an error occurs, + // returns false, and |output| is set to the empty string. + bool ExtractCurrentEntryToString(uint64_t max_read_bytes, + std::string* output) const; + + // Returns the current entry info. Returns NULL if the current entry is + // not yet opened. OpenCurrentEntryInZip() must be called beforehand. + EntryInfo* current_entry_info() const { + return current_entry_info_.get(); + } + + // Returns the number of entries in the zip file. + // Open() must be called beforehand. + int num_entries() const { return num_entries_; } + + private: + // Common code used both in Open and OpenFromFd. + bool OpenInternal(); + + // Resets the internal state. + void Reset(); + + // Extracts a chunk of the file to the target. Will post a task for the next + // chunk and success/failure/progress callbacks as necessary. + void ExtractChunk(base::File target_file, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback, + const int64_t offset); + + unzFile zip_file_; + int num_entries_; + bool reached_end_; + std::unique_ptr current_entry_info_; + + base::WeakPtrFactory weak_ptr_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(ZipReader); +}; + +// A writer delegate that writes to a given File. +class FileWriterDelegate : public WriterDelegate { + public: + // Constructs a FileWriterDelegate that manipulates |file|. The delegate will + // not own |file|, therefore the caller must guarantee |file| will outlive the + // delegate. + explicit FileWriterDelegate(base::File* file); + + // Constructs a FileWriterDelegate that takes ownership of |file|. + explicit FileWriterDelegate(std::unique_ptr file); + + // Truncates the file to the number of bytes written. + ~FileWriterDelegate() override; + + // WriterDelegate methods: + + // Seeks to the beginning of the file, returning false if the seek fails. + bool PrepareOutput() override; + + // Writes |num_bytes| bytes of |data| to the file, returning false on error or + // if not all bytes could be written. + bool WriteBytes(const char* data, int num_bytes) override; + + // Sets the last-modified time of the data. + void SetTimeModified(const base::Time& time) override; + + // Return the actual size of the file. + int64_t file_length() { return file_length_; } + + private: + // The file the delegate modifies. + base::File* file_; + + // The delegate can optionally own the file it modifies, in which case + // owned_file_ is set and file_ is an alias for owned_file_. + std::unique_ptr owned_file_; + + int64_t file_length_ = 0; + + DISALLOW_COPY_AND_ASSIGN(FileWriterDelegate); +}; + +// A writer delegate that writes a file at a given path. +class FilePathWriterDelegate : public WriterDelegate { + public: + explicit FilePathWriterDelegate(const base::FilePath& output_file_path); + ~FilePathWriterDelegate() override; + + // WriterDelegate methods: + + // Creates the output file and any necessary intermediate directories. + bool PrepareOutput() override; + + // Writes |num_bytes| bytes of |data| to the file, returning false if not all + // bytes could be written. + bool WriteBytes(const char* data, int num_bytes) override; + + // Sets the last-modified time of the data. + void SetTimeModified(const base::Time& time) override; + + private: + base::FilePath output_file_path_; + base::File file_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWriterDelegate); +}; + +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ diff --git a/deps/zlib/google/zip_reader_unittest.cc b/deps/zlib/google/zip_reader_unittest.cc new file mode 100644 index 00000000000000..87190c7e0dee76 --- /dev/null +++ b/deps/zlib/google/zip_reader_unittest.cc @@ -0,0 +1,672 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_reader.h" + +#include +#include +#include + +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/hash/md5.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/run_loop.h" +#include "base/stl_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/task_environment.h" +#include "base/time/time.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" +#include "third_party/zlib/google/zip_internal.h" + +using ::testing::Return; +using ::testing::_; + +namespace { + +const static std::string kQuuxExpectedMD5 = "d1ae4ac8a17a0e09317113ab284b57a6"; + +class FileWrapper { + public: + typedef enum { + READ_ONLY, + READ_WRITE + } AccessMode; + + FileWrapper(const base::FilePath& path, AccessMode mode) { + int flags = base::File::FLAG_READ; + if (mode == READ_ONLY) + flags |= base::File::FLAG_OPEN; + else + flags |= base::File::FLAG_WRITE | base::File::FLAG_CREATE_ALWAYS; + + file_.Initialize(path, flags); + } + + ~FileWrapper() {} + + base::PlatformFile platform_file() { return file_.GetPlatformFile(); } + + base::File* file() { return &file_; } + + private: + base::File file_; +}; + +// A mock that provides methods that can be used as callbacks in asynchronous +// unzip functions. Tracks the number of calls and number of bytes reported. +// Assumes that progress callbacks will be executed in-order. +class MockUnzipListener : public base::SupportsWeakPtr { + public: + MockUnzipListener() + : success_calls_(0), + failure_calls_(0), + progress_calls_(0), + current_progress_(0) { + } + + // Success callback for async functions. + void OnUnzipSuccess() { + success_calls_++; + } + + // Failure callback for async functions. + void OnUnzipFailure() { + failure_calls_++; + } + + // Progress callback for async functions. + void OnUnzipProgress(int64_t progress) { + DCHECK(progress > current_progress_); + progress_calls_++; + current_progress_ = progress; + } + + int success_calls() { return success_calls_; } + int failure_calls() { return failure_calls_; } + int progress_calls() { return progress_calls_; } + int current_progress() { return current_progress_; } + + private: + int success_calls_; + int failure_calls_; + int progress_calls_; + + int64_t current_progress_; +}; + +class MockWriterDelegate : public zip::WriterDelegate { + public: + MOCK_METHOD0(PrepareOutput, bool()); + MOCK_METHOD2(WriteBytes, bool(const char*, int)); + MOCK_METHOD1(SetTimeModified, void(const base::Time&)); +}; + +bool ExtractCurrentEntryToFilePath(zip::ZipReader* reader, + base::FilePath path) { + zip::FilePathWriterDelegate writer(path); + return reader->ExtractCurrentEntry(&writer, + std::numeric_limits::max()); +} + +bool LocateAndOpenEntry(zip::ZipReader* reader, + const base::FilePath& path_in_zip) { + // The underlying library can do O(1) access, but ZipReader does not expose + // that. O(N) access is acceptable for these tests. + while (reader->HasMore()) { + if (!reader->OpenCurrentEntryInZip()) + return false; + if (reader->current_entry_info()->file_path() == path_in_zip) + return true; + reader->AdvanceToNextEntry(); + } + return false; +} + +} // namespace + +namespace zip { + +// Make the test a PlatformTest to setup autorelease pools properly on Mac. +class ZipReaderTest : public PlatformTest { + protected: + virtual void SetUp() { + PlatformTest::SetUp(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + test_dir_ = temp_dir_.GetPath(); + + ASSERT_TRUE(GetTestDataDirectory(&test_data_dir_)); + + test_zip_file_ = test_data_dir_.AppendASCII("test.zip"); + encrypted_zip_file_ = test_data_dir_.AppendASCII("test_encrypted.zip"); + evil_zip_file_ = test_data_dir_.AppendASCII("evil.zip"); + evil_via_invalid_utf8_zip_file_ = test_data_dir_.AppendASCII( + "evil_via_invalid_utf8.zip"); + evil_via_absolute_file_name_zip_file_ = test_data_dir_.AppendASCII( + "evil_via_absolute_file_name.zip"); + + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo/"))); + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo/bar/"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/baz.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/quux.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar.txt"))); + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/.hidden"))); + } + + virtual void TearDown() { + PlatformTest::TearDown(); + } + + bool GetTestDataDirectory(base::FilePath* path) { + bool success = base::PathService::Get(base::DIR_SOURCE_ROOT, path); + EXPECT_TRUE(success); + if (!success) + return false; + *path = path->AppendASCII("third_party"); + *path = path->AppendASCII("zlib"); + *path = path->AppendASCII("google"); + *path = path->AppendASCII("test"); + *path = path->AppendASCII("data"); + return true; + } + + bool CompareFileAndMD5(const base::FilePath& path, + const std::string expected_md5) { + // Read the output file and compute the MD5. + std::string output; + if (!base::ReadFileToString(path, &output)) + return false; + const std::string md5 = base::MD5String(output); + return expected_md5 == md5; + } + + // The path to temporary directory used to contain the test operations. + base::FilePath test_dir_; + // The path to the test data directory where test.zip etc. are located. + base::FilePath test_data_dir_; + // The path to test.zip in the test data directory. + base::FilePath test_zip_file_; + // The path to test_encrypted.zip in the test data directory. + base::FilePath encrypted_zip_file_; + // The path to evil.zip in the test data directory. + base::FilePath evil_zip_file_; + // The path to evil_via_invalid_utf8.zip in the test data directory. + base::FilePath evil_via_invalid_utf8_zip_file_; + // The path to evil_via_absolute_file_name.zip in the test data directory. + base::FilePath evil_via_absolute_file_name_zip_file_; + std::set test_zip_contents_; + + base::ScopedTempDir temp_dir_; + + base::test::TaskEnvironment task_environment_; +}; + +TEST_F(ZipReaderTest, Open_ValidZipFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); +} + +TEST_F(ZipReaderTest, Open_ValidZipPlatformFile) { + ZipReader reader; + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); +} + +TEST_F(ZipReaderTest, Open_NonExistentFile) { + ZipReader reader; + ASSERT_FALSE(reader.Open(test_data_dir_.AppendASCII("nonexistent.zip"))); +} + +TEST_F(ZipReaderTest, Open_ExistentButNonZipFile) { + ZipReader reader; + ASSERT_FALSE(reader.Open(test_data_dir_.AppendASCII("create_test_zip.sh"))); +} + +// Iterate through the contents in the test zip file, and compare that the +// contents collected from the zip reader matches the expected contents. +TEST_F(ZipReaderTest, Iteration) { + std::set actual_contents; + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + while (reader.HasMore()) { + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + actual_contents.insert(reader.current_entry_info()->file_path()); + ASSERT_TRUE(reader.AdvanceToNextEntry()); + } + EXPECT_FALSE(reader.AdvanceToNextEntry()); // Shouldn't go further. + EXPECT_EQ(test_zip_contents_.size(), + static_cast(reader.num_entries())); + EXPECT_EQ(test_zip_contents_.size(), actual_contents.size()); + EXPECT_EQ(test_zip_contents_, actual_contents); +} + +// Open the test zip file from a file descriptor, iterate through its contents, +// and compare that they match the expected contents. +TEST_F(ZipReaderTest, PlatformFileIteration) { + std::set actual_contents; + ZipReader reader; + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); + while (reader.HasMore()) { + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + actual_contents.insert(reader.current_entry_info()->file_path()); + ASSERT_TRUE(reader.AdvanceToNextEntry()); + } + EXPECT_FALSE(reader.AdvanceToNextEntry()); // Shouldn't go further. + EXPECT_EQ(test_zip_contents_.size(), + static_cast(reader.num_entries())); + EXPECT_EQ(test_zip_contents_.size(), actual_contents.size()); + EXPECT_EQ(test_zip_contents_, actual_contents); +} + +TEST_F(ZipReaderTest, current_entry_info_RegularFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + EXPECT_EQ(target_path, current_entry_info->file_path()); + EXPECT_EQ(13527, current_entry_info->original_size()); + + // The expected time stamp: 2009-05-29 06:22:20 + base::Time::Exploded exploded = {}; // Zero-clear. + current_entry_info->last_modified().LocalExplode(&exploded); + EXPECT_EQ(2009, exploded.year); + EXPECT_EQ(5, exploded.month); + EXPECT_EQ(29, exploded.day_of_month); + EXPECT_EQ(6, exploded.hour); + EXPECT_EQ(22, exploded.minute); + EXPECT_EQ(20, exploded.second); + EXPECT_EQ(0, exploded.millisecond); + + EXPECT_FALSE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_DotDotFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL( + "../levilevilevilevilevilevilevilevilevilevilevilevil")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + EXPECT_EQ(target_path, current_entry_info->file_path()); + + // This file is unsafe because of ".." in the file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_InvalidUTF8File) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_via_invalid_utf8_zip_file_)); + // The evil file is the 2nd file in the zip file. + // We cannot locate by the file name ".\x80.\\evil.txt", + // as FilePath may internally convert the string. + ASSERT_TRUE(reader.AdvanceToNextEntry()); + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + // This file is unsafe because of invalid UTF-8 in the file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_AbsoluteFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_via_absolute_file_name_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("/evil.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + EXPECT_EQ(target_path, current_entry_info->file_path()); + + // This file is unsafe because of the absolute file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_Directory) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + EXPECT_EQ(base::FilePath(FILE_PATH_LITERAL("foo/bar/")), + current_entry_info->file_path()); + // The directory size should be zero. + EXPECT_EQ(0, current_entry_info->original_size()); + + // The expected time stamp: 2009-05-31 15:49:52 + base::Time::Exploded exploded = {}; // Zero-clear. + current_entry_info->last_modified().LocalExplode(&exploded); + EXPECT_EQ(2009, exploded.year); + EXPECT_EQ(5, exploded.month); + EXPECT_EQ(31, exploded.day_of_month); + EXPECT_EQ(15, exploded.hour); + EXPECT_EQ(49, exploded.minute); + EXPECT_EQ(52, exploded.second); + EXPECT_EQ(0, exploded.millisecond); + + EXPECT_FALSE(current_entry_info->is_unsafe()); + EXPECT_TRUE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_EncryptedFile) { + ZipReader reader; + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + + ASSERT_TRUE(reader.Open(encrypted_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + EXPECT_TRUE(reader.current_entry_info()->is_encrypted()); + reader.Close(); + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + EXPECT_FALSE(reader.current_entry_info()->is_encrypted()); +} + +// Verifies that the ZipReader class can extract a file from a zip archive +// stored in memory. This test opens a zip archive in a std::string object, +// extracts its content, and verifies the content is the same as the expected +// text. +TEST_F(ZipReaderTest, OpenFromString) { + // A zip archive consisting of one file "test.txt", which is a 16-byte text + // file that contains "This is a test.\n". + const char kTestData[] = + "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\xa4\x66\x24\x41\x13\xe8" + "\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00\x1c\x00\x74\x65" + "\x73\x74\x2e\x74\x78\x74\x55\x54\x09\x00\x03\x34\x89\x45\x50\x34" + "\x89\x45\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13" + "\x00\x00\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74" + "\x2e\x0a\x50\x4b\x01\x02\x1e\x03\x0a\x00\x00\x00\x00\x00\xa4\x66" + "\x24\x41\x13\xe8\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00" + "\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xa4\x81\x00\x00\x00\x00" + "\x74\x65\x73\x74\x2e\x74\x78\x74\x55\x54\x05\x00\x03\x34\x89\x45" + "\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13\x00\x00" + "\x50\x4b\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00\x4e\x00\x00\x00" + "\x52\x00\x00\x00\x00\x00"; + std::string data(kTestData, base::size(kTestData)); + ZipReader reader; + ASSERT_TRUE(reader.OpenFromString(data)); + base::FilePath target_path(FILE_PATH_LITERAL("test.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_TRUE(ExtractCurrentEntryToFilePath(&reader, + test_dir_.AppendASCII("test.txt"))); + + std::string actual; + ASSERT_TRUE(base::ReadFileToString( + test_dir_.AppendASCII("test.txt"), &actual)); + EXPECT_EQ(std::string("This is a test.\n"), actual); +} + +// Verifies that the asynchronous extraction to a file works. +TEST_F(ZipReaderTest, ExtractToFileAsync_RegularFile) { + MockUnzipListener listener; + + ZipReader reader; + base::FilePath target_file = test_dir_.AppendASCII("quux.txt"); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + reader.ExtractCurrentEntryToFilePathAsync( + target_file, + base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()), + base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()), + base::BindRepeating(&MockUnzipListener::OnUnzipProgress, + listener.AsWeakPtr())); + + EXPECT_EQ(0, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_EQ(0, listener.progress_calls()); + + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(1, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_LE(1, listener.progress_calls()); + + std::string output; + ASSERT_TRUE(base::ReadFileToString(test_dir_.AppendASCII("quux.txt"), + &output)); + const std::string md5 = base::MD5String(output); + EXPECT_EQ(kQuuxExpectedMD5, md5); + + int64_t file_size = 0; + ASSERT_TRUE(base::GetFileSize(target_file, &file_size)); + + EXPECT_EQ(file_size, listener.current_progress()); +} + +// Verifies that the asynchronous extraction to a file works. +TEST_F(ZipReaderTest, ExtractToFileAsync_Directory) { + MockUnzipListener listener; + + ZipReader reader; + base::FilePath target_file = test_dir_.AppendASCII("foo"); + base::FilePath target_path(FILE_PATH_LITERAL("foo/")); + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + reader.ExtractCurrentEntryToFilePathAsync( + target_file, + base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()), + base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()), + base::BindRepeating(&MockUnzipListener::OnUnzipProgress, + listener.AsWeakPtr())); + + EXPECT_EQ(0, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_EQ(0, listener.progress_calls()); + + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(1, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_GE(0, listener.progress_calls()); + + ASSERT_TRUE(base::DirectoryExists(target_file)); +} + +TEST_F(ZipReaderTest, ExtractCurrentEntryToString) { + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, being the contents of each file a + // substring of "0123456" starting at '0'. + base::FilePath test_zip_file = + test_data_dir_.AppendASCII("test_mismatch_size.zip"); + + ZipReader reader; + std::string contents; + ASSERT_TRUE(reader.Open(test_zip_file)); + + for (size_t i = 0; i < 8; i++) { + SCOPED_TRACE(base::StringPrintf("Processing %d.txt", static_cast(i))); + + base::FilePath file_name = base::FilePath::FromUTF8Unsafe( + base::StringPrintf("%d.txt", static_cast(i))); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name)); + + if (i > 1) { + // Off by one byte read limit: must fail. + EXPECT_FALSE(reader.ExtractCurrentEntryToString(i - 1, &contents)); + } + + if (i > 0) { + // Exact byte read limit: must pass. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(i, &contents)); + EXPECT_EQ(base::StringPiece("0123456", i).as_string(), contents); + } + + // More than necessary byte read limit: must pass. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(16, &contents)); + EXPECT_EQ(base::StringPiece("0123456", i).as_string(), contents); + } + reader.Close(); +} + +TEST_F(ZipReaderTest, ExtractPartOfCurrentEntry) { + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, being the contents of each file a + // substring of "0123456" starting at '0'. + base::FilePath test_zip_file = + test_data_dir_.AppendASCII("test_mismatch_size.zip"); + + ZipReader reader; + std::string contents; + ASSERT_TRUE(reader.Open(test_zip_file)); + + base::FilePath file_name0 = base::FilePath::FromUTF8Unsafe("0.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name0)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents)); + EXPECT_EQ("", contents); + + base::FilePath file_name1 = base::FilePath::FromUTF8Unsafe("1.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name1)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents)); + EXPECT_EQ("0", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(2, &contents)); + EXPECT_EQ("0", contents); + + base::FilePath file_name4 = base::FilePath::FromUTF8Unsafe("4.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name4)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_FALSE(reader.ExtractCurrentEntryToString(2, &contents)); + EXPECT_EQ("01", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(4, &contents)); + EXPECT_EQ("0123", contents); + // Checks that entire file is extracted and function returns true when + // |max_read_bytes| is larger than file size. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(5, &contents)); + EXPECT_EQ("0123", contents); + + reader.Close(); +} + +// This test exposes http://crbug.com/430959, at least on OS X +TEST_F(ZipReaderTest, DISABLED_LeakDetectionTest) { + for (int i = 0; i < 100000; ++i) { + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ZipReader reader; + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); + } +} + +// Test that when WriterDelegate::PrepareMock returns false, no other methods on +// the delegate are called and the extraction fails. +TEST_F(ZipReaderTest, ExtractCurrentEntryPrepareFailure) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(false)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_FALSE(reader.ExtractCurrentEntry( + &mock_writer, std::numeric_limits::max())); +} + +// Test that when WriterDelegate::WriteBytes returns false, no other methods on +// the delegate are called and the extraction fails. +TEST_F(ZipReaderTest, ExtractCurrentEntryWriteBytesFailure) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(true)); + EXPECT_CALL(mock_writer, WriteBytes(_, _)) + .WillOnce(Return(false)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_FALSE(reader.ExtractCurrentEntry( + &mock_writer, std::numeric_limits::max())); +} + +// Test that extraction succeeds when the writer delegate reports all is well. +TEST_F(ZipReaderTest, ExtractCurrentEntrySuccess) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(true)); + EXPECT_CALL(mock_writer, WriteBytes(_, _)) + .WillRepeatedly(Return(true)); + EXPECT_CALL(mock_writer, SetTimeModified(_)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_TRUE(reader.ExtractCurrentEntry(&mock_writer, + std::numeric_limits::max())); +} + +class FileWriterDelegateTest : public ::testing::Test { + protected: + void SetUp() override { + ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path_)); + file_.Initialize(temp_file_path_, (base::File::FLAG_CREATE_ALWAYS | + base::File::FLAG_READ | + base::File::FLAG_WRITE | + base::File::FLAG_TEMPORARY | + base::File::FLAG_DELETE_ON_CLOSE)); + ASSERT_TRUE(file_.IsValid()); + } + + // Writes data to the file, leaving the current position at the end of the + // write. + void PopulateFile() { + static const char kSomeData[] = "this sure is some data."; + static const size_t kSomeDataLen = sizeof(kSomeData) - 1; + ASSERT_NE(-1LL, file_.Write(0LL, kSomeData, kSomeDataLen)); + } + + base::FilePath temp_file_path_; + base::File file_; +}; + +TEST_F(FileWriterDelegateTest, WriteToStartAndTruncate) { + // Write stuff and advance. + PopulateFile(); + + // This should rewind, write, then truncate. + static const char kSomeData[] = "short"; + static const int kSomeDataLen = sizeof(kSomeData) - 1; + { + FileWriterDelegate writer(&file_); + ASSERT_TRUE(writer.PrepareOutput()); + ASSERT_TRUE(writer.WriteBytes(kSomeData, kSomeDataLen)); + } + ASSERT_EQ(kSomeDataLen, file_.GetLength()); + char buf[kSomeDataLen] = {}; + ASSERT_EQ(kSomeDataLen, file_.Read(0LL, buf, kSomeDataLen)); + ASSERT_EQ(std::string(kSomeData), std::string(buf, kSomeDataLen)); +} + +} // namespace zip diff --git a/deps/zlib/google/zip_unittest.cc b/deps/zlib/google/zip_unittest.cc new file mode 100644 index 00000000000000..7ea3c36c2a80f1 --- /dev/null +++ b/deps/zlib/google/zip_unittest.cc @@ -0,0 +1,559 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include +#include +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "build/build_config.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" +#include "third_party/zlib/google/zip.h" +#include "third_party/zlib/google/zip_reader.h" + +namespace { + +bool CreateFile(const std::string& content, + base::FilePath* file_path, + base::File* file) { + if (!base::CreateTemporaryFile(file_path)) + return false; + + if (base::WriteFile(*file_path, content.data(), content.size()) == -1) + return false; + + *file = base::File( + *file_path, base::File::Flags::FLAG_OPEN | base::File::Flags::FLAG_READ); + return file->IsValid(); +} + +// A virtual file system containing: +// /test +// /test/foo.txt +// /test/bar/bar1.txt +// /test/bar/bar2.txt +// Used to test providing a custom zip::FileAccessor when unzipping. +class VirtualFileSystem : public zip::FileAccessor { + public: + static constexpr char kFooContent[] = "This is foo."; + static constexpr char kBar1Content[] = "This is bar."; + static constexpr char kBar2Content[] = "This is bar too."; + + VirtualFileSystem() { + base::FilePath test_dir(FILE_PATH_LITERAL("/test")); + base::FilePath foo_txt_path = test_dir.Append(FILE_PATH_LITERAL("foo.txt")); + + base::FilePath file_path; + base::File file; + bool success = CreateFile(kFooContent, &file_path, &file); + DCHECK(success); + files_[foo_txt_path] = std::move(file); + + base::FilePath bar_dir = test_dir.Append(FILE_PATH_LITERAL("bar")); + base::FilePath bar1_txt_path = + bar_dir.Append(FILE_PATH_LITERAL("bar1.txt")); + success = CreateFile(kBar1Content, &file_path, &file); + DCHECK(success); + files_[bar1_txt_path] = std::move(file); + + base::FilePath bar2_txt_path = + bar_dir.Append(FILE_PATH_LITERAL("bar2.txt")); + success = CreateFile(kBar2Content, &file_path, &file); + DCHECK(success); + files_[bar2_txt_path] = std::move(file); + + file_tree_[test_dir] = std::vector{ + DirectoryContentEntry(foo_txt_path, /*is_dir=*/false), + DirectoryContentEntry(bar_dir, /*is_dir=*/true)}; + file_tree_[bar_dir] = std::vector{ + DirectoryContentEntry(bar1_txt_path, /*is_dir=*/false), + DirectoryContentEntry(bar2_txt_path, /*is_dir=*/false)}; + } + ~VirtualFileSystem() override = default; + + private: + std::vector OpenFilesForReading( + const std::vector& paths) override { + std::vector files; + for (const auto& path : paths) { + auto iter = files_.find(path); + files.push_back(iter == files_.end() ? base::File() + : std::move(iter->second)); + } + return files; + } + + bool DirectoryExists(const base::FilePath& file) override { + return file_tree_.count(file) == 1 && files_.count(file) == 0; + } + + std::vector ListDirectoryContent( + const base::FilePath& dir) override { + auto iter = file_tree_.find(dir); + if (iter == file_tree_.end()) { + NOTREACHED(); + return std::vector(); + } + return iter->second; + } + + base::Time GetLastModifiedTime(const base::FilePath& path) override { + return base::Time::FromDoubleT(172097977); // Some random date. + } + + std::map> file_tree_; + std::map files_; + + DISALLOW_COPY_AND_ASSIGN(VirtualFileSystem); +}; + +// static +constexpr char VirtualFileSystem::kFooContent[]; +constexpr char VirtualFileSystem::kBar1Content[]; +constexpr char VirtualFileSystem::kBar2Content[]; + +// Make the test a PlatformTest to setup autorelease pools properly on Mac. +class ZipTest : public PlatformTest { + protected: + enum ValidYearType { + VALID_YEAR, + INVALID_YEAR + }; + + virtual void SetUp() { + PlatformTest::SetUp(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + test_dir_ = temp_dir_.GetPath(); + + base::FilePath zip_path(test_dir_); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("foo.txt"))); + zip_path = zip_path.Append(FILE_PATH_LITERAL("foo")); + zip_contents_.insert(zip_path); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("bar.txt"))); + zip_path = zip_path.Append(FILE_PATH_LITERAL("bar")); + zip_contents_.insert(zip_path); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("baz.txt"))); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("quux.txt"))); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL(".hidden"))); + + // Include a subset of files in |zip_file_list_| to test ZipFiles(). + zip_file_list_.push_back(base::FilePath(FILE_PATH_LITERAL("foo.txt"))); + zip_file_list_.push_back( + base::FilePath(FILE_PATH_LITERAL("foo/bar/quux.txt"))); + zip_file_list_.push_back( + base::FilePath(FILE_PATH_LITERAL("foo/bar/.hidden"))); + } + + virtual void TearDown() { + PlatformTest::TearDown(); + } + + bool GetTestDataDirectory(base::FilePath* path) { + bool success = base::PathService::Get(base::DIR_SOURCE_ROOT, path); + EXPECT_TRUE(success); + if (!success) + return false; + *path = path->AppendASCII("third_party"); + *path = path->AppendASCII("zlib"); + *path = path->AppendASCII("google"); + *path = path->AppendASCII("test"); + *path = path->AppendASCII("data"); + return true; + } + + void TestUnzipFile(const base::FilePath::StringType& filename, + bool expect_hidden_files) { + base::FilePath test_dir; + ASSERT_TRUE(GetTestDataDirectory(&test_dir)); + TestUnzipFile(test_dir.Append(filename), expect_hidden_files); + } + + void TestUnzipFile(const base::FilePath& path, bool expect_hidden_files) { + ASSERT_TRUE(base::PathExists(path)) << "no file " << path.value(); + ASSERT_TRUE(zip::Unzip(path, test_dir_)); + + base::FilePath original_dir; + ASSERT_TRUE(GetTestDataDirectory(&original_dir)); + original_dir = original_dir.AppendASCII("test"); + + base::FileEnumerator files(test_dir_, true, + base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES); + base::FilePath unzipped_entry_path = files.Next(); + size_t count = 0; + while (!unzipped_entry_path.value().empty()) { + EXPECT_EQ(zip_contents_.count(unzipped_entry_path), 1U) + << "Couldn't find " << unzipped_entry_path.value(); + count++; + + if (base::PathExists(unzipped_entry_path) && + !base::DirectoryExists(unzipped_entry_path)) { + // It's a file, check its contents are what we zipped. + // TODO(774156): figure out why the commented out EXPECT_TRUE below + // fails on the build bots (but not on the try-bots). + base::FilePath relative_path; + bool append_relative_path_success = + test_dir_.AppendRelativePath(unzipped_entry_path, &relative_path); + if (!append_relative_path_success) { + LOG(ERROR) << "Append relative path failed, params: " + << test_dir_.value() << " and " + << unzipped_entry_path.value(); + } + base::FilePath original_path = original_dir.Append(relative_path); + LOG(ERROR) << "Comparing original " << original_path.value() + << " and unzipped file " << unzipped_entry_path.value() + << " result: " + << base::ContentsEqual(original_path, unzipped_entry_path); + // EXPECT_TRUE(base::ContentsEqual(original_path, unzipped_entry_path)) + // << "Contents differ between original " << original_path.value() + // << " and unzipped file " << unzipped_entry_path.value(); + } + unzipped_entry_path = files.Next(); + } + + size_t expected_count = 0; + for (std::set::iterator iter = zip_contents_.begin(); + iter != zip_contents_.end(); ++iter) { + if (expect_hidden_files || iter->BaseName().value()[0] != '.') + ++expected_count; + } + + EXPECT_EQ(expected_count, count); + } + + // This function does the following: + // 1) Creates a test.txt file with the given last modification timestamp + // 2) Zips test.txt and extracts it back into a different location. + // 3) Confirms that test.txt in the output directory has the specified + // last modification timestamp if it is valid (|valid_year| is true). + // If the timestamp is not supported by the zip format, the last + // modification defaults to the current time. + void TestTimeStamp(const char* date_time, ValidYearType valid_year) { + SCOPED_TRACE(std::string("TestTimeStamp(") + date_time + ")"); + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + base::FilePath src_dir = temp_dir.GetPath().AppendASCII("input"); + base::FilePath out_dir = temp_dir.GetPath().AppendASCII("output"); + + base::FilePath src_file = src_dir.AppendASCII("test.txt"); + base::FilePath out_file = out_dir.AppendASCII("test.txt"); + + EXPECT_TRUE(base::CreateDirectory(src_dir)); + EXPECT_TRUE(base::CreateDirectory(out_dir)); + + base::Time test_mtime; + ASSERT_TRUE(base::Time::FromString(date_time, &test_mtime)); + + // Adjusting the current timestamp to the resolution that the zip file + // supports, which is 2 seconds. Note that between this call to Time::Now() + // and zip::Zip() the clock can advance a bit, hence the use of EXPECT_GE. + base::Time::Exploded now_parts; + base::Time::Now().LocalExplode(&now_parts); + now_parts.second = now_parts.second & ~1; + now_parts.millisecond = 0; + base::Time now_time; + EXPECT_TRUE(base::Time::FromLocalExploded(now_parts, &now_time)); + + EXPECT_EQ(1, base::WriteFile(src_file, "1", 1)); + EXPECT_TRUE(base::TouchFile(src_file, base::Time::Now(), test_mtime)); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, true)); + ASSERT_TRUE(zip::Unzip(zip_file, out_dir)); + + base::File::Info file_info; + EXPECT_TRUE(base::GetFileInfo(out_file, &file_info)); + EXPECT_EQ(file_info.size, 1); + + if (valid_year == VALID_YEAR) { + EXPECT_EQ(file_info.last_modified, test_mtime); + } else { + // Invalid date means the modification time will default to 'now'. + EXPECT_GE(file_info.last_modified, now_time); + } + } + + // The path to temporary directory used to contain the test operations. + base::FilePath test_dir_; + + base::ScopedTempDir temp_dir_; + + // Hard-coded contents of a known zip file. + std::set zip_contents_; + + // Hard-coded list of relative paths for a zip file created with ZipFiles. + std::vector zip_file_list_; +}; + +TEST_F(ZipTest, Unzip) { + TestUnzipFile(FILE_PATH_LITERAL("test.zip"), true); +} + +TEST_F(ZipTest, UnzipUncompressed) { + TestUnzipFile(FILE_PATH_LITERAL("test_nocompress.zip"), true); +} + +TEST_F(ZipTest, UnzipEvil) { + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + path = path.AppendASCII("evil.zip"); + // Unzip the zip file into a sub directory of test_dir_ so evil.zip + // won't create a persistent file outside test_dir_ in case of a + // failure. + base::FilePath output_dir = test_dir_.AppendASCII("out"); + ASSERT_FALSE(zip::Unzip(path, output_dir)); + base::FilePath evil_file = output_dir; + evil_file = evil_file.AppendASCII( + "../levilevilevilevilevilevilevilevilevilevilevilevil"); + ASSERT_FALSE(base::PathExists(evil_file)); +} + +TEST_F(ZipTest, UnzipEvil2) { + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + // The zip file contains an evil file with invalid UTF-8 in its file + // name. + path = path.AppendASCII("evil_via_invalid_utf8.zip"); + // See the comment at UnzipEvil() for why we do this. + base::FilePath output_dir = test_dir_.AppendASCII("out"); + // This should fail as it contains an evil file. + ASSERT_FALSE(zip::Unzip(path, output_dir)); + base::FilePath evil_file = output_dir; + evil_file = evil_file.AppendASCII("../evil.txt"); + ASSERT_FALSE(base::PathExists(evil_file)); +} + +TEST_F(ZipTest, UnzipWithFilter) { + auto filter = base::BindRepeating([](const base::FilePath& path) { + return path.BaseName().MaybeAsASCII() == "foo.txt"; + }); + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + ASSERT_TRUE(zip::UnzipWithFilterCallback(path.AppendASCII("test.zip"), + test_dir_, filter, false)); + // Only foo.txt should have been extracted. The following paths should not + // be extracted: + // foo/ + // foo/bar.txt + // foo/bar/ + // foo/bar/.hidden + // foo/bar/baz.txt + // foo/bar/quux.txt + ASSERT_TRUE(base::PathExists(test_dir_.AppendASCII("foo.txt"))); + base::FileEnumerator extractedFiles( + test_dir_, + false, // Do not enumerate recursively - the file must be in the root. + base::FileEnumerator::FileType::FILES); + int extracted_count = 0; + while (!extractedFiles.Next().empty()) + ++extracted_count; + ASSERT_EQ(1, extracted_count); + + base::FileEnumerator extractedDirs( + test_dir_, + false, // Do not enumerate recursively - we require zero directories. + base::FileEnumerator::FileType::DIRECTORIES); + extracted_count = 0; + while (!extractedDirs.Next().empty()) + ++extracted_count; + ASSERT_EQ(0, extracted_count); +} + +TEST_F(ZipTest, UnzipWithDelegates) { + auto filter = + base::BindRepeating([](const base::FilePath& path) { return true; }); + auto dir_creator = base::BindRepeating( + [](const base::FilePath& extract_dir, const base::FilePath& entry_path) { + return base::CreateDirectory(extract_dir.Append(entry_path)); + }, + test_dir_); + auto writer = base::BindRepeating( + [](const base::FilePath& extract_dir, const base::FilePath& entry_path) + -> std::unique_ptr { + return std::make_unique( + extract_dir.Append(entry_path)); + }, + test_dir_); + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + base::File file(path.AppendASCII("test.zip"), + base::File::Flags::FLAG_OPEN | base::File::Flags::FLAG_READ); + ASSERT_TRUE(zip::UnzipWithFilterAndWriters(file.GetPlatformFile(), writer, + dir_creator, filter, false)); + base::FilePath dir = test_dir_; + base::FilePath dir_foo = dir.AppendASCII("foo"); + base::FilePath dir_foo_bar = dir_foo.AppendASCII("bar"); + ASSERT_TRUE(base::PathExists(dir.AppendASCII("foo.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo)); + ASSERT_TRUE(base::PathExists(dir_foo.AppendASCII("bar.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar)); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII(".hidden"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII("baz.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII("quux.txt"))); +} + +TEST_F(ZipTest, Zip) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, /*include_hidden_files=*/true)); + TestUnzipFile(zip_file, true); +} + +TEST_F(ZipTest, ZipIgnoreHidden) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, /*include_hidden_files=*/false)); + TestUnzipFile(zip_file, false); +} + +TEST_F(ZipTest, ZipNonASCIIDir) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + // Append 'Тест' (in cyrillic). + base::FilePath src_dir_russian = temp_dir.GetPath().Append( + base::FilePath::FromUTF8Unsafe("\xD0\xA2\xD0\xB5\xD1\x81\xD1\x82")); + base::CopyDirectory(src_dir, src_dir_russian, true); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out_russian.zip"); + + EXPECT_TRUE(zip::Zip(src_dir_russian, zip_file, true)); + TestUnzipFile(zip_file, true); +} + +TEST_F(ZipTest, ZipTimeStamp) { + // The dates tested are arbitrary, with some constraints. The zip format can + // only store years from 1980 to 2107 and an even number of seconds, due to it + // using the ms dos date format. + + // Valid arbitrary date. + TestTimeStamp("23 Oct 1997 23:22:20", VALID_YEAR); + + // Date before 1980, zip format limitation, must default to unix epoch. + TestTimeStamp("29 Dec 1979 21:00:10", INVALID_YEAR); + + // Despite the minizip headers telling the maximum year should be 2044, it + // can actually go up to 2107. Beyond that, the dos date format cannot store + // the year (2107-1980=127). To test that limit, the input file needs to be + // touched, but the code that modifies the file access and modification times + // relies on time_t which is defined as long, therefore being in many + // platforms just a 4-byte integer, like 32-bit Mac OSX or linux. As such, it + // suffers from the year-2038 bug. Therefore 2038 is the highest we can test + // in all platforms reliably. + TestTimeStamp("02 Jan 2038 23:59:58", VALID_YEAR); +} + +#if defined(OS_POSIX) +TEST_F(ZipTest, ZipFiles) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_name = temp_dir.GetPath().AppendASCII("out.zip"); + + base::File zip_file(zip_name, + base::File::FLAG_CREATE | base::File::FLAG_WRITE); + ASSERT_TRUE(zip_file.IsValid()); + EXPECT_TRUE(zip::ZipFiles(src_dir, zip_file_list_, + zip_file.GetPlatformFile())); + zip_file.Close(); + + zip::ZipReader reader; + EXPECT_TRUE(reader.Open(zip_name)); + EXPECT_EQ(zip_file_list_.size(), static_cast(reader.num_entries())); + for (size_t i = 0; i < zip_file_list_.size(); ++i) { + EXPECT_TRUE(reader.HasMore()); + EXPECT_TRUE(reader.OpenCurrentEntryInZip()); + const zip::ZipReader::EntryInfo* entry_info = reader.current_entry_info(); + EXPECT_EQ(entry_info->file_path(), zip_file_list_[i]); + reader.AdvanceToNextEntry(); + } +} +#endif // defined(OS_POSIX) + +TEST_F(ZipTest, UnzipFilesWithIncorrectSize) { + base::FilePath test_data_folder; + ASSERT_TRUE(GetTestDataDirectory(&test_data_folder)); + + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, but the metadata in the zip file says + // the uncompressed size is 3 bytes. The ZipReader and minizip code needs to + // be clever enough to get all the data out. + base::FilePath test_zip_file = + test_data_folder.AppendASCII("test_mismatch_size.zip"); + + base::ScopedTempDir scoped_temp_dir; + ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + const base::FilePath& temp_dir = scoped_temp_dir.GetPath(); + + ASSERT_TRUE(zip::Unzip(test_zip_file, temp_dir)); + EXPECT_TRUE(base::DirectoryExists(temp_dir.AppendASCII("d"))); + + for (int i = 0; i < 8; i++) { + SCOPED_TRACE(base::StringPrintf("Processing %d.txt", i)); + base::FilePath file_path = temp_dir.AppendASCII( + base::StringPrintf("%d.txt", i)); + int64_t file_size = -1; + EXPECT_TRUE(base::GetFileSize(file_path, &file_size)); + EXPECT_EQ(static_cast(i), file_size); + } +} + +TEST_F(ZipTest, ZipWithFileAccessor) { + base::FilePath zip_file; + ASSERT_TRUE(base::CreateTemporaryFile(&zip_file)); + zip::ZipParams params(base::FilePath(FILE_PATH_LITERAL("/test")), zip_file); + params.set_file_accessor(std::make_unique()); + ASSERT_TRUE(zip::Zip(params)); + + base::ScopedTempDir scoped_temp_dir; + ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + const base::FilePath& temp_dir = scoped_temp_dir.GetPath(); + ASSERT_TRUE(zip::Unzip(zip_file, temp_dir)); + base::FilePath bar_dir = temp_dir.Append(FILE_PATH_LITERAL("bar")); + EXPECT_TRUE(base::DirectoryExists(bar_dir)); + std::string file_content; + EXPECT_TRUE(base::ReadFileToString( + temp_dir.Append(FILE_PATH_LITERAL("foo.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kFooContent, file_content); + EXPECT_TRUE(base::ReadFileToString( + bar_dir.Append(FILE_PATH_LITERAL("bar1.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kBar1Content, file_content); + EXPECT_TRUE(base::ReadFileToString( + bar_dir.Append(FILE_PATH_LITERAL("bar2.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kBar2Content, file_content); +} + +} // namespace diff --git a/deps/zlib/google/zip_writer.cc b/deps/zlib/google/zip_writer.cc new file mode 100644 index 00000000000000..1f2f073b30cb32 --- /dev/null +++ b/deps/zlib/google/zip_writer.cc @@ -0,0 +1,203 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_writer.h" + +#include "base/files/file.h" +#include "base/strings/string_util.h" +#include "third_party/zlib/google/zip_internal.h" + +namespace zip { +namespace internal { + +namespace { + +// Numbers of pending entries that trigger writting them to the ZIP file. +constexpr size_t kMaxPendingEntriesCount = 50; + +bool AddFileContentToZip(zipFile zip_file, + base::File file, + const base::FilePath& file_path) { + int num_bytes; + char buf[zip::internal::kZipBufSize]; + do { + num_bytes = file.ReadAtCurrentPos(buf, zip::internal::kZipBufSize); + + if (num_bytes > 0) { + if (zipWriteInFileInZip(zip_file, buf, num_bytes) != ZIP_OK) { + DLOG(ERROR) << "Could not write data to zip for path " + << file_path.value(); + return false; + } + } + } while (num_bytes > 0); + + return true; +} + +bool OpenNewFileEntry(zipFile zip_file, + const base::FilePath& path, + bool is_directory, + base::Time last_modified) { + std::string str_path = path.AsUTF8Unsafe(); +#if defined(OS_WIN) + base::ReplaceSubstringsAfterOffset(&str_path, 0u, "\\", "/"); +#endif + if (is_directory) + str_path += "/"; + + return zip::internal::ZipOpenNewFileInZip(zip_file, str_path, last_modified); +} + +bool CloseNewFileEntry(zipFile zip_file) { + return zipCloseFileInZip(zip_file) == ZIP_OK; +} + +bool AddFileEntryToZip(zipFile zip_file, + const base::FilePath& path, + base::File file) { + base::File::Info file_info; + if (!file.GetInfo(&file_info)) + return false; + + if (!OpenNewFileEntry(zip_file, path, /*is_directory=*/false, + file_info.last_modified)) + return false; + + bool success = AddFileContentToZip(zip_file, std::move(file), path); + if (!CloseNewFileEntry(zip_file)) + return false; + + return success; +} + +bool AddDirectoryEntryToZip(zipFile zip_file, + const base::FilePath& path, + base::Time last_modified) { + return OpenNewFileEntry(zip_file, path, /*is_directory=*/true, + last_modified) && + CloseNewFileEntry(zip_file); +} + +} // namespace + +#if defined(OS_POSIX) +// static +std::unique_ptr ZipWriter::CreateWithFd( + int zip_file_fd, + const base::FilePath& root_dir, + FileAccessor* file_accessor) { + DCHECK(zip_file_fd != base::kInvalidPlatformFile); + zipFile zip_file = + internal::OpenFdForZipping(zip_file_fd, APPEND_STATUS_CREATE); + if (!zip_file) { + DLOG(ERROR) << "Couldn't create ZIP file for FD " << zip_file_fd; + return nullptr; + } + return std::unique_ptr( + new ZipWriter(zip_file, root_dir, file_accessor)); +} +#endif + +// static +std::unique_ptr ZipWriter::Create( + const base::FilePath& zip_file_path, + const base::FilePath& root_dir, + FileAccessor* file_accessor) { + DCHECK(!zip_file_path.empty()); + zipFile zip_file = internal::OpenForZipping(zip_file_path.AsUTF8Unsafe(), + APPEND_STATUS_CREATE); + if (!zip_file) { + DLOG(ERROR) << "Couldn't create ZIP file at path " << zip_file_path; + return nullptr; + } + return std::unique_ptr( + new ZipWriter(zip_file, root_dir, file_accessor)); +} + +ZipWriter::ZipWriter(zipFile zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor) + : zip_file_(zip_file), root_dir_(root_dir), file_accessor_(file_accessor) {} + +ZipWriter::~ZipWriter() { + DCHECK(pending_entries_.empty()); +} + +bool ZipWriter::WriteEntries(const std::vector& paths) { + return AddEntries(paths) && Close(); +} + +bool ZipWriter::AddEntries(const std::vector& paths) { + DCHECK(zip_file_); + pending_entries_.insert(pending_entries_.end(), paths.begin(), paths.end()); + return FlushEntriesIfNeeded(/*force=*/false); +} + +bool ZipWriter::Close() { + bool success = FlushEntriesIfNeeded(/*force=*/true) && + zipClose(zip_file_, nullptr) == ZIP_OK; + zip_file_ = nullptr; + return success; +} + +bool ZipWriter::FlushEntriesIfNeeded(bool force) { + if (pending_entries_.size() < kMaxPendingEntriesCount && !force) + return true; + + while (pending_entries_.size() >= kMaxPendingEntriesCount || + (force && !pending_entries_.empty())) { + size_t entry_count = + std::min(pending_entries_.size(), kMaxPendingEntriesCount); + std::vector relative_paths; + std::vector absolute_paths; + relative_paths.insert(relative_paths.begin(), pending_entries_.begin(), + pending_entries_.begin() + entry_count); + for (auto iter = pending_entries_.begin(); + iter != pending_entries_.begin() + entry_count; ++iter) { + // The FileAccessor requires absolute paths. + absolute_paths.push_back(root_dir_.Append(*iter)); + } + pending_entries_.erase(pending_entries_.begin(), + pending_entries_.begin() + entry_count); + + // We don't know which paths are files and which ones are directories, and + // we want to avoid making a call to file_accessor_ for each entry. Open the + // files instead, invalid files are returned for directories. + std::vector files = + file_accessor_->OpenFilesForReading(absolute_paths); + DCHECK_EQ(files.size(), relative_paths.size()); + for (size_t i = 0; i < files.size(); i++) { + const base::FilePath& relative_path = relative_paths[i]; + const base::FilePath& absolute_path = absolute_paths[i]; + base::File file = std::move(files[i]); + if (file.IsValid()) { + if (!AddFileEntryToZip(zip_file_, relative_path, std::move(file))) { + LOG(ERROR) << "Failed to write file " << relative_path.value() + << " to ZIP file."; + return false; + } + } else { + // Missing file or directory case. + base::Time last_modified = + file_accessor_->GetLastModifiedTime(absolute_path); + if (last_modified.is_null()) { + LOG(ERROR) << "Failed to write entry " << relative_path.value() + << " to ZIP file."; + return false; + } + DCHECK(file_accessor_->DirectoryExists(absolute_path)); + if (!AddDirectoryEntryToZip(zip_file_, relative_path, last_modified)) { + LOG(ERROR) << "Failed to write directory " << relative_path.value() + << " to ZIP file."; + return false; + } + } + } + } + return true; +} + +} // namespace internal +} // namespace zip diff --git a/deps/zlib/google/zip_writer.h b/deps/zlib/google/zip_writer.h new file mode 100644 index 00000000000000..bd2a727b94d408 --- /dev/null +++ b/deps/zlib/google/zip_writer.h @@ -0,0 +1,91 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ + +#include +#include + +#include "base/files/file_path.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#endif + +namespace zip { +namespace internal { + +// A class used to write entries to a ZIP file and buffering the reading of +// files to limit the number of calls to the FileAccessor. This is for +// performance reasons as these calls may be expensive when IPC based). +// This class is so far internal and only used by zip.cc, but could be made +// public if needed. +class ZipWriter { + public: +// Creates a writer that will write a ZIP file to |zip_file_fd|/|zip_file| +// and which entries (specifies with AddEntries) are relative to |root_dir|. +// All file reads are performed using |file_accessor|. +#if defined(OS_POSIX) + static std::unique_ptr CreateWithFd(int zip_file_fd, + const base::FilePath& root_dir, + FileAccessor* file_accessor); +#endif + static std::unique_ptr Create(const base::FilePath& zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor); + ~ZipWriter(); + + // Writes the files at |paths| to the ZIP file and closes this Zip file. + // Note that the the FilePaths must be relative to |root_dir| specified in the + // Create method. + // Returns true if all entries were written successfuly. + bool WriteEntries(const std::vector& paths); + + private: + ZipWriter(zipFile zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor); + + // Writes the pending entries to the ZIP file if there are at least + // |kMaxPendingEntriesCount| of them. If |force| is true, all pending entries + // are written regardless of how many there are. + // Returns false if writing an entry fails, true if no entry was written or + // there was no error writing entries. + bool FlushEntriesIfNeeded(bool force); + + // Adds the files at |paths| to the ZIP file. These FilePaths must be relative + // to |root_dir| specified in the Create method. + bool AddEntries(const std::vector& paths); + + // Closes the ZIP file. + // Returns true if successful, false otherwise (typically if an entry failed + // to be written). + bool Close(); + + // The entries that have been added but not yet written to the ZIP file. + std::vector pending_entries_; + + // The actual zip file. + zipFile zip_file_; + + // Path to the directory entry paths are relative to. + base::FilePath root_dir_; + + // Abstraction over file access methods used to read files. + FileAccessor* file_accessor_; + + DISALLOW_COPY_AND_ASSIGN(ZipWriter); +}; + +} // namespace internal +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ \ No newline at end of file diff --git a/deps/zlib/gzread.c b/deps/zlib/gzread.c index 956b91ea7d9e2a..832d3ef98c5948 100644 --- a/deps/zlib/gzread.c +++ b/deps/zlib/gzread.c @@ -443,7 +443,11 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) # undef z_gzgetc #else # undef gzgetc +# ifdef Z_CR_PREFIX_SET +# define gzgetc Cr_z_gzgetc +# endif #endif + int ZEXPORT gzgetc(file) gzFile file; { diff --git a/deps/zlib/infback.c b/deps/zlib/infback.c index 59679ecbfc5d77..aab14b4848effa 100644 --- a/deps/zlib/infback.c +++ b/deps/zlib/infback.c @@ -480,7 +480,8 @@ void FAR *out_desc; case LEN: /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; diff --git a/deps/zlib/inffast.c b/deps/zlib/inffast.c index 0dbd1dbc09f2f6..2797e8a03c5151 100644 --- a/deps/zlib/inffast.c +++ b/deps/zlib/inffast.c @@ -18,13 +18,13 @@ available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. + inflate() execution time is spent in this routine. Entry assumptions: state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 + strm->avail_in >= INFLATE_FAST_MIN_INPUT (6 bytes) + strm->avail_out >= INFLATE_FAST_MIN_OUTPUT (258 bytes) start >= strm->avail_out state->bits < 8 @@ -36,16 +36,20 @@ Notes: + INFLATE_FAST_MIN_INPUT: 6 bytes + - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. + INFLATE_FAST_MIN_OUTPUT: 258 bytes + - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for - output space. + available output space while decoding. */ void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; @@ -80,10 +84,10 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; in = strm->next_in; - last = in + (strm->avail_in - 5); + last = in + (strm->avail_in - (INFLATE_FAST_MIN_INPUT - 1)); out = strm->next_out; beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); + end = out + (strm->avail_out - (INFLATE_FAST_MIN_OUTPUT - 1)); #ifdef INFLATE_STRICT dmax = state->dmax; #endif @@ -298,9 +302,12 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ /* update state and return */ strm->next_in = in; strm->next_out = out; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_in = (unsigned)(in < last ? + (INFLATE_FAST_MIN_INPUT - 1) + (last - in) : + (INFLATE_FAST_MIN_INPUT - 1) - (in - last)); strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); + (INFLATE_FAST_MIN_OUTPUT - 1) + (end - out) : + (INFLATE_FAST_MIN_OUTPUT - 1) - (out - end)); state->hold = hold; state->bits = bits; return; diff --git a/deps/zlib/inffast.h b/deps/zlib/inffast.h index e5c1aa4ca8cd52..c7c1c09808e5e9 100644 --- a/deps/zlib/inffast.h +++ b/deps/zlib/inffast.h @@ -8,4 +8,19 @@ subject to change. Applications should only use zlib.h. */ +/* INFLATE_FAST_MIN_INPUT: the minimum number of input bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair (15 bits for the length code, 5 bits for length + extra, 15 bits for the distance code, 13 bits for distance extra) requires + reading up to 48 input bits (6 bytes). +*/ +#define INFLATE_FAST_MIN_INPUT 6 + +/* INFLATE_FAST_MIN_OUTPUT: the minimum number of output bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair can output up to 258 bytes, which is the maximum + length that can be coded. + */ +#define INFLATE_FAST_MIN_OUTPUT 258 + void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/deps/zlib/inflate.c b/deps/zlib/inflate.c index ac333e8c2edae9..68902e81bd4be9 100644 --- a/deps/zlib/inflate.c +++ b/deps/zlib/inflate.c @@ -228,6 +228,7 @@ int stream_size; state->strm = strm; state->window = Z_NULL; state->mode = HEAD; /* to pass state test in inflateReset2() */ + state->check = 1L; /* 1L is the result of adler32() zero length data */ ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); @@ -1042,7 +1043,8 @@ int flush; case LEN_: state->mode = LEN; case LEN: - if (have >= 6 && left >= 258) { + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { RESTORE(); inflate_fast(strm, out); LOAD(); diff --git a/deps/zlib/make_vms.com b/deps/zlib/make_vms.com deleted file mode 100644 index 65e9d0cbc8e1dd..00000000000000 --- a/deps/zlib/make_vms.com +++ /dev/null @@ -1,867 +0,0 @@ -$! make libz under VMS written by -$! Martin P.J. Zinser -$! -$! In case of problems with the install you might contact me at -$! zinser@zinser.no-ip.info(preferred) or -$! martin.zinser@eurexchange.com (work) -$! -$! Make procedure history for Zlib -$! -$!------------------------------------------------------------------------------ -$! Version history -$! 0.01 20060120 First version to receive a number -$! 0.02 20061008 Adapt to new Makefile.in -$! 0.03 20091224 Add support for large file check -$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite -$! 0.05 20100221 Exchange zlibdefs.h by zconf.h.in -$! 0.06 20120111 Fix missing amiss_err, update zconf_h.in, fix new exmples -$! subdir path, update module search in makefile.in -$! 0.07 20120115 Triggered by work done by Alexey Chupahin completly redesigned -$! shared image creation -$! 0.08 20120219 Make it work on VAX again, pre-load missing symbols to shared -$! image -$! 0.09 20120305 SMS. P1 sets builder ("MMK", "MMS", " " (built-in)). -$! "" -> automatic, preference: MMK, MMS, built-in. -$! -$ on error then goto err_exit -$! -$ true = 1 -$ false = 0 -$ tmpnam = "temp_" + f$getjpi("","pid") -$ tt = tmpnam + ".txt" -$ tc = tmpnam + ".c" -$ th = tmpnam + ".h" -$ define/nolog tconfig 'th' -$ its_decc = false -$ its_vaxc = false -$ its_gnuc = false -$ s_case = False -$! -$! Setup variables holding "config" information -$! -$ Make = "''p1'" -$ name = "Zlib" -$ version = "?.?.?" -$ v_string = "ZLIB_VERSION" -$ v_file = "zlib.h" -$ ccopt = "/include = []" -$ lopts = "" -$ dnsrl = "" -$ aconf_in_file = "zconf.h.in#zconf.h_in#zconf_h.in" -$ conf_check_string = "" -$ linkonly = false -$ optfile = name + ".opt" -$ mapfile = name + ".map" -$ libdefs = "" -$ vax = f$getsyi("HW_MODEL").lt.1024 -$ axp = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096 -$ ia64 = f$getsyi("HW_MODEL").ge.4096 -$! -$! 2012-03-05 SMS. -$! Why is this needed? And if it is needed, why not simply ".not. vax"? -$! -$!!! if axp .or. ia64 then set proc/parse=extended -$! -$ whoami = f$parse(f$environment("Procedure"),,,,"NO_CONCEAL") -$ mydef = F$parse(whoami,,,"DEVICE") -$ mydir = f$parse(whoami,,,"DIRECTORY") - "][" -$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type") -$! -$! Check for MMK/MMS -$! -$ if (Make .eqs. "") -$ then -$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS" -$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK" -$ else -$ Make = f$edit( Make, "trim") -$ endif -$! -$ gosub find_version -$! -$ open/write topt tmp.opt -$ open/write optf 'optfile' -$! -$ gosub check_opts -$! -$! Look for the compiler used -$! -$ gosub check_compiler -$ close topt -$ close optf -$! -$ if its_decc -$ then -$ ccopt = "/prefix=all" + ccopt -$ if f$trnlnm("SYS") .eqs. "" -$ then -$ if axp -$ then -$ define sys sys$library: -$ else -$ ccopt = "/decc" + ccopt -$ define sys decc$library_include: -$ endif -$ endif -$! -$! 2012-03-05 SMS. -$! Why /NAMES = AS_IS? Why not simply ".not. vax"? And why not on VAX? -$! -$ if axp .or. ia64 -$ then -$ ccopt = ccopt + "/name=as_is/opt=(inline=speed)" -$ s_case = true -$ endif -$ endif -$ if its_vaxc .or. its_gnuc -$ then -$ if f$trnlnm("SYS").eqs."" then define sys sys$library: -$ endif -$! -$! Build a fake configure input header -$! -$ open/write conf_hin config.hin -$ write conf_hin "#undef _LARGEFILE64_SOURCE" -$ close conf_hin -$! -$! -$ i = 0 -$FIND_ACONF: -$ fname = f$element(i,"#",aconf_in_file) -$ if fname .eqs. "#" then goto AMISS_ERR -$ if f$search(fname) .eqs. "" -$ then -$ i = i + 1 -$ goto find_aconf -$ endif -$ open/read/err=aconf_err aconf_in 'fname' -$ open/write aconf zconf.h -$ACONF_LOOP: -$ read/end_of_file=aconf_exit aconf_in line -$ work = f$edit(line, "compress,trim") -$ if f$extract(0,6,work) .nes. "#undef" -$ then -$ if f$extract(0,12,work) .nes. "#cmakedefine" -$ then -$ write aconf line -$ endif -$ else -$ cdef = f$element(1," ",work) -$ gosub check_config -$ endif -$ goto aconf_loop -$ACONF_EXIT: -$ write aconf "" -$ write aconf "/* VMS specifics added by make_vms.com: */" -$ write aconf "#define VMS 1" -$ write aconf "#include " -$ write aconf "#include " -$ write aconf "#ifdef _LARGEFILE" -$ write aconf "# define off64_t __off64_t" -$ write aconf "# define fopen64 fopen" -$ write aconf "# define fseeko64 fseeko" -$ write aconf "# define lseek64 lseek" -$ write aconf "# define ftello64 ftell" -$ write aconf "#endif" -$ write aconf "#if !defined( __VAX) && (__CRTL_VER >= 70312000)" -$ write aconf "# define HAVE_VSNPRINTF" -$ write aconf "#endif" -$ close aconf_in -$ close aconf -$ if f$search("''th'") .nes. "" then delete 'th';* -$! Build the thing plain or with mms -$! -$ write sys$output "Compiling Zlib sources ..." -$ if make.eqs."" -$ then -$ if (f$search( "example.obj;*") .nes. "") then delete example.obj;* -$ if (f$search( "minigzip.obj;*") .nes. "") then delete minigzip.obj;* -$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" - - adler32.c zlib.h zconf.h -$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" - - compress.c zlib.h zconf.h -$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" - - crc32.c zlib.h zconf.h -$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" - - deflate.c deflate.h zutil.h zlib.h zconf.h -$ CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" - - gzclose.c zutil.h zlib.h zconf.h -$ CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" - - gzlib.c zutil.h zlib.h zconf.h -$ CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" - - gzread.c zutil.h zlib.h zconf.h -$ CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" - - gzwrite.c zutil.h zlib.h zconf.h -$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" - - infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h -$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" - - inffast.c zutil.h zlib.h zconf.h inffast.h -$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" - - inflate.c zutil.h zlib.h zconf.h infblock.h -$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" - - inftrees.c zutil.h zlib.h zconf.h inftrees.h -$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" - - trees.c deflate.h zutil.h zlib.h zconf.h -$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" - - uncompr.c zlib.h zconf.h -$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" - - zutil.c zutil.h zlib.h zconf.h -$ write sys$output "Building Zlib ..." -$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ -$ write sys$output "Building example..." -$ CALL MAKE example.OBJ "CC ''CCOPT' [.test]example" - - [.test]example.c zlib.h zconf.h -$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb -$ write sys$output "Building minigzip..." -$ CALL MAKE minigzip.OBJ "CC ''CCOPT' [.test]minigzip" - - [.test]minigzip.c zlib.h zconf.h -$ call make minigzip.exe - - "LINK minigzip,libz.olb/lib" - - minigzip.obj libz.olb -$ else -$ gosub crea_mms -$ write sys$output "Make ''name' ''version' with ''Make' " -$ 'make' -$ endif -$! -$! Create shareable image -$! -$ gosub crea_olist -$ write sys$output "Creating libzshr.exe" -$ call map_2_shopt 'mapfile' 'optfile' -$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,'optfile'/opt -$ write sys$output "Zlib build completed" -$ delete/nolog tmp.opt;* -$ exit -$AMISS_ERR: -$ write sys$output "No source for config.hin found." -$ write sys$output "Tried any of ''aconf_in_file'" -$ goto err_exit -$CC_ERR: -$ write sys$output "C compiler required to build ''name'" -$ goto err_exit -$ERR_EXIT: -$ set message/facil/ident/sever/text -$ close/nolog optf -$ close/nolog topt -$ close/nolog aconf_in -$ close/nolog aconf -$ close/nolog out -$ close/nolog min -$ close/nolog mod -$ close/nolog h_in -$ write sys$output "Exiting..." -$ exit 2 -$! -$! -$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES -$ V = 'F$Verify(0) -$! P1 = What we are trying to make -$! P2 = Command to make it -$! P3 - P8 What it depends on -$ -$ If F$Search(P1) .Eqs. "" Then Goto Makeit -$ Time = F$CvTime(F$File(P1,"RDT")) -$arg=3 -$Loop: -$ Argument = P'arg -$ If Argument .Eqs. "" Then Goto Exit -$ El=0 -$Loop2: -$ File = F$Element(El," ",Argument) -$ If File .Eqs. " " Then Goto Endl -$ AFile = "" -$Loop3: -$ OFile = AFile -$ AFile = F$Search(File) -$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl -$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit -$ Goto Loop3 -$NextEL: -$ El = El + 1 -$ Goto Loop2 -$EndL: -$ arg=arg+1 -$ If arg .Le. 8 Then Goto Loop -$ Goto Exit -$ -$Makeit: -$ VV=F$VERIFY(0) -$ write sys$output P2 -$ 'P2 -$ VV='F$Verify(VV) -$Exit: -$ If V Then Set Verify -$ENDSUBROUTINE -$!------------------------------------------------------------------------------ -$! -$! Check command line options and set symbols accordingly -$! -$!------------------------------------------------------------------------------ -$! Version history -$! 0.01 20041206 First version to receive a number -$! 0.02 20060126 Add new "HELP" target -$ CHECK_OPTS: -$ i = 1 -$ OPT_LOOP: -$ if i .lt. 9 -$ then -$ cparm = f$edit(p'i',"upcase") -$! -$! Check if parameter actually contains something -$! -$ if f$edit(cparm,"trim") .nes. "" -$ then -$ if cparm .eqs. "DEBUG" -$ then -$ ccopt = ccopt + "/noopt/deb" -$ lopts = lopts + "/deb" -$ endif -$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ ccopt = ccopt + f$extract(start,len,cparm) -$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) - - then s_case = true -$ endif -$ if cparm .eqs. "LINK" then linkonly = true -$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ lopts = lopts + f$extract(start,len,cparm) -$ endif -$ if f$locate("CC=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ cc_com = f$extract(start,len,cparm) - if (cc_com .nes. "DECC") .and. - - (cc_com .nes. "VAXC") .and. - - (cc_com .nes. "GNUC") -$ then -$ write sys$output "Unsupported compiler choice ''cc_com' ignored" -$ write sys$output "Use DECC, VAXC, or GNUC instead" -$ else -$ if cc_com .eqs. "DECC" then its_decc = true -$ if cc_com .eqs. "VAXC" then its_vaxc = true -$ if cc_com .eqs. "GNUC" then its_gnuc = true -$ endif -$ endif -$ if f$locate("MAKE=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ mmks = f$extract(start,len,cparm) -$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS") -$ then -$ make = mmks -$ else -$ write sys$output "Unsupported make choice ''mmks' ignored" -$ write sys$output "Use MMK or MMS instead" -$ endif -$ endif -$ if cparm .eqs. "HELP" then gosub bhelp -$ endif -$ i = i + 1 -$ goto opt_loop -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Look for the compiler used -$! -$! Version history -$! 0.01 20040223 First version to receive a number -$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists -$! 0.03 20060202 Extend handling of GNU C -$! 0.04 20090402 Compaq -> hp -$CHECK_COMPILER: -$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) -$ then -$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "") -$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "") -$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "") -$ endif -$! -$! Exit if no compiler available -$! -$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) -$ then goto CC_ERR -$ else -$ if its_decc -$ then -$ write sys$output "CC compiler check ... hp C" -$ if f$trnlnm("decc$no_rooted_search_lists") .nes. "" -$ then -$ dnrsl = f$trnlnm("decc$no_rooted_search_lists") -$ endif -$ define/nolog decc$no_rooted_search_lists 1 -$ else -$ if its_vaxc then write sys$output "CC compiler check ... VAX C" -$ if its_gnuc -$ then -$ write sys$output "CC compiler check ... GNU C" -$ if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib" -$ if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib" -$ cc = "gcc" -$ endif -$ if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share" -$ if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share" -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! If MMS/MMK are available dump out the descrip.mms if required -$! -$CREA_MMS: -$ write sys$output "Creating descrip.mms..." -$ create descrip.mms -$ open/append out descrip.mms -$ copy sys$input: out -$ deck -# descrip.mms: MMS description file for building zlib on VMS -# written by Martin P.J. Zinser -# - -OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzlib.obj\ - gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\ - deflate.obj, trees.obj, zutil.obj, inflate.obj, \ - inftrees.obj, inffast.obj - -$ eod -$ write out "CFLAGS=", ccopt -$ write out "LOPTS=", lopts -$ write out "all : example.exe minigzip.exe libz.olb" -$ copy sys$input: out -$ deck - @ write sys$output " Example applications available" - -libz.olb : libz.olb($(OBJS)) - @ write sys$output " libz available" - -example.exe : example.obj libz.olb - link $(LOPTS) example,libz.olb/lib - -minigzip.exe : minigzip.obj libz.olb - link $(LOPTS) minigzip,libz.olb/lib - -clean : - delete *.obj;*,libz.olb;*,*.opt;*,*.exe;* - - -# Other dependencies. -adler32.obj : adler32.c zutil.h zlib.h zconf.h -compress.obj : compress.c zlib.h zconf.h -crc32.obj : crc32.c zutil.h zlib.h zconf.h -deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h -example.obj : [.test]example.c zlib.h zconf.h -gzclose.obj : gzclose.c zutil.h zlib.h zconf.h -gzlib.obj : gzlib.c zutil.h zlib.h zconf.h -gzread.obj : gzread.c zutil.h zlib.h zconf.h -gzwrite.obj : gzwrite.c zutil.h zlib.h zconf.h -inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h -inflate.obj : inflate.c zutil.h zlib.h zconf.h -inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h -minigzip.obj : [.test]minigzip.c zlib.h zconf.h -trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h -uncompr.obj : uncompr.c zlib.h zconf.h -zutil.obj : zutil.c zutil.h zlib.h zconf.h -infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h -$ eod -$ close out -$ return -$!------------------------------------------------------------------------------ -$! -$! Read list of core library sources from makefile.in and create options -$! needed to build shareable image -$! -$CREA_OLIST: -$ open/read min makefile.in -$ open/write mod modules.opt -$ src_check_list = "OBJZ =#OBJG =" -$MRLOOP: -$ read/end=mrdone min rec -$ i = 0 -$SRC_CHECK_LOOP: -$ src_check = f$element(i, "#", src_check_list) -$ i = i+1 -$ if src_check .eqs. "#" then goto mrloop -$ if (f$extract(0,6,rec) .nes. src_check) then goto src_check_loop -$ rec = rec - src_check -$ gosub extra_filnam -$ if (f$element(1,"\",rec) .eqs. "\") then goto mrloop -$MRSLOOP: -$ read/end=mrdone min rec -$ gosub extra_filnam -$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop -$MRDONE: -$ close min -$ close mod -$ return -$!------------------------------------------------------------------------------ -$! -$! Take record extracted in crea_olist and split it into single filenames -$! -$EXTRA_FILNAM: -$ myrec = f$edit(rec - "\", "trim,compress") -$ i = 0 -$FELOOP: -$ srcfil = f$element(i," ", myrec) -$ if (srcfil .nes. " ") -$ then -$ write mod f$parse(srcfil,,,"NAME"), ".obj" -$ i = i + 1 -$ goto feloop -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Find current Zlib version number -$! -$FIND_VERSION: -$ open/read h_in 'v_file' -$hloop: -$ read/end=hdone h_in rec -$ rec = f$edit(rec,"TRIM") -$ if (f$extract(0,1,rec) .nes. "#") then goto hloop -$ rec = f$edit(rec - "#", "TRIM") -$ if f$element(0," ",rec) .nes. "define" then goto hloop -$ if f$element(1," ",rec) .eqs. v_string -$ then -$ version = 'f$element(2," ",rec)' -$ goto hdone -$ endif -$ goto hloop -$hdone: -$ close h_in -$ return -$!------------------------------------------------------------------------------ -$! -$CHECK_CONFIG: -$! -$ in_ldef = f$locate(cdef,libdefs) -$ if (in_ldef .lt. f$length(libdefs)) -$ then -$ write aconf "#define ''cdef' 1" -$ libdefs = f$extract(0,in_ldef,libdefs) + - - f$extract(in_ldef + f$length(cdef) + 1, - - f$length(libdefs) - in_ldef - f$length(cdef) - 1, - - libdefs) -$ else -$ if (f$type('cdef') .eqs. "INTEGER") -$ then -$ write aconf "#define ''cdef' ", 'cdef' -$ else -$ if (f$type('cdef') .eqs. "STRING") -$ then -$ write aconf "#define ''cdef' ", """", '''cdef'', """" -$ else -$ gosub check_cc_def -$ endif -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Check if this is a define relating to the properties of the C/C++ -$! compiler -$! -$ CHECK_CC_DEF: -$ if (cdef .eqs. "_LARGEFILE64_SOURCE") -$ then -$ copy sys$input: 'tc' -$ deck -#include "tconfig" -#define _LARGEFILE -#include - -int main(){ -FILE *fp; - fp = fopen("temp.txt","r"); - fseeko(fp,1,SEEK_SET); - fclose(fp); -} - -$ eod -$ test_inv = false -$ comm_h = false -$ gosub cc_prop_check -$ return -$ endif -$ write aconf "/* ", line, " */" -$ return -$!------------------------------------------------------------------------------ -$! -$! Check for properties of C/C++ compiler -$! -$! Version history -$! 0.01 20031020 First version to receive a number -$! 0.02 20031022 Added logic for defines with value -$! 0.03 20040309 Make sure local config file gets not deleted -$! 0.04 20041230 Also write include for configure run -$! 0.05 20050103 Add processing of "comment defines" -$CC_PROP_CHECK: -$ cc_prop = true -$ is_need = false -$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true) -$ if f$search(th) .eqs. "" then create 'th' -$ set message/nofac/noident/nosever/notext -$ on error then continue -$ cc 'tmpnam' -$ if .not. ($status) then cc_prop = false -$ on error then continue -$! The headers might lie about the capabilities of the RTL -$ link 'tmpnam',tmp.opt/opt -$ if .not. ($status) then cc_prop = false -$ set message/fac/ident/sever/text -$ on error then goto err_exit -$ delete/nolog 'tmpnam'.*;*/exclude='th' -$ if (cc_prop .and. .not. is_need) .or. - - (.not. cc_prop .and. is_need) -$ then -$ write sys$output "Checking for ''cdef'... yes" -$ if f$type('cdef_val'_yes) .nes. "" -$ then -$ if f$type('cdef_val'_yes) .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes) -$ if f$type('cdef_val'_yes) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes) -$ else -$ call write_config f$fao("#define !AS 1",cdef) -$ endif -$ if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. - - (cdef .eqs. "_LARGEFILE64_SOURCE") then - - call write_config f$string("#define _LARGEFILE 1") -$ else -$ write sys$output "Checking for ''cdef'... no" -$ if (comm_h) -$ then - call write_config f$fao("/* !AS */",line) -$ else -$ if f$type('cdef_val'_no) .nes. "" -$ then -$ if f$type('cdef_val'_no) .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no) -$ if f$type('cdef_val'_no) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no) -$ else -$ call write_config f$fao("#undef !AS",cdef) -$ endif -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Check for properties of C/C++ compiler with multiple result values -$! -$! Version history -$! 0.01 20040127 First version -$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05 -$CC_MPROP_CHECK: -$ cc_prop = true -$ i = 1 -$ idel = 1 -$ MT_LOOP: -$ if f$type(result_'i') .eqs. "STRING" -$ then -$ set message/nofac/noident/nosever/notext -$ on error then continue -$ cc 'tmpnam'_'i' -$ if .not. ($status) then cc_prop = false -$ on error then continue -$! The headers might lie about the capabilities of the RTL -$ link 'tmpnam'_'i',tmp.opt/opt -$ if .not. ($status) then cc_prop = false -$ set message/fac/ident/sever/text -$ on error then goto err_exit -$ delete/nolog 'tmpnam'_'i'.*;* -$ if (cc_prop) -$ then -$ write sys$output "Checking for ''cdef'... ", mdef_'i' -$ if f$type(mdef_'i') .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,mdef_'i') -$ if f$type('cdef_val'_yes) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,mdef_'i') -$ goto msym_clean -$ else -$ i = i + 1 -$ goto mt_loop -$ endif -$ endif -$ write sys$output "Checking for ''cdef'... no" -$ call write_config f$fao("#undef !AS",cdef) -$ MSYM_CLEAN: -$ if (idel .le. msym_max) -$ then -$ delete/sym mdef_'idel' -$ idel = idel + 1 -$ goto msym_clean -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Write configuration to both permanent and temporary config file -$! -$! Version history -$! 0.01 20031029 First version to receive a number -$! -$WRITE_CONFIG: SUBROUTINE -$ write aconf 'p1' -$ open/append confh 'th' -$ write confh 'p1' -$ close confh -$ENDSUBROUTINE -$!------------------------------------------------------------------------------ -$! -$! Analyze the project map file and create the symbol vector for a shareable -$! image from it -$! -$! Version history -$! 0.01 20120128 First version -$! 0.02 20120226 Add pre-load logic -$! -$ MAP_2_SHOPT: Subroutine -$! -$ SAY := "WRITE_ SYS$OUTPUT" -$! -$ IF F$SEARCH("''P1'") .EQS. "" -$ THEN -$ SAY "MAP_2_SHOPT-E-NOSUCHFILE: Error, inputfile ''p1' not available" -$ goto exit_m2s -$ ENDIF -$ IF "''P2'" .EQS. "" -$ THEN -$ SAY "MAP_2_SHOPT: Error, no output file provided" -$ goto exit_m2s -$ ENDIF -$! -$ module1 = "deflate#deflateEnd#deflateInit_#deflateParams#deflateSetDictionary" -$ module2 = "gzclose#gzerror#gzgetc#gzgets#gzopen#gzprintf#gzputc#gzputs#gzread" -$ module3 = "gzseek#gztell#inflate#inflateEnd#inflateInit_#inflateSetDictionary" -$ module4 = "inflateSync#uncompress#zlibVersion#compress" -$ open/read map 'p1 -$ if axp .or. ia64 -$ then -$ open/write aopt a.opt -$ open/write bopt b.opt -$ write aopt " CASE_SENSITIVE=YES" -$ write bopt "SYMBOL_VECTOR= (-" -$ mod_sym_num = 1 -$ MOD_SYM_LOOP: -$ if f$type(module'mod_sym_num') .nes. "" -$ then -$ mod_in = 0 -$ MOD_SYM_IN: -$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') -$ if shared_proc .nes. "#" -$ then -$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- - f$edit(shared_proc,"upcase"),shared_proc) -$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) -$ mod_in = mod_in + 1 -$ goto mod_sym_in -$ endif -$ mod_sym_num = mod_sym_num + 1 -$ goto mod_sym_loop -$ endif -$MAP_LOOP: -$ read/end=map_end map line -$ if (f$locate("{",line).lt. f$length(line)) .or. - - (f$locate("global:", line) .lt. f$length(line)) -$ then -$ proc = true -$ goto map_loop -$ endif -$ if f$locate("}",line).lt. f$length(line) then proc = false -$ if f$locate("local:", line) .lt. f$length(line) then proc = false -$ if proc -$ then -$ shared_proc = f$edit(line,"collapse") -$ chop_semi = f$locate(";", shared_proc) -$ if chop_semi .lt. f$length(shared_proc) then - - shared_proc = f$extract(0, chop_semi, shared_proc) -$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- - f$edit(shared_proc,"upcase"),shared_proc) -$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) -$ endif -$ goto map_loop -$MAP_END: -$ close/nolog aopt -$ close/nolog bopt -$ open/append libopt 'p2' -$ open/read aopt a.opt -$ open/read bopt b.opt -$ALOOP: -$ read/end=aloop_end aopt line -$ write libopt line -$ goto aloop -$ALOOP_END: -$ close/nolog aopt -$ sv = "" -$BLOOP: -$ read/end=bloop_end bopt svn -$ if (svn.nes."") -$ then -$ if (sv.nes."") then write libopt sv -$ sv = svn -$ endif -$ goto bloop -$BLOOP_END: -$ write libopt f$extract(0,f$length(sv)-2,sv), "-" -$ write libopt ")" -$ close/nolog bopt -$ delete/nolog/noconf a.opt;*,b.opt;* -$ else -$ if vax -$ then -$ open/append libopt 'p2' -$ mod_sym_num = 1 -$ VMOD_SYM_LOOP: -$ if f$type(module'mod_sym_num') .nes. "" -$ then -$ mod_in = 0 -$ VMOD_SYM_IN: -$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') -$ if shared_proc .nes. "#" -$ then -$ write libopt f$fao("UNIVERSAL=!AS",- - f$edit(shared_proc,"upcase")) -$ mod_in = mod_in + 1 -$ goto vmod_sym_in -$ endif -$ mod_sym_num = mod_sym_num + 1 -$ goto vmod_sym_loop -$ endif -$VMAP_LOOP: -$ read/end=vmap_end map line -$ if (f$locate("{",line).lt. f$length(line)) .or. - - (f$locate("global:", line) .lt. f$length(line)) -$ then -$ proc = true -$ goto vmap_loop -$ endif -$ if f$locate("}",line).lt. f$length(line) then proc = false -$ if f$locate("local:", line) .lt. f$length(line) then proc = false -$ if proc -$ then -$ shared_proc = f$edit(line,"collapse") -$ chop_semi = f$locate(";", shared_proc) -$ if chop_semi .lt. f$length(shared_proc) then - - shared_proc = f$extract(0, chop_semi, shared_proc) -$ write libopt f$fao("UNIVERSAL=!AS",- - f$edit(shared_proc,"upcase")) -$ endif -$ goto vmap_loop -$VMAP_END: -$ else -$ write sys$output "Unknown Architecture (Not VAX, AXP, or IA64)" -$ write sys$output "No options file created" -$ endif -$ endif -$ EXIT_M2S: -$ close/nolog map -$ close/nolog libopt -$ endsubroutine diff --git a/deps/zlib/msdos/Makefile.bor b/deps/zlib/msdos/Makefile.bor deleted file mode 100644 index 3d12a2c25270a4..00000000000000 --- a/deps/zlib/msdos/Makefile.bor +++ /dev/null @@ -1,115 +0,0 @@ -# Makefile for zlib -# Borland C++ -# Last updated: 15-Mar-2003 - -# To use, do "make -fmakefile.bor" -# To compile in small model, set below: MODEL=s - -# WARNING: the small model is supported but only for small values of -# MAX_WBITS and MAX_MEM_LEVEL. For example: -# -DMAX_WBITS=11 -DDEF_WBITS=11 -DMAX_MEM_LEVEL=3 -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to the LOC macro below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------ Turbo C++, Borland C++ ------------ - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added -# to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -# type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. -CPU_TYP = 0 - -# memory model: one of s, m, c, l (small, medium, compact, large) -MODEL=l - -# replace bcc with tcc for Turbo C++ 1.0, with bcc32 for the 32 bit version -CC=bcc -LD=bcc -AR=tlib - -# compiler flags -# replace "-O2" by "-O -G -a -d" for Turbo C++ 1.0 -CFLAGS=-O2 -Z -m$(MODEL) $(LOC) - -LDFLAGS=-m$(MODEL) -f- - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/msdos/Makefile.dj2 b/deps/zlib/msdos/Makefile.dj2 deleted file mode 100644 index 59d2037d69c4e8..00000000000000 --- a/deps/zlib/msdos/Makefile.dj2 +++ /dev/null @@ -1,104 +0,0 @@ -# Makefile for zlib. Modified for djgpp v2.0 by F. J. Donahoe, 3/15/96. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.dj2; make test -fmakefile.dj2 -# -# To install libz.a, zconf.h and zlib.h in the djgpp directories, type: -# -# make install -fmakefile.dj2 -# -# after first defining LIBRARY_PATH and INCLUDE_PATH in djgpp.env as -# in the sample below if the pattern of the DJGPP distribution is to -# be followed. Remember that, while 'es around <=> are ignored in -# makefiles, they are *not* in batch files or in djgpp.env. -# - - - - - -# [make] -# INCLUDE_PATH=%\>;INCLUDE_PATH%%\DJDIR%\include -# LIBRARY_PATH=%\>;LIBRARY_PATH%%\DJDIR%\lib -# BUTT=-m486 -# - - - - - -# Alternately, these variables may be defined below, overriding the values -# in djgpp.env, as -# INCLUDE_PATH=c:\usr\include -# LIBRARY_PATH=c:\usr\lib - -CC=gcc - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lz -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=libz.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -OBJA = -# to use the asm code: make OBJA=match.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -check: test -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -libz.a: $(OBJS) $(OBJA) - $(AR) $@ $(OBJS) $(OBJA) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - -# INCLUDE_PATH and LIBRARY_PATH were set for [make] in djgpp.env . - -.PHONY : uninstall clean - -install: $(INCL) $(LIBS) - -@if not exist $(INCLUDE_PATH)\nul mkdir $(INCLUDE_PATH) - -@if not exist $(LIBRARY_PATH)\nul mkdir $(LIBRARY_PATH) - $(INSTALL) zlib.h $(INCLUDE_PATH) - $(INSTALL) zconf.h $(INCLUDE_PATH) - $(INSTALL) libz.a $(LIBRARY_PATH) - -uninstall: - $(RM) $(INCLUDE_PATH)\zlib.h - $(RM) $(INCLUDE_PATH)\zconf.h - $(RM) $(LIBRARY_PATH)\libz.a - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) libz.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/msdos/Makefile.emx b/deps/zlib/msdos/Makefile.emx deleted file mode 100644 index e30f67bed68e86..00000000000000 --- a/deps/zlib/msdos/Makefile.emx +++ /dev/null @@ -1,69 +0,0 @@ -# Makefile for zlib. Modified for emx 0.9c by Chr. Spieler, 6/17/98. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.emx; make test -fmakefile.emx -# - -CC=gcc - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lzlib -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=zlib.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -zlib.a: $(OBJS) - $(AR) $@ $(OBJS) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - - -.PHONY : clean - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) zlib.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/msdos/Makefile.msc b/deps/zlib/msdos/Makefile.msc deleted file mode 100644 index ae8378615ec6bc..00000000000000 --- a/deps/zlib/msdos/Makefile.msc +++ /dev/null @@ -1,112 +0,0 @@ -# Makefile for zlib -# Microsoft C 5.1 or later -# Last updated: 19-Mar-2003 - -# To use, do "make makefile.msc" -# To compile in small model, set below: MODEL=S - -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to the LOC macro below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------- Microsoft C 5.1 and later ------------- - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added -# to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -# Type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. -CPU_TYP = 0 - -# Memory model: one of S, M, C, L (small, medium, compact, large) -MODEL=L - -CC=cl -CFLAGS=-nologo -A$(MODEL) -G$(CPU_TYP) -W3 -Oait -Gs $(LOC) -#-Ox generates bad code with MSC 5.1 -LIB_CFLAGS=-Zl $(CFLAGS) - -LD=link -LDFLAGS=/noi/e/st:0x1500/noe/farcall/packcode -# "/farcall/packcode" are only useful for `large code' memory models -# but should be a "no-op" for small code models. - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(LIB_CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - $(CC) -c $(CFLAGS) $*.c - -minigzip.obj: test/minigzip.c zlib.h zconf.h - $(CC) -c $(CFLAGS) $*.c - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - if exist $(ZLIB_LIB) del $(ZLIB_LIB) - lib $(ZLIB_LIB) $(OBJ1); - lib $(ZLIB_LIB) $(OBJ2); - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj,,,$(ZLIB_LIB); - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj,,,$(ZLIB_LIB); - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del *.map - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/msdos/Makefile.tc b/deps/zlib/msdos/Makefile.tc deleted file mode 100644 index 5aec82a9d58c45..00000000000000 --- a/deps/zlib/msdos/Makefile.tc +++ /dev/null @@ -1,100 +0,0 @@ -# Makefile for zlib -# Turbo C 2.01, Turbo C++ 1.01 -# Last updated: 15-Mar-2003 - -# To use, do "make -fmakefile.tc" -# To compile in small model, set below: MODEL=s - -# WARNING: the small model is supported but only for small values of -# MAX_WBITS and MAX_MEM_LEVEL. For example: -# -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to CFLAGS below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------ Turbo C 2.01, Turbo C++ 1.01 ------------ -MODEL=l -CC=tcc -LD=tcc -AR=tlib -# CFLAGS=-O2 -G -Z -m$(MODEL) -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 -CFLAGS=-O2 -G -Z -m$(MODEL) -LDFLAGS=-m$(MODEL) -f- - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/nintendods/Makefile b/deps/zlib/nintendods/Makefile deleted file mode 100644 index 21337d01ab2fe2..00000000000000 --- a/deps/zlib/nintendods/Makefile +++ /dev/null @@ -1,126 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITARM)),) -$(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM") -endif - -include $(DEVKITARM)/ds_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# BUILD is the directory where object files & intermediate files will be placed -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -#--------------------------------------------------------------------------------- -TARGET := $(shell basename $(CURDIR)) -BUILD := build -SOURCES := ../../ -DATA := data -INCLUDES := include - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -mthumb -mthumb-interwork - -CFLAGS := -Wall -O2\ - -march=armv5te -mtune=arm946e-s \ - -fomit-frame-pointer -ffast-math \ - $(ARCH) - -CFLAGS += $(INCLUDE) -DARM9 -CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions - -ASFLAGS := $(ARCH) -march=armv5te -mtune=arm946e-s -LDFLAGS = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(LIBNDS) - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export OUTPUT := $(CURDIR)/lib/libz.a - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -export DEPSDIR := $(CURDIR)/$(BUILD) - -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES := $(addsuffix .o,$(BINFILES)) \ - $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -.PHONY: $(BUILD) clean all - -#--------------------------------------------------------------------------------- -all: $(BUILD) - @[ -d $@ ] || mkdir -p include - @cp ../../*.h include - -lib: - @[ -d $@ ] || mkdir -p $@ - -$(BUILD): lib - @[ -d $@ ] || mkdir -p $@ - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @echo clean ... - @rm -fr $(BUILD) lib - -#--------------------------------------------------------------------------------- -else - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -$(OUTPUT) : $(OFILES) - -#--------------------------------------------------------------------------------- -%.bin.o : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/deps/zlib/nintendods/README b/deps/zlib/nintendods/README deleted file mode 100644 index ba7a37dbe8e916..00000000000000 --- a/deps/zlib/nintendods/README +++ /dev/null @@ -1,5 +0,0 @@ -This Makefile requires devkitARM (http://www.devkitpro.org/category/devkitarm/) and works inside "contrib/nds". It is based on a devkitARM template. - -Eduardo Costa -January 3, 2009 - diff --git a/deps/zlib/old/Makefile.emx b/deps/zlib/old/Makefile.emx deleted file mode 100644 index 612b03791583cb..00000000000000 --- a/deps/zlib/old/Makefile.emx +++ /dev/null @@ -1,69 +0,0 @@ -# Makefile for zlib. Modified for emx/rsxnt by Chr. Spieler, 6/16/98. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.emx; make test -fmakefile.emx -# - -CC=gcc -Zwin32 - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lzlib -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=zlib.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ - gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -zlib.a: $(OBJS) - $(AR) $@ $(OBJS) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - - -.PHONY : clean - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) zlib.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/old/Makefile.riscos b/deps/zlib/old/Makefile.riscos deleted file mode 100644 index 57e29d3fba9177..00000000000000 --- a/deps/zlib/old/Makefile.riscos +++ /dev/null @@ -1,151 +0,0 @@ -# Project: zlib_1_03 -# Patched for zlib 1.1.2 rw@shadow.org.uk 19980430 -# test works out-of-the-box, installs `somewhere' on demand - -# Toolflags: -CCflags = -c -depend !Depend -IC: -g -throwback -DRISCOS -fah -C++flags = -c -depend !Depend -IC: -throwback -Linkflags = -aif -c++ -o $@ -ObjAsmflags = -throwback -NoCache -depend !Depend -CMHGflags = -LibFileflags = -c -l -o $@ -Squeezeflags = -o $@ - -# change the line below to where _you_ want the library installed. -libdest = lib:zlib - -# Final targets: -@.lib: @.o.adler32 @.o.compress @.o.crc32 @.o.deflate @.o.gzio \ - @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil @.o.trees \ - @.o.uncompr @.o.zutil - LibFile $(LibFileflags) @.o.adler32 @.o.compress @.o.crc32 @.o.deflate \ - @.o.gzio @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil \ - @.o.trees @.o.uncompr @.o.zutil -test: @.minigzip @.example @.lib - @copy @.lib @.libc A~C~DF~L~N~P~Q~RS~TV - @echo running tests: hang on. - @/@.minigzip -f -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -f -1 libc - @/@.minigzip -d libc-gz - @/@.minigzip -h -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -h -1 libc - @/@.minigzip -d libc-gz - @/@.minigzip -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -1 libc - @/@.minigzip -d libc-gz - @diff @.lib @.libc - @echo that should have reported '@.lib and @.libc identical' if you have diff. - @/@.example @.fred @.fred - @echo that will have given lots of hello!'s. - -@.minigzip: @.o.minigzip @.lib C:o.Stubs - Link $(Linkflags) @.o.minigzip @.lib C:o.Stubs -@.example: @.o.example @.lib C:o.Stubs - Link $(Linkflags) @.o.example @.lib C:o.Stubs - -install: @.lib - cdir $(libdest) - cdir $(libdest).h - @copy @.h.zlib $(libdest).h.zlib A~C~DF~L~N~P~Q~RS~TV - @copy @.h.zconf $(libdest).h.zconf A~C~DF~L~N~P~Q~RS~TV - @copy @.lib $(libdest).lib A~C~DF~L~N~P~Q~RS~TV - @echo okay, installed zlib in $(libdest) - -clean:; remove @.minigzip - remove @.example - remove @.libc - -wipe @.o.* F~r~cV - remove @.fred - -# User-editable dependencies: -.c.o: - cc $(ccflags) -o $@ $< - -# Static dependencies: - -# Dynamic dependencies: -o.example: c.example -o.example: h.zlib -o.example: h.zconf -o.minigzip: c.minigzip -o.minigzip: h.zlib -o.minigzip: h.zconf -o.adler32: c.adler32 -o.adler32: h.zlib -o.adler32: h.zconf -o.compress: c.compress -o.compress: h.zlib -o.compress: h.zconf -o.crc32: c.crc32 -o.crc32: h.zlib -o.crc32: h.zconf -o.deflate: c.deflate -o.deflate: h.deflate -o.deflate: h.zutil -o.deflate: h.zlib -o.deflate: h.zconf -o.gzio: c.gzio -o.gzio: h.zutil -o.gzio: h.zlib -o.gzio: h.zconf -o.infblock: c.infblock -o.infblock: h.zutil -o.infblock: h.zlib -o.infblock: h.zconf -o.infblock: h.infblock -o.infblock: h.inftrees -o.infblock: h.infcodes -o.infblock: h.infutil -o.infcodes: c.infcodes -o.infcodes: h.zutil -o.infcodes: h.zlib -o.infcodes: h.zconf -o.infcodes: h.inftrees -o.infcodes: h.infblock -o.infcodes: h.infcodes -o.infcodes: h.infutil -o.infcodes: h.inffast -o.inffast: c.inffast -o.inffast: h.zutil -o.inffast: h.zlib -o.inffast: h.zconf -o.inffast: h.inftrees -o.inffast: h.infblock -o.inffast: h.infcodes -o.inffast: h.infutil -o.inffast: h.inffast -o.inflate: c.inflate -o.inflate: h.zutil -o.inflate: h.zlib -o.inflate: h.zconf -o.inflate: h.infblock -o.inftrees: c.inftrees -o.inftrees: h.zutil -o.inftrees: h.zlib -o.inftrees: h.zconf -o.inftrees: h.inftrees -o.inftrees: h.inffixed -o.infutil: c.infutil -o.infutil: h.zutil -o.infutil: h.zlib -o.infutil: h.zconf -o.infutil: h.infblock -o.infutil: h.inftrees -o.infutil: h.infcodes -o.infutil: h.infutil -o.trees: c.trees -o.trees: h.deflate -o.trees: h.zutil -o.trees: h.zlib -o.trees: h.zconf -o.trees: h.trees -o.uncompr: c.uncompr -o.uncompr: h.zlib -o.uncompr: h.zconf -o.zutil: c.zutil -o.zutil: h.zutil -o.zutil: h.zlib -o.zutil: h.zconf diff --git a/deps/zlib/old/README b/deps/zlib/old/README deleted file mode 100644 index 800bf079827b7b..00000000000000 --- a/deps/zlib/old/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains files that have not been updated for zlib 1.2.x - -(Volunteers are encouraged to help clean this up. Thanks.) diff --git a/deps/zlib/old/descrip.mms b/deps/zlib/old/descrip.mms deleted file mode 100644 index 7066da5b557e89..00000000000000 --- a/deps/zlib/old/descrip.mms +++ /dev/null @@ -1,48 +0,0 @@ -# descrip.mms: MMS description file for building zlib on VMS -# written by Martin P.J. Zinser - -cc_defs = -c_deb = - -.ifdef __DECC__ -pref = /prefix=all -.endif - -OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj,\ - deflate.obj, trees.obj, zutil.obj, inflate.obj, infblock.obj,\ - inftrees.obj, infcodes.obj, infutil.obj, inffast.obj - -CFLAGS= $(C_DEB) $(CC_DEFS) $(PREF) - -all : example.exe minigzip.exe - @ write sys$output " Example applications available" -libz.olb : libz.olb($(OBJS)) - @ write sys$output " libz available" - -example.exe : example.obj libz.olb - link example,libz.olb/lib - -minigzip.exe : minigzip.obj libz.olb - link minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib - -clean : - delete *.obj;*,libz.olb;* - - -# Other dependencies. -adler32.obj : zutil.h zlib.h zconf.h -compress.obj : zlib.h zconf.h -crc32.obj : zutil.h zlib.h zconf.h -deflate.obj : deflate.h zutil.h zlib.h zconf.h -example.obj : zlib.h zconf.h -gzio.obj : zutil.h zlib.h zconf.h -infblock.obj : zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h -infcodes.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h infcodes.h inffast.h -inffast.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h inffast.h -inflate.obj : zutil.h zlib.h zconf.h infblock.h -inftrees.obj : zutil.h zlib.h zconf.h inftrees.h -infutil.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h -minigzip.obj : zlib.h zconf.h -trees.obj : deflate.h zutil.h zlib.h zconf.h -uncompr.obj : zlib.h zconf.h -zutil.obj : zutil.h zlib.h zconf.h diff --git a/deps/zlib/old/os2/Makefile.os2 b/deps/zlib/old/os2/Makefile.os2 deleted file mode 100644 index bb426c0d8e68df..00000000000000 --- a/deps/zlib/old/os2/Makefile.os2 +++ /dev/null @@ -1,136 +0,0 @@ -# Makefile for zlib under OS/2 using GCC (PGCC) -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile and test, type: -# cp Makefile.os2 .. -# cd .. -# make -f Makefile.os2 test - -# This makefile will build a static library z.lib, a shared library -# z.dll and a import library zdll.lib. You can use either z.lib or -# zdll.lib by specifying either -lz or -lzdll on gcc's command line - -CC=gcc -Zomf -s - -CFLAGS=-O6 -Wall -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-g -DZLIB_DEBUG -#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ -# -Wstrict-prototypes -Wmissing-prototypes - -#################### BUG WARNING: ##################### -## infcodes.c hits a bug in pgcc-1.0, so you have to use either -## -O# where # <= 4 or one of (-fno-ommit-frame-pointer or -fno-force-mem) -## This bug is reportedly fixed in pgcc >1.0, but this was not tested -CFLAGS+=-fno-force-mem - -LDFLAGS=-s -L. -lzdll -Zcrtdll -LDSHARED=$(CC) -s -Zomf -Zdll -Zcrtdll - -VER=1.1.0 -ZLIB=z.lib -SHAREDLIB=z.dll -SHAREDLIBIMP=zdll.lib -LIBS=$(ZLIB) $(SHAREDLIB) $(SHAREDLIBIMP) - -AR=emxomfar cr -IMPLIB=emximp -RANLIB=echo -TAR=tar -SHELL=bash - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ - zutil.o inflate.o infblock.o inftrees.o infcodes.o infutil.o inffast.o - -TEST_OBJS = example.o minigzip.o - -DISTFILES = README INDEX ChangeLog configure Make*[a-z0-9] *.[ch] descrip.mms \ - algorithm.txt zlib.3 msdos/Make*[a-z0-9] msdos/zlib.def msdos/zlib.rc \ - nt/Makefile.nt nt/zlib.dnt contrib/README.contrib contrib/*.txt \ - contrib/asm386/*.asm contrib/asm386/*.c \ - contrib/asm386/*.bat contrib/asm386/zlibvc.d?? contrib/iostream/*.cpp \ - contrib/iostream/*.h contrib/iostream2/*.h contrib/iostream2/*.cpp \ - contrib/untgz/Makefile contrib/untgz/*.c contrib/untgz/*.w32 - -all: example.exe minigzip.exe - -test: all - @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ - echo hello world | ./minigzip | ./minigzip -d || \ - echo ' *** minigzip test FAILED ***' ; \ - if ./example; then \ - echo ' *** zlib test OK ***'; \ - else \ - echo ' *** zlib test FAILED ***'; \ - fi - -$(ZLIB): $(OBJS) - $(AR) $@ $(OBJS) - -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 - -$(SHAREDLIB): $(OBJS) os2/z.def - $(LDSHARED) -o $@ $^ - -$(SHAREDLIBIMP): os2/z.def - $(IMPLIB) -o $@ $^ - -example.exe: example.o $(LIBS) - $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) - -minigzip.exe: minigzip.o $(LIBS) - $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) - -clean: - rm -f *.o *~ example minigzip libz.a libz.so* foo.gz - -distclean: clean - -zip: - mv Makefile Makefile~; cp -p Makefile.in Makefile - rm -f test.c ztest*.c - v=`sed -n -e 's/\.//g' -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ - zip -ul9 zlib$$v $(DISTFILES) - mv Makefile~ Makefile - -dist: - mv Makefile Makefile~; cp -p Makefile.in Makefile - rm -f test.c ztest*.c - d=zlib-`sed -n '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ - rm -f $$d.tar.gz; \ - if test ! -d ../$$d; then rm -f ../$$d; ln -s `pwd` ../$$d; fi; \ - files=""; \ - for f in $(DISTFILES); do files="$$files $$d/$$f"; done; \ - cd ..; \ - GZIP=-9 $(TAR) chofz $$d/$$d.tar.gz $$files; \ - if test ! -d $$d; then rm -f $$d; fi - mv Makefile~ Makefile - -tags: - etags *.[ch] - -depend: - makedepend -- $(CFLAGS) -- *.[ch] - -# DO NOT DELETE THIS LINE -- make depend depends on it. - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -example.o: zlib.h zconf.h -gzio.o: zutil.h zlib.h zconf.h -infblock.o: infblock.h inftrees.h infcodes.h infutil.h zutil.h zlib.h zconf.h -infcodes.o: zutil.h zlib.h zconf.h -infcodes.o: inftrees.h infblock.h infcodes.h infutil.h inffast.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h -inffast.o: infblock.h infcodes.h infutil.h inffast.h -inflate.o: zutil.h zlib.h zconf.h infblock.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -infutil.o: zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h -minigzip.o: zlib.h zconf.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/old/os2/zlib.def b/deps/zlib/old/os2/zlib.def deleted file mode 100644 index 4c753f1a3b9938..00000000000000 --- a/deps/zlib/old/os2/zlib.def +++ /dev/null @@ -1,51 +0,0 @@ -; -; Slightly modified version of ../nt/zlib.dnt :-) -; - -LIBRARY Z -DESCRIPTION "Zlib compression library for OS/2" -CODE PRELOAD MOVEABLE DISCARDABLE -DATA PRELOAD MOVEABLE MULTIPLE - -EXPORTS - adler32 - compress - crc32 - deflate - deflateCopy - deflateEnd - deflateInit2_ - deflateInit_ - deflateParams - deflateReset - deflateSetDictionary - gzclose - gzdopen - gzerror - gzflush - gzopen - gzread - gzwrite - inflate - inflateEnd - inflateInit2_ - inflateInit_ - inflateReset - inflateSetDictionary - inflateSync - uncompress - zlibVersion - gzprintf - gzputc - gzgetc - gzseek - gzrewind - gztell - gzeof - gzsetparams - zError - inflateSyncPoint - get_crc_table - compress2 - gzputs - gzgets diff --git a/deps/zlib/old/visual-basic.txt b/deps/zlib/old/visual-basic.txt deleted file mode 100644 index 57efe58124eed6..00000000000000 --- a/deps/zlib/old/visual-basic.txt +++ /dev/null @@ -1,160 +0,0 @@ -See below some functions declarations for Visual Basic. - -Frequently Asked Question: - -Q: Each time I use the compress function I get the -5 error (not enough - room in the output buffer). - -A: Make sure that the length of the compressed buffer is passed by - reference ("as any"), not by value ("as long"). Also check that - before the call of compress this length is equal to the total size of - the compressed buffer and not zero. - - -From: "Jon Caruana" -Subject: Re: How to port zlib declares to vb? -Date: Mon, 28 Oct 1996 18:33:03 -0600 - -Got the answer! (I haven't had time to check this but it's what I got, and -looks correct): - -He has the following routines working: - compress - uncompress - gzopen - gzwrite - gzread - gzclose - -Declares follow: (Quoted from Carlos Rios , in Vb4 form) - -#If Win16 Then 'Use Win16 calls. -Declare Function compress Lib "ZLIB.DLL" (ByVal compr As - String, comprLen As Any, ByVal buf As String, ByVal buflen - As Long) As Integer -Declare Function uncompress Lib "ZLIB.DLL" (ByVal uncompr - As String, uncomprLen As Any, ByVal compr As String, ByVal - lcompr As Long) As Integer -Declare Function gzopen Lib "ZLIB.DLL" (ByVal filePath As - String, ByVal mode As String) As Long -Declare Function gzread Lib "ZLIB.DLL" (ByVal file As - Long, ByVal uncompr As String, ByVal uncomprLen As Integer) - As Integer -Declare Function gzwrite Lib "ZLIB.DLL" (ByVal file As - Long, ByVal uncompr As String, ByVal uncomprLen As Integer) - As Integer -Declare Function gzclose Lib "ZLIB.DLL" (ByVal file As - Long) As Integer -#Else -Declare Function compress Lib "ZLIB32.DLL" - (ByVal compr As String, comprLen As Any, ByVal buf As - String, ByVal buflen As Long) As Integer -Declare Function uncompress Lib "ZLIB32.DLL" - (ByVal uncompr As String, uncomprLen As Any, ByVal compr As - String, ByVal lcompr As Long) As Long -Declare Function gzopen Lib "ZLIB32.DLL" - (ByVal file As String, ByVal mode As String) As Long -Declare Function gzread Lib "ZLIB32.DLL" - (ByVal file As Long, ByVal uncompr As String, ByVal - uncomprLen As Long) As Long -Declare Function gzwrite Lib "ZLIB32.DLL" - (ByVal file As Long, ByVal uncompr As String, ByVal - uncomprLen As Long) As Long -Declare Function gzclose Lib "ZLIB32.DLL" - (ByVal file As Long) As Long -#End If - --Jon Caruana -jon-net@usa.net -Microsoft Sitebuilder Network Level 1 Member - HTML Writer's Guild Member - - -Here is another example from Michael that he -says conforms to the VB guidelines, and that solves the problem of not -knowing the uncompressed size by storing it at the end of the file: - -'Calling the functions: -'bracket meaning: [optional] {Range of possible values} -'Call subCompressFile( [, , [level of compression {1..9}]]) -'Call subUncompressFile() - -Option Explicit -Private lngpvtPcnSml As Long 'Stores value for 'lngPercentSmaller' -Private Const SUCCESS As Long = 0 -Private Const strFilExt As String = ".cpr" -Private Declare Function lngfncCpr Lib "zlib.dll" Alias "compress2" (ByRef -dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long, -ByVal level As Integer) As Long -Private Declare Function lngfncUcp Lib "zlib.dll" Alias "uncompress" (ByRef -dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long) -As Long - -Public Sub subCompressFile(ByVal strargOriFilPth As String, Optional ByVal -strargCprFilPth As String, Optional ByVal intLvl As Integer = 9) - Dim strCprPth As String - Dim lngOriSiz As Long - Dim lngCprSiz As Long - Dim bytaryOri() As Byte - Dim bytaryCpr() As Byte - lngOriSiz = FileLen(strargOriFilPth) - ReDim bytaryOri(lngOriSiz - 1) - Open strargOriFilPth For Binary Access Read As #1 - Get #1, , bytaryOri() - Close #1 - strCprPth = IIf(strargCprFilPth = "", strargOriFilPth, strargCprFilPth) -'Select file path and name - strCprPth = strCprPth & IIf(Right(strCprPth, Len(strFilExt)) = -strFilExt, "", strFilExt) 'Add file extension if not exists - lngCprSiz = (lngOriSiz * 1.01) + 12 'Compression needs temporary a bit -more space then original file size - ReDim bytaryCpr(lngCprSiz - 1) - If lngfncCpr(bytaryCpr(0), lngCprSiz, bytaryOri(0), lngOriSiz, intLvl) = -SUCCESS Then - lngpvtPcnSml = (1# - (lngCprSiz / lngOriSiz)) * 100 - ReDim Preserve bytaryCpr(lngCprSiz - 1) - Open strCprPth For Binary Access Write As #1 - Put #1, , bytaryCpr() - Put #1, , lngOriSiz 'Add the the original size value to the end -(last 4 bytes) - Close #1 - Else - MsgBox "Compression error" - End If - Erase bytaryCpr - Erase bytaryOri -End Sub - -Public Sub subUncompressFile(ByVal strargFilPth As String) - Dim bytaryCpr() As Byte - Dim bytaryOri() As Byte - Dim lngOriSiz As Long - Dim lngCprSiz As Long - Dim strOriPth As String - lngCprSiz = FileLen(strargFilPth) - ReDim bytaryCpr(lngCprSiz - 1) - Open strargFilPth For Binary Access Read As #1 - Get #1, , bytaryCpr() - Close #1 - 'Read the original file size value: - lngOriSiz = bytaryCpr(lngCprSiz - 1) * (2 ^ 24) _ - + bytaryCpr(lngCprSiz - 2) * (2 ^ 16) _ - + bytaryCpr(lngCprSiz - 3) * (2 ^ 8) _ - + bytaryCpr(lngCprSiz - 4) - ReDim Preserve bytaryCpr(lngCprSiz - 5) 'Cut of the original size value - ReDim bytaryOri(lngOriSiz - 1) - If lngfncUcp(bytaryOri(0), lngOriSiz, bytaryCpr(0), lngCprSiz) = SUCCESS -Then - strOriPth = Left(strargFilPth, Len(strargFilPth) - Len(strFilExt)) - Open strOriPth For Binary Access Write As #1 - Put #1, , bytaryOri() - Close #1 - Else - MsgBox "Uncompression error" - End If - Erase bytaryCpr - Erase bytaryOri -End Sub -Public Property Get lngPercentSmaller() As Long - lngPercentSmaller = lngpvtPcnSml -End Property diff --git a/deps/zlib/os400/README400 b/deps/zlib/os400/README400 deleted file mode 100644 index 4f98334f5ac5f4..00000000000000 --- a/deps/zlib/os400/README400 +++ /dev/null @@ -1,48 +0,0 @@ - ZLIB version 1.2.11 for OS/400 installation instructions - -1) Download and unpack the zlib tarball to some IFS directory. - (i.e.: /path/to/the/zlib/ifs/source/directory) - - If the installed IFS command suppors gzip format, this is straightforward, -else you have to unpack first to some directory on a system supporting it, -then move the whole directory to the IFS via the network (via SMB or FTP). - -2) Edit the configuration parameters in the compilation script. - - EDTF STMF('/path/to/the/zlib/ifs/source/directory/os400/make.sh') - -Tune the parameters according to your needs if not matching the defaults. -Save the file and exit after edition. - -3) Enter qshell, then work in the zlib OS/400 specific directory. - - QSH - cd /path/to/the/zlib/ifs/source/directory/os400 - -4) Compile and install - - sh make.sh - -The script will: -- create the libraries, objects and IFS directories for the zlib environment, -- compile all modules, -- create a service program, -- create a static and a dynamic binding directory, -- install header files for C/C++ and for ILE/RPG, both for compilation in - DB2 and IFS environments. - -That's all. - - -Notes: For OS/400 ILE RPG programmers, a /copy member defining the ZLIB - API prototypes for ILE RPG can be found in ZLIB/H(ZLIB.INC). - In the ILE environment, the same definitions are available from - file zlib.inc located in the same IFS include directory as the - C/C++ header files. - Please read comments in this member for more information. - - Remember that most foreign textual data are ASCII coded: this - implementation does not handle conversion from/to ASCII, so - text data code conversions must be done explicitely. - - Mainly for the reason above, always open zipped files in binary mode. diff --git a/deps/zlib/os400/bndsrc b/deps/zlib/os400/bndsrc deleted file mode 100644 index 5e6e0a2f0af3a8..00000000000000 --- a/deps/zlib/os400/bndsrc +++ /dev/null @@ -1,119 +0,0 @@ -STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('ZLIB') - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.1.3 entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32") - EXPORT SYMBOL("compress") - EXPORT SYMBOL("compress2") - EXPORT SYMBOL("crc32") - EXPORT SYMBOL("get_crc_table") - EXPORT SYMBOL("deflate") - EXPORT SYMBOL("deflateEnd") - EXPORT SYMBOL("deflateSetDictionary") - EXPORT SYMBOL("deflateCopy") - EXPORT SYMBOL("deflateReset") - EXPORT SYMBOL("deflateParams") - EXPORT SYMBOL("deflatePrime") - EXPORT SYMBOL("deflateInit_") - EXPORT SYMBOL("deflateInit2_") - EXPORT SYMBOL("gzopen") - EXPORT SYMBOL("gzdopen") - EXPORT SYMBOL("gzsetparams") - EXPORT SYMBOL("gzread") - EXPORT SYMBOL("gzwrite") - EXPORT SYMBOL("gzprintf") - EXPORT SYMBOL("gzputs") - EXPORT SYMBOL("gzgets") - EXPORT SYMBOL("gzputc") - EXPORT SYMBOL("gzgetc") - EXPORT SYMBOL("gzflush") - EXPORT SYMBOL("gzseek") - EXPORT SYMBOL("gzrewind") - EXPORT SYMBOL("gztell") - EXPORT SYMBOL("gzeof") - EXPORT SYMBOL("gzclose") - EXPORT SYMBOL("gzerror") - EXPORT SYMBOL("inflate") - EXPORT SYMBOL("inflateEnd") - EXPORT SYMBOL("inflateSetDictionary") - EXPORT SYMBOL("inflateSync") - EXPORT SYMBOL("inflateReset") - EXPORT SYMBOL("inflateInit_") - EXPORT SYMBOL("inflateInit2_") - EXPORT SYMBOL("inflateSyncPoint") - EXPORT SYMBOL("uncompress") - EXPORT SYMBOL("zlibVersion") - EXPORT SYMBOL("zError") - EXPORT SYMBOL("z_errmsg") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.1 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("compressBound") - EXPORT SYMBOL("deflateBound") - EXPORT SYMBOL("deflatePending") - EXPORT SYMBOL("gzungetc") - EXPORT SYMBOL("gzclearerr") - EXPORT SYMBOL("inflateBack") - EXPORT SYMBOL("inflateBackEnd") - EXPORT SYMBOL("inflateBackInit_") - EXPORT SYMBOL("inflateCopy") - EXPORT SYMBOL("zlibCompileFlags") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.4 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32_combine") - EXPORT SYMBOL("adler32_combine64") - EXPORT SYMBOL("crc32_combine") - EXPORT SYMBOL("crc32_combine64") - EXPORT SYMBOL("deflateSetHeader") - EXPORT SYMBOL("deflateTune") - EXPORT SYMBOL("gzbuffer") - EXPORT SYMBOL("gzclose_r") - EXPORT SYMBOL("gzclose_w") - EXPORT SYMBOL("gzdirect") - EXPORT SYMBOL("gzoffset") - EXPORT SYMBOL("gzoffset64") - EXPORT SYMBOL("gzopen64") - EXPORT SYMBOL("gzseek64") - EXPORT SYMBOL("gztell64") - EXPORT SYMBOL("inflateGetHeader") - EXPORT SYMBOL("inflateMark") - EXPORT SYMBOL("inflatePrime") - EXPORT SYMBOL("inflateReset2") - EXPORT SYMBOL("inflateUndermine") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.6 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("deflateResetKeep") - EXPORT SYMBOL("gzgetc_") - EXPORT SYMBOL("inflateResetKeep") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.8 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("gzvprintf") - EXPORT SYMBOL("inflateGetDictionary") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.9 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32_z") - EXPORT SYMBOL("crc32_z") - EXPORT SYMBOL("deflateGetDictionary") - EXPORT SYMBOL("gzfread") - EXPORT SYMBOL("gzfwrite") - EXPORT SYMBOL("inflateCodesUsed") - EXPORT SYMBOL("inflateValidate") - EXPORT SYMBOL("uncompress2") - -ENDPGMEXP diff --git a/deps/zlib/os400/make.sh b/deps/zlib/os400/make.sh deleted file mode 100644 index 19eec117a678ce..00000000000000 --- a/deps/zlib/os400/make.sh +++ /dev/null @@ -1,366 +0,0 @@ -#!/bin/sh -# -# ZLIB compilation script for the OS/400. -# -# -# This is a shell script since make is not a standard component of OS/400. - - -################################################################################ -# -# Tunable configuration parameters. -# -################################################################################ - -TARGETLIB='ZLIB' # Target OS/400 program library -STATBNDDIR='ZLIB_A' # Static binding directory. -DYNBNDDIR='ZLIB' # Dynamic binding directory. -SRVPGM="ZLIB" # Service program. -IFSDIR='/zlib' # IFS support base directory. -TGTCCSID='500' # Target CCSID of objects -DEBUG='*NONE' # Debug level -OPTIMIZE='40' # Optimisation level -OUTPUT='*NONE' # Compilation output option. -TGTRLS='V6R1M0' # Target OS release - -export TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR -export TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS - - -################################################################################ -# -# OS/400 specific definitions. -# -################################################################################ - -LIBIFSNAME="/QSYS.LIB/${TARGETLIB}.LIB" - - -################################################################################ -# -# Procedures. -# -################################################################################ - -# action_needed dest [src] -# -# dest is an object to build -# if specified, src is an object on which dest depends. -# -# exit 0 (succeeds) if some action has to be taken, else 1. - -action_needed() - -{ - [ ! -e "${1}" ] && return 0 - [ "${2}" ] || return 1 - [ "${1}" -ot "${2}" ] && return 0 - return 1 -} - - -# make_module module_name source_name [additional_definitions] -# -# Compile source name into module if needed. -# As side effect, append the module name to variable MODULES. -# Set LINK to "YES" if the module has been compiled. - -make_module() - -{ - MODULES="${MODULES} ${1}" - MODIFSNAME="${LIBIFSNAME}/${1}.MODULE" - CSRC="`basename \"${2}\"`" - - if action_needed "${MODIFSNAME}" "${2}" - then : - elif [ ! "`sed -e \"//,/<\\\\/source>/!d\" \ - -e '/ tmphdrfile - - # Need to translate to target CCSID. - - CMD="CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')" - CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" - system "${CMD}" - # touch -r "${HFILE}" "${DEST}" - rm -f tmphdrfile - fi - - IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" - - if action_needed "${IFSFILE}" "${DEST}" - then rm -f "${IFSFILE}" - ln -s "${DEST}" "${IFSFILE}" - fi -done - - -# Install the ILE/RPG header file. - - -HFILE="${SCRIPTDIR}/zlib.inc" -DEST="${SRCPF}/ZLIB.INC.MBR" - -if action_needed "${DEST}" "${HFILE}" -then CMD="CPY OBJ('${HFILE}') TOOBJ('${DEST}')" - CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" - system "${CMD}" - # touch -r "${HFILE}" "${DEST}" -fi - -IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" - -if action_needed "${IFSFILE}" "${DEST}" -then rm -f "${IFSFILE}" - ln -s "${DEST}" "${IFSFILE}" -fi - - -# Create and compile the identification source file. - -echo '#pragma comment(user, "ZLIB version '"${VERSION}"'")' > os400.c -echo '#pragma comment(user, __DATE__)' >> os400.c -echo '#pragma comment(user, __TIME__)' >> os400.c -echo '#pragma comment(copyright, "Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.")' >> os400.c -make_module OS400 os400.c -LINK= # No need to rebuild service program yet. -MODULES= - - -# Get source list. - -CSOURCES=`sed -e '/ + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + + #if defined(USE_FILE32API) + #define fopen64 fopen +diff --git a/contrib/minizip/iowin32.c b/contrib/minizip/iowin32.c +index 274f39eb1dd2..246ceb91a139 100644 +--- a/contrib/minizip/iowin32.c ++++ b/contrib/minizip/iowin32.c +@@ -26,12 +26,19 @@ + #endif + + ++#ifdef _WIN32_WINNT ++#undef _WIN32_WINNT ++#define _WIN32_WINNT 0x601 ++#endif ++ ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + // see Include/shared/winapifamily.h in the Windows Kit + #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) + #if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) + #define IOWIN32_USING_WINRT_API 1 + #endif + #endif ++#endif + + voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); + uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +diff --git a/contrib/minizip/mztools.c b/contrib/minizip/mztools.c +index 96891c2e0b71..8bf9cca32633 100644 +--- a/contrib/minizip/mztools.c ++++ b/contrib/minizip/mztools.c +@@ -8,7 +8,7 @@ + #include + #include + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "unzip.h" + + #define READ_8(adr) ((unsigned char)*(adr)) +diff --git a/contrib/minizip/mztools.h b/contrib/minizip/mztools.h +index a49a426ec2fc..f295ffeda6af 100644 +--- a/contrib/minizip/mztools.h ++++ b/contrib/minizip/mztools.h +@@ -12,7 +12,7 @@ extern "C" { + #endif + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #include "unzip.h" +diff --git a/contrib/minizip/unzip.c b/contrib/minizip/unzip.c +index bcfb9416ec35..199b4723fcfc 100644 +--- a/contrib/minizip/unzip.c ++++ b/contrib/minizip/unzip.c +@@ -72,7 +72,7 @@ + #define NOUNCRYPT + #endif + +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "unzip.h" + + #ifdef STDC +@@ -1705,11 +1705,6 @@ extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + +- if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && +- (!(pfile_in_zip_read_info->raw))) +- pfile_in_zip_read_info->stream.avail_out = +- (uInt)pfile_in_zip_read_info->rest_read_uncompressed; +- + if ((len>pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) +diff --git a/contrib/minizip/unzip.h b/contrib/minizip/unzip.h +index 2104e3915074..3c0143529b91 100644 +--- a/contrib/minizip/unzip.h ++++ b/contrib/minizip/unzip.h +@@ -48,7 +48,7 @@ extern "C" { + #endif + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #ifndef _ZLIBIOAPI_H +diff --git a/contrib/minizip/zip.c b/contrib/minizip/zip.c +index 44e88a9cb989..65c0c7251843 100644 +--- a/contrib/minizip/zip.c ++++ b/contrib/minizip/zip.c +@@ -26,7 +26,7 @@ + #include + #include + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "zip.h" + + #ifdef STDC +diff --git a/contrib/minizip/zip.h b/contrib/minizip/zip.h +index 8aaebb623430..8c06c0aa7bb0 100644 +--- a/contrib/minizip/zip.h ++++ b/contrib/minizip/zip.h +@@ -47,7 +47,7 @@ extern "C" { + //#define HAVE_BZIP2 + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #ifndef _ZLIBIOAPI_H +diff --git a/gzread.c b/gzread.c +index 956b91ea7d9e..832d3ef98c59 100644 +--- a/gzread.c ++++ b/gzread.c +@@ -443,7 +443,11 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) + # undef z_gzgetc + #else + # undef gzgetc ++# ifdef Z_CR_PREFIX_SET ++# define gzgetc Cr_z_gzgetc ++# endif + #endif ++ + int ZEXPORT gzgetc(file) + gzFile file; + { +diff --git a/zconf.h b/zconf.h +index 5e1d68a004e9..a7a815f575a7 100644 +--- a/zconf.h ++++ b/zconf.h +@@ -8,6 +8,10 @@ + #ifndef ZCONF_H + #define ZCONF_H + ++/* ++ * This library is also built as a part of AOSP, which does not need to include ++ * chromeconf.h. This config does not want chromeconf.h, so it can set this ++ * macro to opt out. While this works today, there's no guarantee that building ++ * zlib outside of Chromium keeps working in the future. ++ */ ++#if !defined(CHROMIUM_ZLIB_NO_CHROMECONF) ++/* This include does prefixing as below, but with an updated set of names. Also ++ * sets up export macros in component builds. */ ++#include "chromeconf.h" ++#endif ++ + /* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. +@@ -431,7 +434,7 @@ typedef uLong FAR uLongf; + typedef unsigned long z_crc_t; + #endif + +-#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ ++#if !defined(_WIN32) + # define Z_HAVE_UNISTD_H + #endif + +diff --git a/zlib.h b/zlib.h +index f09cdaf1e054..99fd467f6b1a 100644 +--- a/zlib.h ++++ b/zlib.h +@@ -1824,6 +1824,11 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + # undef z_gzgetc + # define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) ++#elif defined(Z_CR_PREFIX_SET) ++# undef gzgetc ++# define gzgetc(g) \ ++ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) \ ++ : (Cr_z_gzgetc)(g)) + #else + # define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +@@ -1853,11 +1858,29 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + # define z_adler32_combine z_adler32_combine64 + # define z_crc32_combine z_crc32_combine64 + # else ++# ifdef gzopen ++# undef gzopen ++# endif + # define gzopen gzopen64 ++# ifdef gzseek ++# undef gzseek ++# endif + # define gzseek gzseek64 ++# ifdef gztell ++# undef gztell ++# endif + # define gztell gztell64 ++# ifdef gzoffset ++# undef gzoffset ++# endif + # define gzoffset gzoffset64 ++# ifdef adler32_combine ++# undef adler32_combine ++# endif + # define adler32_combine adler32_combine64 ++# ifdef crc32_combine ++# undef crc32_combine ++# endif + # define crc32_combine crc32_combine64 + # endif + # ifndef Z_LARGE64 +diff --git a/zutil.h b/zutil.h +index b079ea6a80f5..80375b8b6109 100644 +--- a/zutil.h ++++ b/zutil.h +@@ -28,6 +28,21 @@ + # include + # include + #endif ++#ifdef NO_ERRNO_H ++# ifdef _WIN32_WCE ++ /* The Microsoft C Run-Time Library for Windows CE doesn't have ++ * errno. We define it as a global variable to simplify porting. ++ * Its value is always 0 and should not be used. We rename it to ++ * avoid conflict with other libraries that use the same workaround. ++ */ ++# define errno z_errno ++# endif ++ extern int errno; ++#else ++# ifndef _WIN32_WCE ++# include ++# endif ++#endif + + #ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ diff --git a/deps/zlib/patches/0001-simd.patch b/deps/zlib/patches/0001-simd.patch new file mode 100644 index 00000000000000..9434ca0cc4a68c --- /dev/null +++ b/deps/zlib/patches/0001-simd.patch @@ -0,0 +1,1214 @@ +diff --git a/crc32.c b/crc32.c +index 9580440c0e6b..9162429cc7b4 100644 +--- a/crc32.c ++++ b/crc32.c +@@ -28,6 +28,8 @@ + # endif /* !DYNAMIC_CRC_TABLE */ + #endif /* MAKECRCH */ + ++#include "deflate.h" ++#include "x86.h" + #include "zutil.h" /* for STDC and FAR definitions */ + + /* Definitions for doing the crc four data bytes at a time. */ +@@ -440,3 +442,28 @@ uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + { + return crc32_combine_(crc1, crc2, len2); + } ++ ++ZLIB_INTERNAL void crc_reset(deflate_state *const s) ++{ ++ if (x86_cpu_enable_simd) { ++ crc_fold_init(s); ++ return; ++ } ++ s->strm->adler = crc32(0L, Z_NULL, 0); ++} ++ ++ZLIB_INTERNAL void crc_finalize(deflate_state *const s) ++{ ++ if (x86_cpu_enable_simd) ++ s->strm->adler = crc_fold_512to32(s); ++} ++ ++ZLIB_INTERNAL void copy_with_crc(z_streamp strm, Bytef *dst, long size) ++{ ++ if (x86_cpu_enable_simd) { ++ crc_fold_copy(strm->state, dst, strm->next_in, size); ++ return; ++ } ++ zmemcpy(dst, strm->next_in, size); ++ strm->adler = crc32(strm->adler, dst, size); ++} +diff --git a/crc_folding.c b/crc_folding.c +new file mode 100644 +index 000000000000..48d77744aaf4 +--- /dev/null ++++ b/crc_folding.c +@@ -0,0 +1,493 @@ ++/* ++ * Compute the CRC32 using a parallelized folding approach with the PCLMULQDQ ++ * instruction. ++ * ++ * A white paper describing this algorithm can be found at: ++ * http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf ++ * ++ * Copyright (C) 2013 Intel Corporation. All rights reserved. ++ * Authors: ++ * Wajdi Feghali ++ * Jim Guilford ++ * Vinodh Gopal ++ * Erdinc Ozturk ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include "deflate.h" ++ ++#include ++#include ++#include ++#include ++ ++#define CRC_LOAD(s) \ ++ do { \ ++ __m128i xmm_crc0 = _mm_loadu_si128((__m128i *)s->crc0 + 0);\ ++ __m128i xmm_crc1 = _mm_loadu_si128((__m128i *)s->crc0 + 1);\ ++ __m128i xmm_crc2 = _mm_loadu_si128((__m128i *)s->crc0 + 2);\ ++ __m128i xmm_crc3 = _mm_loadu_si128((__m128i *)s->crc0 + 3);\ ++ __m128i xmm_crc_part = _mm_loadu_si128((__m128i *)s->crc0 + 4); ++ ++#define CRC_SAVE(s) \ ++ _mm_storeu_si128((__m128i *)s->crc0 + 0, xmm_crc0);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 1, xmm_crc1);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 2, xmm_crc2);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 3, xmm_crc3);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 4, xmm_crc_part);\ ++ } while (0); ++ ++ZLIB_INTERNAL void crc_fold_init(deflate_state *const s) ++{ ++ CRC_LOAD(s) ++ ++ xmm_crc0 = _mm_cvtsi32_si128(0x9db42487); ++ xmm_crc1 = _mm_setzero_si128(); ++ xmm_crc2 = _mm_setzero_si128(); ++ xmm_crc3 = _mm_setzero_si128(); ++ ++ CRC_SAVE(s) ++ ++ s->strm->adler = 0; ++} ++ ++local void fold_1(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3; ++ __m128 ps_crc0, ps_crc3, ps_res; ++ ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc3 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_res = _mm_xor_ps(ps_crc0, ps_crc3); ++ ++ *xmm_crc0 = *xmm_crc1; ++ *xmm_crc1 = *xmm_crc2; ++ *xmm_crc2 = x_tmp3; ++ *xmm_crc3 = _mm_castps_si128(ps_res); ++} ++ ++local void fold_2(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3, x_tmp2; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res31, ps_res20; ++ ++ x_tmp3 = *xmm_crc3; ++ x_tmp2 = *xmm_crc2; ++ ++ *xmm_crc3 = *xmm_crc1; ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_res31= _mm_xor_ps(ps_crc3, ps_crc1); ++ ++ *xmm_crc2 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_res20= _mm_xor_ps(ps_crc0, ps_crc2); ++ ++ *xmm_crc0 = x_tmp2; ++ *xmm_crc1 = x_tmp3; ++ *xmm_crc2 = _mm_castps_si128(ps_res20); ++ *xmm_crc3 = _mm_castps_si128(ps_res31); ++} ++ ++local void fold_3(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res32, ps_res21, ps_res10; ++ ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc3 = *xmm_crc2; ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_res32 = _mm_xor_ps(ps_crc2, ps_crc3); ++ ++ *xmm_crc2 = *xmm_crc1; ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_res21= _mm_xor_ps(ps_crc1, ps_crc2); ++ ++ *xmm_crc1 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_res10= _mm_xor_ps(ps_crc0, ps_crc1); ++ ++ *xmm_crc0 = x_tmp3; ++ *xmm_crc1 = _mm_castps_si128(ps_res10); ++ *xmm_crc2 = _mm_castps_si128(ps_res21); ++ *xmm_crc3 = _mm_castps_si128(ps_res32); ++} ++ ++local void fold_4(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp0, x_tmp1, x_tmp2, x_tmp3; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3; ++ __m128 ps_t0, ps_t1, ps_t2, ps_t3; ++ __m128 ps_res0, ps_res1, ps_res2, ps_res3; ++ ++ x_tmp0 = *xmm_crc0; ++ x_tmp1 = *xmm_crc1; ++ x_tmp2 = *xmm_crc2; ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ x_tmp0 = _mm_clmulepi64_si128(x_tmp0, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_t0 = _mm_castsi128_ps(x_tmp0); ++ ps_res0 = _mm_xor_ps(ps_crc0, ps_t0); ++ ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ x_tmp1 = _mm_clmulepi64_si128(x_tmp1, xmm_fold4, 0x10); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_t1 = _mm_castsi128_ps(x_tmp1); ++ ps_res1 = _mm_xor_ps(ps_crc1, ps_t1); ++ ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); ++ x_tmp2 = _mm_clmulepi64_si128(x_tmp2, xmm_fold4, 0x10); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_t2 = _mm_castsi128_ps(x_tmp2); ++ ps_res2 = _mm_xor_ps(ps_crc2, ps_t2); ++ ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x01); ++ x_tmp3 = _mm_clmulepi64_si128(x_tmp3, xmm_fold4, 0x10); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_t3 = _mm_castsi128_ps(x_tmp3); ++ ps_res3 = _mm_xor_ps(ps_crc3, ps_t3); ++ ++ *xmm_crc0 = _mm_castps_si128(ps_res0); ++ *xmm_crc1 = _mm_castps_si128(ps_res1); ++ *xmm_crc2 = _mm_castps_si128(ps_res2); ++ *xmm_crc3 = _mm_castps_si128(ps_res3); ++} ++ ++local const unsigned zalign(32) pshufb_shf_table[60] = { ++ 0x84838281,0x88878685,0x8c8b8a89,0x008f8e8d, /* shl 15 (16 - 1)/shr1 */ ++ 0x85848382,0x89888786,0x8d8c8b8a,0x01008f8e, /* shl 14 (16 - 3)/shr2 */ ++ 0x86858483,0x8a898887,0x8e8d8c8b,0x0201008f, /* shl 13 (16 - 4)/shr3 */ ++ 0x87868584,0x8b8a8988,0x8f8e8d8c,0x03020100, /* shl 12 (16 - 4)/shr4 */ ++ 0x88878685,0x8c8b8a89,0x008f8e8d,0x04030201, /* shl 11 (16 - 5)/shr5 */ ++ 0x89888786,0x8d8c8b8a,0x01008f8e,0x05040302, /* shl 10 (16 - 6)/shr6 */ ++ 0x8a898887,0x8e8d8c8b,0x0201008f,0x06050403, /* shl 9 (16 - 7)/shr7 */ ++ 0x8b8a8988,0x8f8e8d8c,0x03020100,0x07060504, /* shl 8 (16 - 8)/shr8 */ ++ 0x8c8b8a89,0x008f8e8d,0x04030201,0x08070605, /* shl 7 (16 - 9)/shr9 */ ++ 0x8d8c8b8a,0x01008f8e,0x05040302,0x09080706, /* shl 6 (16 -10)/shr10*/ ++ 0x8e8d8c8b,0x0201008f,0x06050403,0x0a090807, /* shl 5 (16 -11)/shr11*/ ++ 0x8f8e8d8c,0x03020100,0x07060504,0x0b0a0908, /* shl 4 (16 -12)/shr12*/ ++ 0x008f8e8d,0x04030201,0x08070605,0x0c0b0a09, /* shl 3 (16 -13)/shr13*/ ++ 0x01008f8e,0x05040302,0x09080706,0x0d0c0b0a, /* shl 2 (16 -14)/shr14*/ ++ 0x0201008f,0x06050403,0x0a090807,0x0e0d0c0b /* shl 1 (16 -15)/shr15*/ ++}; ++ ++local void partial_fold(deflate_state *const s, const size_t len, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3, ++ __m128i *xmm_crc_part) ++{ ++ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ const __m128i xmm_mask3 = _mm_set1_epi32(0x80808080); ++ ++ __m128i xmm_shl, xmm_shr, xmm_tmp1, xmm_tmp2, xmm_tmp3; ++ __m128i xmm_a0_0, xmm_a0_1; ++ __m128 ps_crc3, psa0_0, psa0_1, ps_res; ++ ++ xmm_shl = _mm_load_si128((__m128i *)pshufb_shf_table + (len - 1)); ++ xmm_shr = xmm_shl; ++ xmm_shr = _mm_xor_si128(xmm_shr, xmm_mask3); ++ ++ xmm_a0_0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shl); ++ ++ *xmm_crc0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shr); ++ xmm_tmp1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shl); ++ *xmm_crc0 = _mm_or_si128(*xmm_crc0, xmm_tmp1); ++ ++ *xmm_crc1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shr); ++ xmm_tmp2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shl); ++ *xmm_crc1 = _mm_or_si128(*xmm_crc1, xmm_tmp2); ++ ++ *xmm_crc2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shr); ++ xmm_tmp3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shl); ++ *xmm_crc2 = _mm_or_si128(*xmm_crc2, xmm_tmp3); ++ ++ *xmm_crc3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shr); ++ *xmm_crc_part = _mm_shuffle_epi8(*xmm_crc_part, xmm_shl); ++ *xmm_crc3 = _mm_or_si128(*xmm_crc3, *xmm_crc_part); ++ ++ xmm_a0_1 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x10); ++ xmm_a0_0 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x01); ++ ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ psa0_0 = _mm_castsi128_ps(xmm_a0_0); ++ psa0_1 = _mm_castsi128_ps(xmm_a0_1); ++ ++ ps_res = _mm_xor_ps(ps_crc3, psa0_0); ++ ps_res = _mm_xor_ps(ps_res, psa0_1); ++ ++ *xmm_crc3 = _mm_castps_si128(ps_res); ++} ++ ++ZLIB_INTERNAL void crc_fold_copy(deflate_state *const s, ++ unsigned char *dst, const unsigned char *src, long len) ++{ ++ unsigned long algn_diff; ++ __m128i xmm_t0, xmm_t1, xmm_t2, xmm_t3; ++ ++ CRC_LOAD(s) ++ ++ if (len < 16) { ++ if (len == 0) ++ return; ++ goto partial; ++ } ++ ++ algn_diff = 0 - (uintptr_t)src & 0xF; ++ if (algn_diff) { ++ xmm_crc_part = _mm_loadu_si128((__m128i *)src); ++ _mm_storeu_si128((__m128i *)dst, xmm_crc_part); ++ ++ dst += algn_diff; ++ src += algn_diff; ++ len -= algn_diff; ++ ++ partial_fold(s, algn_diff, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, ++ &xmm_crc_part); ++ } ++ ++ while ((len -= 64) >= 0) { ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ xmm_t2 = _mm_load_si128((__m128i *)src + 2); ++ xmm_t3 = _mm_load_si128((__m128i *)src + 3); ++ ++ fold_4(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); ++ _mm_storeu_si128((__m128i *)dst + 3, xmm_t3); ++ ++ xmm_crc0 = _mm_xor_si128(xmm_crc0, xmm_t0); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t1); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t3); ++ ++ src += 64; ++ dst += 64; ++ } ++ ++ /* ++ * len = num bytes left - 64 ++ */ ++ if (len + 16 >= 0) { ++ len += 16; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ xmm_t2 = _mm_load_si128((__m128i *)src + 2); ++ ++ fold_3(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); ++ ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t0); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t1); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t2); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 48; ++ src += 48; ++ } else if (len + 32 >= 0) { ++ len += 32; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ ++ fold_2(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t0); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t1); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 32; ++ src += 32; ++ } else if (len + 48 >= 0) { ++ len += 48; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ ++ fold_1(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t0); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 16; ++ src += 16; ++ } else { ++ len += 64; ++ if (len == 0) ++ goto done; ++ } ++ ++partial: ++ ++#if defined(_MSC_VER) ++ /* VS does not permit the use of _mm_set_epi64x in 32-bit builds */ ++ { ++ int32_t parts[4] = {0, 0, 0, 0}; ++ memcpy(&parts, src, len); ++ xmm_crc_part = _mm_set_epi32(parts[3], parts[2], parts[1], parts[0]); ++ } ++#else ++ { ++ int64_t parts[2] = {0, 0}; ++ memcpy(&parts, src, len); ++ xmm_crc_part = _mm_set_epi64x(parts[1], parts[0]); ++ } ++#endif ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_crc_part); ++ partial_fold(s, len, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, ++ &xmm_crc_part); ++done: ++ CRC_SAVE(s) ++} ++ ++local const unsigned zalign(16) crc_k[] = { ++ 0xccaa009e, 0x00000000, /* rk1 */ ++ 0x751997d0, 0x00000001, /* rk2 */ ++ 0xccaa009e, 0x00000000, /* rk5 */ ++ 0x63cd6124, 0x00000001, /* rk6 */ ++ 0xf7011640, 0x00000001, /* rk7 */ ++ 0xdb710640, 0x00000001 /* rk8 */ ++}; ++ ++local const unsigned zalign(16) crc_mask[4] = { ++ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 ++}; ++ ++local const unsigned zalign(16) crc_mask2[4] = { ++ 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF ++}; ++ ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) ++{ ++ const __m128i xmm_mask = _mm_load_si128((__m128i *)crc_mask); ++ const __m128i xmm_mask2 = _mm_load_si128((__m128i *)crc_mask2); ++ ++ unsigned crc; ++ __m128i x_tmp0, x_tmp1, x_tmp2, crc_fold; ++ ++ CRC_LOAD(s) ++ ++ /* ++ * k1 ++ */ ++ crc_fold = _mm_load_si128((__m128i *)crc_k); ++ ++ x_tmp0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x10); ++ xmm_crc0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x01); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, x_tmp0); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_crc0); ++ ++ x_tmp1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x10); ++ xmm_crc1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x01); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, x_tmp1); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_crc1); ++ ++ x_tmp2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x10); ++ xmm_crc2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x01); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, x_tmp2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ ++ /* ++ * k5 ++ */ ++ crc_fold = _mm_load_si128((__m128i *)crc_k + 1); ++ ++ xmm_crc0 = xmm_crc3; ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); ++ xmm_crc0 = _mm_srli_si128(xmm_crc0, 8); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); ++ ++ xmm_crc0 = xmm_crc3; ++ xmm_crc3 = _mm_slli_si128(xmm_crc3, 4); ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); ++ xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask2); ++ ++ /* ++ * k7 ++ */ ++ xmm_crc1 = xmm_crc3; ++ xmm_crc2 = xmm_crc3; ++ crc_fold = _mm_load_si128((__m128i *)crc_k + 2); ++ ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask); ++ ++ xmm_crc2 = xmm_crc3; ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc1); ++ ++ crc = _mm_extract_epi32(xmm_crc3, 2); ++ return ~crc; ++ CRC_SAVE(s) ++} +diff --git a/deflate.c b/deflate.c +index 1ec761448de9..aa0c9c67a6dc 100644 +--- a/deflate.c ++++ b/deflate.c +@@ -48,8 +48,9 @@ + */ + + /* @(#) $Id$ */ +- ++#include + #include "deflate.h" ++#include "x86.h" + + const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +@@ -86,7 +87,7 @@ local block_state deflate_huff OF((deflate_state *s, int flush)); + local void lm_init OF((deflate_state *s)); + local void putShortMSB OF((deflate_state *s, uInt b)); + local void flush_pending OF((z_streamp strm)); +-local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); ++unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); + #ifdef ASMV + # pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ +@@ -100,6 +101,20 @@ local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); + #endif + ++/* From crc32.c */ ++extern void ZLIB_INTERNAL crc_reset(deflate_state *const s); ++extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s); ++extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size); ++ ++#ifdef _MSC_VER ++#define INLINE __inline ++#else ++#define INLINE inline ++#endif ++ ++/* Inline optimisation */ ++local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str); ++ + /* =========================================================================== + * Local data + */ +@@ -162,7 +177,6 @@ local const config configuration_table[10] = { + */ + #define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + +- + /* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return +@@ -173,17 +187,28 @@ local const config configuration_table[10] = { + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ ++local INLINE Pos insert_string_c(deflate_state *const s, const Pos str) ++{ ++ Pos ret; ++ ++ UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]); + #ifdef FASTEST +-#define INSERT_STRING(s, str, match_head) \ +- (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +- match_head = s->head[s->ins_h], \ +- s->head[s->ins_h] = (Pos)(str)) ++ ret = s->head[s->ins_h]; + #else +-#define INSERT_STRING(s, str, match_head) \ +- (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +- match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ +- s->head[s->ins_h] = (Pos)(str)) ++ ret = s->prev[str & s->w_mask] = s->head[s->ins_h]; + #endif ++ s->head[s->ins_h] = str; ++ ++ return ret; ++} ++ ++local INLINE Pos insert_string(deflate_state *const s, const Pos str) ++{ ++ if (x86_cpu_enable_simd) ++ return insert_string_sse(s, str); ++ return insert_string_c(s, str); ++} ++ + + /* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). +@@ -248,6 +273,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + const char *version; + int stream_size; + { ++ unsigned window_padding = 8; + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; +@@ -257,6 +283,8 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + * output size for (length,distance) codes is <= 24 bits. + */ + ++ x86_check_features(); ++ + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; +@@ -313,12 +341,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + +- s->hash_bits = (uInt)memLevel + 7; ++ if (x86_cpu_enable_simd) { ++ s->hash_bits = 15; ++ } else { ++ s->hash_bits = memLevel + 7; ++ } ++ + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + +- s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); ++ s->window = (Bytef *) ZALLOC(strm, ++ s->w_size + window_padding, ++ 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + +@@ -418,11 +453,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { +- UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +-#ifndef FASTEST +- s->prev[str & s->w_mask] = s->head[s->ins_h]; +-#endif +- s->head[s->ins_h] = (Pos)str; ++ insert_string(s, str); + str++; + } while (--n); + s->strstart = str; +@@ -848,7 +879,7 @@ int ZEXPORT deflate (strm, flush) + #ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ +- strm->adler = crc32(0L, Z_NULL, 0); ++ crc_reset(s); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); +@@ -1049,6 +1080,7 @@ int ZEXPORT deflate (strm, flush) + /* Write the trailer */ + #ifdef GZIP + if (s->wrap == 2) { ++ crc_finalize(s); + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); +@@ -1161,7 +1193,7 @@ int ZEXPORT deflateCopy (dest, source) + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +-local unsigned read_buf(strm, buf, size) ++ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +@@ -1173,15 +1205,16 @@ local unsigned read_buf(strm, buf, size) + + strm->avail_in -= len; + +- zmemcpy(buf, strm->next_in, len); +- if (strm->state->wrap == 1) { +- strm->adler = adler32(strm->adler, buf, len); +- } + #ifdef GZIP +- else if (strm->state->wrap == 2) { +- strm->adler = crc32(strm->adler, buf, len); +- } ++ if (strm->state->wrap == 2) ++ copy_with_crc(strm, buf, len); ++ else + #endif ++ { ++ zmemcpy(buf, strm->next_in, len); ++ if (strm->state->wrap == 1) ++ strm->adler = adler32(strm->adler, buf, len); ++ } + strm->next_in += len; + strm->total_in += len; + +@@ -1479,7 +1512,19 @@ local void check_match(s, start, match, length) + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +-local void fill_window(s) ++local void fill_window_c(deflate_state *s); ++ ++local void fill_window(deflate_state *s) ++{ ++ if (x86_cpu_enable_simd) { ++ fill_window_sse(s); ++ return; ++ } ++ ++ fill_window_c(s); ++} ++ ++local void fill_window_c(s) + deflate_state *s; + { + unsigned n; +@@ -1847,7 +1892,7 @@ local block_state deflate_fast(s, flush) + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + + /* Find the longest match, discarding those <= prev_length. +@@ -1878,7 +1923,7 @@ local block_state deflate_fast(s, flush) + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ +@@ -1950,7 +1995,7 @@ local block_state deflate_slow(s, flush) + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + + /* Find the longest match, discarding those <= prev_length. +@@ -2001,7 +2046,7 @@ local block_state deflate_slow(s, flush) + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + } while (--s->prev_length != 0); + s->match_available = 0; +@@ -2161,3 +2206,37 @@ local block_state deflate_huff(s, flush) + FLUSH_BLOCK(s, 0); + return block_done; + } ++ ++/* Safe to inline this as GCC/clang will use inline asm and Visual Studio will ++ * use intrinsic without extra params ++ */ ++local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str) ++{ ++ Pos ret; ++ unsigned *ip, val, h = 0; ++ ++ ip = (unsigned *)&s->window[str]; ++ val = *ip; ++ ++ if (s->level >= 6) ++ val &= 0xFFFFFF; ++ ++/* Windows clang should use inline asm */ ++#if defined(_MSC_VER) && !defined(__clang__) ++ h = _mm_crc32_u32(h, val); ++#elif defined(__i386__) || defined(__amd64__) ++ __asm__ __volatile__ ( ++ "crc32 %1,%0\n\t" ++ : "+r" (h) ++ : "r" (val) ++ ); ++#else ++ /* This should never happen */ ++ assert(0); ++#endif ++ ++ ret = s->head[h & s->hash_mask]; ++ s->head[h & s->hash_mask] = str; ++ s->prev[str & s->w_mask] = ret; ++ return ret; ++} +diff --git a/deflate.h b/deflate.h +index 23ecdd312bc0..ab56df7663b6 100644 +--- a/deflate.h ++++ b/deflate.h +@@ -109,7 +109,7 @@ typedef struct internal_state { + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ +- ++ unsigned zalign(16) crc0[4 * 5]; + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ +@@ -346,4 +346,14 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + flush = _tr_tally(s, distance, length) + #endif + ++/* Functions that are SIMD optimised on x86 */ ++void ZLIB_INTERNAL crc_fold_init(deflate_state* const s); ++void ZLIB_INTERNAL crc_fold_copy(deflate_state* const s, ++ unsigned char* dst, ++ const unsigned char* src, ++ long len); ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state* const s); ++ ++void ZLIB_INTERNAL fill_window_sse(deflate_state* s); ++ + #endif /* DEFLATE_H */ +diff --git a/fill_window_sse.c b/fill_window_sse.c +new file mode 100644 +index 000000000000..949ccce1ba9c +--- /dev/null ++++ b/fill_window_sse.c +@@ -0,0 +1,177 @@ ++/* ++ * Fill Window with SSE2-optimized hash shifting ++ * ++ * Copyright (C) 2013 Intel Corporation ++ * Authors: ++ * Arjan van de Ven ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include ++#include "deflate.h" ++ ++#define UPDATE_HASH(s,h,i) \ ++ {\ ++ if (s->level < 6) { \ ++ h = (3483 * (s->window[i]) +\ ++ 23081* (s->window[i+1]) +\ ++ 6954 * (s->window[i+2]) +\ ++ 20947* (s->window[i+3])) & s->hash_mask;\ ++ } else {\ ++ h = (25881* (s->window[i]) +\ ++ 24674* (s->window[i+1]) +\ ++ 25811* (s->window[i+2])) & s->hash_mask;\ ++ }\ ++ }\ ++ ++extern int deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); ++ ++void fill_window_sse(deflate_state *s) ++{ ++ const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); ++ ++ register unsigned n; ++ register Posf *p; ++ unsigned more; /* Amount of free space at the end of the window. */ ++ uInt wsize = s->w_size; ++ ++ Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); ++ ++ do { ++ more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); ++ ++ /* Deal with !@#$% 64K limit: */ ++ if (sizeof(int) <= 2) { ++ if (more == 0 && s->strstart == 0 && s->lookahead == 0) { ++ more = wsize; ++ ++ } else if (more == (unsigned)(-1)) { ++ /* Very unlikely, but possible on 16 bit machine if ++ * strstart == 0 && lookahead == 1 (input done a byte at time) ++ */ ++ more--; ++ } ++ } ++ ++ /* If the window is almost full and there is insufficient lookahead, ++ * move the upper half to the lower one to make room in the upper half. ++ */ ++ if (s->strstart >= wsize+MAX_DIST(s)) { ++ ++ zmemcpy(s->window, s->window+wsize, (unsigned)wsize); ++ s->match_start -= wsize; ++ s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ ++ s->block_start -= (long) wsize; ++ ++ /* Slide the hash table (could be avoided with 32 bit values ++ at the expense of memory usage). We slide even when level == 0 ++ to keep the hash table consistent if we switch back to level > 0 ++ later. (Using level 0 permanently is not an optimal usage of ++ zlib, so we don't care about this pathological case.) ++ */ ++ n = s->hash_size; ++ p = &s->head[n]; ++ p -= 8; ++ do { ++ __m128i value, result; ++ ++ value = _mm_loadu_si128((__m128i *)p); ++ result = _mm_subs_epu16(value, xmm_wsize); ++ _mm_storeu_si128((__m128i *)p, result); ++ ++ p -= 8; ++ n -= 8; ++ } while (n > 0); ++ ++ n = wsize; ++#ifndef FASTEST ++ p = &s->prev[n]; ++ p -= 8; ++ do { ++ __m128i value, result; ++ ++ value = _mm_loadu_si128((__m128i *)p); ++ result = _mm_subs_epu16(value, xmm_wsize); ++ _mm_storeu_si128((__m128i *)p, result); ++ ++ p -= 8; ++ n -= 8; ++ } while (n > 0); ++#endif ++ more += wsize; ++ } ++ if (s->strm->avail_in == 0) break; ++ ++ /* If there was no sliding: ++ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && ++ * more == window_size - lookahead - strstart ++ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) ++ * => more >= window_size - 2*WSIZE + 2 ++ * In the BIG_MEM or MMAP case (not yet supported), ++ * window_size == input_size + MIN_LOOKAHEAD && ++ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. ++ * Otherwise, window_size == 2*WSIZE so more >= 2. ++ * If there was sliding, more >= WSIZE. So in all cases, more >= 2. ++ */ ++ Assert(more >= 2, "more < 2"); ++ ++ n = deflate_read_buf(s->strm, ++ s->window + s->strstart + s->lookahead, ++ more); ++ s->lookahead += n; ++ ++ /* Initialize the hash value now that we have some input: */ ++ if (s->lookahead >= MIN_MATCH) { ++ uInt str = s->strstart; ++ s->ins_h = s->window[str]; ++ if (str >= 1) ++ UPDATE_HASH(s, s->ins_h, str + 1 - (MIN_MATCH-1)); ++#if MIN_MATCH != 3 ++ Call UPDATE_HASH() MIN_MATCH-3 more times ++#endif ++ } ++ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, ++ * but this is not important since only literal bytes will be emitted. ++ */ ++ ++ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); ++ ++ /* If the WIN_INIT bytes after the end of the current data have never been ++ * written, then zero those bytes in order to avoid memory check reports of ++ * the use of uninitialized (or uninitialised as Julian writes) bytes by ++ * the longest match routines. Update the high water mark for the next ++ * time through here. WIN_INIT is set to MAX_MATCH since the longest match ++ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. ++ */ ++ if (s->high_water < s->window_size) { ++ ulg curr = s->strstart + (ulg)(s->lookahead); ++ ulg init; ++ ++ if (s->high_water < curr) { ++ /* Previous high water mark below current data -- zero WIN_INIT ++ * bytes or up to end of window, whichever is less. ++ */ ++ init = s->window_size - curr; ++ if (init > WIN_INIT) ++ init = WIN_INIT; ++ zmemzero(s->window + curr, (unsigned)init); ++ s->high_water = curr + init; ++ } ++ else if (s->high_water < (ulg)curr + WIN_INIT) { ++ /* High water mark at or above current data, but below current data ++ * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up ++ * to end of window, whichever is less. ++ */ ++ init = (ulg)curr + WIN_INIT - s->high_water; ++ if (init > s->window_size - s->high_water) ++ init = s->window_size - s->high_water; ++ zmemzero(s->window + s->high_water, (unsigned)init); ++ s->high_water += init; ++ } ++ } ++ ++ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, ++ "not enough room for search"); ++} +diff --git a/simd_stub.c b/simd_stub.c +new file mode 100644 +index 000000000000..c6d46051498f +--- /dev/null ++++ b/simd_stub.c +@@ -0,0 +1,35 @@ ++/* simd_stub.c -- stub implementations ++* Copyright (C) 2014 Intel Corporation ++* For conditions of distribution and use, see copyright notice in zlib.h ++*/ ++#include ++ ++#include "deflate.h" ++#include "x86.h" ++ ++int ZLIB_INTERNAL x86_cpu_enable_simd = 0; ++ ++void ZLIB_INTERNAL crc_fold_init(deflate_state *const s) { ++ assert(0); ++} ++ ++void ZLIB_INTERNAL crc_fold_copy(deflate_state *const s, ++ unsigned char *dst, ++ const unsigned char *src, ++ long len) { ++ assert(0); ++} ++ ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) { ++ assert(0); ++ return 0; ++} ++ ++void ZLIB_INTERNAL fill_window_sse(deflate_state *s) ++{ ++ assert(0); ++} ++ ++void x86_check_features(void) ++{ ++} +diff --git a/x86.c b/x86.c +new file mode 100644 +index 000000000000..e56fe8b85a39 +--- /dev/null ++++ b/x86.c +@@ -0,0 +1,92 @@ ++/* ++ * x86 feature check ++ * ++ * Copyright (C) 2013 Intel Corporation. All rights reserved. ++ * Author: ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include "x86.h" ++#include "zutil.h" ++ ++int ZLIB_INTERNAL x86_cpu_enable_simd = 0; ++ ++#ifndef _MSC_VER ++#include ++ ++pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; ++static void _x86_check_features(void); ++ ++void x86_check_features(void) ++{ ++ pthread_once(&cpu_check_inited_once, _x86_check_features); ++} ++ ++static void _x86_check_features(void) ++{ ++ int x86_cpu_has_sse2; ++ int x86_cpu_has_sse42; ++ int x86_cpu_has_pclmulqdq; ++ unsigned eax, ebx, ecx, edx; ++ ++ eax = 1; ++#ifdef __i386__ ++ __asm__ __volatile__ ( ++ "xchg %%ebx, %1\n\t" ++ "cpuid\n\t" ++ "xchg %1, %%ebx\n\t" ++ : "+a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx) ++ ); ++#else ++ __asm__ __volatile__ ( ++ "cpuid\n\t" ++ : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) ++ ); ++#endif /* (__i386__) */ ++ ++ x86_cpu_has_sse2 = edx & 0x4000000; ++ x86_cpu_has_sse42 = ecx & 0x100000; ++ x86_cpu_has_pclmulqdq = ecx & 0x2; ++ ++ x86_cpu_enable_simd = x86_cpu_has_sse2 && ++ x86_cpu_has_sse42 && ++ x86_cpu_has_pclmulqdq; ++} ++#else ++#include ++#include ++ ++static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, ++ PVOID param, ++ PVOID *context); ++static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; ++ ++void x86_check_features(void) ++{ ++ InitOnceExecuteOnce(&cpu_check_inited_once, _x86_check_features, ++ NULL, NULL); ++} ++ ++static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, ++ PVOID param, ++ PVOID *context) ++{ ++ int x86_cpu_has_sse2; ++ int x86_cpu_has_sse42; ++ int x86_cpu_has_pclmulqdq; ++ int regs[4]; ++ ++ __cpuid(regs, 1); ++ ++ x86_cpu_has_sse2 = regs[3] & 0x4000000; ++ x86_cpu_has_sse42= regs[2] & 0x100000; ++ x86_cpu_has_pclmulqdq = regs[2] & 0x2; ++ ++ x86_cpu_enable_simd = x86_cpu_has_sse2 && ++ x86_cpu_has_sse42 && ++ x86_cpu_has_pclmulqdq; ++ return TRUE; ++} ++#endif /* _MSC_VER */ +diff --git a/x86.h b/x86.h +new file mode 100644 +index 000000000000..ebcf10ab09d2 +--- /dev/null ++++ b/x86.h +@@ -0,0 +1,15 @@ ++/* x86.h -- check for x86 CPU features ++* Copyright (C) 2013 Intel Corporation Jim Kukunas ++* For conditions of distribution and use, see copyright notice in zlib.h ++*/ ++ ++#ifndef X86_H ++#define X86_H ++ ++#include "zlib.h" ++ ++extern int x86_cpu_enable_simd; ++ ++void x86_check_features(void); ++ ++#endif /* X86_H */ +diff --git a/zutil.h b/zutil.h +index 80375b8b6109..4425bcf75eb3 100644 +--- a/zutil.h ++++ b/zutil.h +@@ -283,4 +283,10 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + ++#ifdef _MSC_VER ++#define zalign(x) __declspec(align(x)) ++#else ++#define zalign(x) __attribute__((aligned((x)))) ++#endif ++ + #endif /* ZUTIL_H */ diff --git a/deps/zlib/patches/0002-uninitializedcheck.patch b/deps/zlib/patches/0002-uninitializedcheck.patch new file mode 100644 index 00000000000000..7c497839d30b87 --- /dev/null +++ b/deps/zlib/patches/0002-uninitializedcheck.patch @@ -0,0 +1,27 @@ +From 1a03e7aec95d89c659fd91f195b99893b6458cd7 Mon Sep 17 00:00:00 2001 +From: Adenilson Cavalcanti +Date: Wed, 27 Sep 2017 13:59:04 -0700 +Subject: [PATCH] Zlib patch: prevent uninitialized use of state->check + +No need to call the Adler32 checksum function, just set +the struct field to the expected value. + +Upstream bug: madler/zlib#245 +--- + third_party/zlib/inflate.c | 2 +- + 1 files changed, 1 insertion(+), 1 deletions(-) + delete mode 100644 third_party/zlib/patches/0002-uninitializedcheck.patch + +diff --git a/third_party/zlib/inflate.c b/third_party/zlib/inflate.c +index bec9497..5c40cf1 100644 +--- a/third_party/zlib/inflate.c ++++ b/third_party/zlib/inflate.c +@@ -228,7 +228,7 @@ int stream_size; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ +- state->check = adler32(0L, Z_NULL, 0); ++ state->check = 1L; /* 1L is the result of adler32() zero length data */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); diff --git a/deps/zlib/patches/README b/deps/zlib/patches/README new file mode 100644 index 00000000000000..b21d309ff91984 --- /dev/null +++ b/deps/zlib/patches/README @@ -0,0 +1,43 @@ +== Patches applied on top of zlib == + + - 0000-build.patch: changes from the upstream version, mostly related to the + build. + - 0001-simd.patch: integrate Intel SIMD optimizations from + https://github.com/jtkukunas/zlib/ + - 0002-uninitializedcheck.patch: prevent uninitialized use of state->check + +== Procedure to create a patch file == + + Assuming you are working in a new feature branch: + - git format-patch master --stdout > foo.patch # where naming follows a growing + # number plus patch description. + - git add foo.patch + - git commit -a -m "Local patch." + - git rebase -i HEAD~2 # Squashing the second commit + + As patches created in this way will feature a ChangeLog, there is no longer +the need to append this file with a description of what the patch does. This +should help to solve frequent conflicts in pending new patches on +Chromium's zlib. + + The plan for the near future is to better insulate the platform specific +changes to ease update adoption with new releases of zlib. This insulation +happens by making changes inside contrib/ rather than the root directory +(where conflicts can happen). + + If a change modifies enough things inside the root directory that the +intention is not immediately clear, generate a .patch file to go with your +change. If the change's modifications in the root directory are small, like: + +#ifdef FEATURE_FLAG +use_special_feature(); +#elif +use_default_behavior(); +#endif + + then the intent is clear and a .patch file doesn't need to be generated (since +it would not provide much value). + + Ideally local changes should have a merge request featured in either: + - canonical zlib: https://github.com/madler/zlib/ + - zlib-ng: https://github.com/Dead2/zlib-ng diff --git a/deps/zlib/qnx/package.qpg b/deps/zlib/qnx/package.qpg deleted file mode 100644 index 31e8e90db4dcd9..00000000000000 --- a/deps/zlib/qnx/package.qpg +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Library - - Medium - - 2.0 - - - - zlib - zlib - alain.bonnefoy@icbt.com - Public - public - www.gzip.org/zlib - - - Jean-Loup Gailly,Mark Adler - www.gzip.org/zlib - - zlib@gzip.org - - - A massively spiffy yet delicately unobtrusive compression library. - zlib is designed to be a free, general-purpose, legally unencumbered, lossless data compression library for use on virtually any computer hardware and operating system. - http://www.gzip.org/zlib - - - - - 1.2.11 - Medium - Stable - - - - - - - No License - - - - Software Development/Libraries and Extensions/C Libraries - zlib,compression - qnx6 - qnx6 - None - Developer - - - - - - - - - - - - - - Install - Post - No - Ignore - - No - Optional - - - - - - - - - - - - - InstallOver - zlib - - - - - - - - - - - - - InstallOver - zlib-dev - - - - - - - - - diff --git a/deps/zlib/simd_stub.c b/deps/zlib/simd_stub.c new file mode 100644 index 00000000000000..c6d46051498f36 --- /dev/null +++ b/deps/zlib/simd_stub.c @@ -0,0 +1,35 @@ +/* simd_stub.c -- stub implementations +* Copyright (C) 2014 Intel Corporation +* For conditions of distribution and use, see copyright notice in zlib.h +*/ +#include + +#include "deflate.h" +#include "x86.h" + +int ZLIB_INTERNAL x86_cpu_enable_simd = 0; + +void ZLIB_INTERNAL crc_fold_init(deflate_state *const s) { + assert(0); +} + +void ZLIB_INTERNAL crc_fold_copy(deflate_state *const s, + unsigned char *dst, + const unsigned char *src, + long len) { + assert(0); +} + +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) { + assert(0); + return 0; +} + +void ZLIB_INTERNAL fill_window_sse(deflate_state *s) +{ + assert(0); +} + +void x86_check_features(void) +{ +} diff --git a/deps/zlib/test/example.c b/deps/zlib/test/example.c deleted file mode 100644 index eee17ce7c1591f..00000000000000 --- a/deps/zlib/test/example.c +++ /dev/null @@ -1,602 +0,0 @@ -/* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2006, 2011, 2016 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#if defined(VMS) || defined(RISCOS) -# define TESTFILE "foo-gz" -#else -# define TESTFILE "foo.gz" -#endif - -#define CHECK_ERR(err, msg) { \ - if (err != Z_OK) { \ - fprintf(stderr, "%s error: %d\n", msg, err); \ - exit(1); \ - } \ -} - -static z_const char hello[] = "hello, hello!"; -/* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - */ - -static const char dictionary[] = "hello"; -static uLong dictId; /* Adler32 value of the dictionary */ - -void test_deflate OF((Byte *compr, uLong comprLen)); -void test_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_deflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_flush OF((Byte *compr, uLong *comprLen)); -void test_sync OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_dict_deflate OF((Byte *compr, uLong comprLen)); -void test_dict_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -int main OF((int argc, char *argv[])); - - -#ifdef Z_SOLO - -void *myalloc OF((void *, unsigned, unsigned)); -void myfree OF((void *, void *)); - -void *myalloc(q, n, m) - void *q; - unsigned n, m; -{ - (void)q; - return calloc(n, m); -} - -void myfree(void *q, void *p) -{ - (void)q; - free(p); -} - -static alloc_func zalloc = myalloc; -static free_func zfree = myfree; - -#else /* !Z_SOLO */ - -static alloc_func zalloc = (alloc_func)0; -static free_func zfree = (free_func)0; - -void test_compress OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_gzio OF((const char *fname, - Byte *uncompr, uLong uncomprLen)); - -/* =========================================================================== - * Test compress() and uncompress() - */ -void test_compress(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - uLong len = (uLong)strlen(hello)+1; - - err = compress(compr, &comprLen, (const Bytef*)hello, len); - CHECK_ERR(err, "compress"); - - strcpy((char*)uncompr, "garbage"); - - err = uncompress(uncompr, &uncomprLen, compr, comprLen); - CHECK_ERR(err, "uncompress"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad uncompress\n"); - exit(1); - } else { - printf("uncompress(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test read/write of .gz files - */ -void test_gzio(fname, uncompr, uncomprLen) - const char *fname; /* compressed file name */ - Byte *uncompr; - uLong uncomprLen; -{ -#ifdef NO_GZCOMPRESS - fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); -#else - int err; - int len = (int)strlen(hello)+1; - gzFile file; - z_off_t pos; - - file = gzopen(fname, "wb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - gzputc(file, 'h'); - if (gzputs(file, "ello") != 4) { - fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); - exit(1); - } - if (gzprintf(file, ", %s!", "hello") != 8) { - fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); - exit(1); - } - gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ - gzclose(file); - - file = gzopen(fname, "rb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - strcpy((char*)uncompr, "garbage"); - - if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { - fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); - exit(1); - } else { - printf("gzread(): %s\n", (char*)uncompr); - } - - pos = gzseek(file, -8L, SEEK_CUR); - if (pos != 6 || gztell(file) != pos) { - fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", - (long)pos, (long)gztell(file)); - exit(1); - } - - if (gzgetc(file) != ' ') { - fprintf(stderr, "gzgetc error\n"); - exit(1); - } - - if (gzungetc(' ', file) != ' ') { - fprintf(stderr, "gzungetc error\n"); - exit(1); - } - - gzgets(file, (char*)uncompr, (int)uncomprLen); - if (strlen((char*)uncompr) != 7) { /* " hello!" */ - fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello + 6)) { - fprintf(stderr, "bad gzgets after gzseek\n"); - exit(1); - } else { - printf("gzgets() after gzseek: %s\n", (char*)uncompr); - } - - gzclose(file); -#endif -} - -#endif /* Z_SOLO */ - -/* =========================================================================== - * Test deflate() with small buffers - */ -void test_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uLong len = (uLong)strlen(hello)+1; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.next_out = compr; - - while (c_stream.total_in != len && c_stream.total_out < comprLen) { - c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - } - /* Finish the stream, still forcing small buffers: */ - for (;;) { - c_stream.avail_out = 1; - err = deflate(&c_stream, Z_FINISH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "deflate"); - } - - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with small buffers - */ -void test_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 0; - d_stream.next_out = uncompr; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { - d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate\n"); - exit(1); - } else { - printf("inflate(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test deflate() with large buffers and dynamic change of compression level - */ -void test_large_deflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_SPEED); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - /* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - */ - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - if (c_stream.avail_in != 0) { - fprintf(stderr, "deflate not greedy\n"); - exit(1); - } - - /* Feed in already compressed data and switch to no compression: */ - deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in = compr; - c_stream.avail_in = (uInt)comprLen/2; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - /* Switch back to compressing mode: */ - deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with large buffers - */ -void test_large_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - for (;;) { - d_stream.next_out = uncompr; /* discard the output */ - d_stream.avail_out = (uInt)uncomprLen; - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "large inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (d_stream.total_out != 2*uncomprLen + comprLen/2) { - fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); - exit(1); - } else { - printf("large_inflate(): OK\n"); - } -} - -/* =========================================================================== - * Test deflate() with full flush - */ -void test_flush(compr, comprLen) - Byte *compr; - uLong *comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uInt len = (uInt)strlen(hello)+1; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.next_out = compr; - c_stream.avail_in = 3; - c_stream.avail_out = (uInt)*comprLen; - err = deflate(&c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, "deflate"); - - compr[3]++; /* force an error in first compressed block */ - c_stream.avail_in = len - 3; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - CHECK_ERR(err, "deflate"); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); - - *comprLen = c_stream.total_out; -} - -/* =========================================================================== - * Test inflateSync() - */ -void test_sync(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 2; /* just read the zlib header */ - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - err = inflate(&d_stream, Z_NO_FLUSH); - CHECK_ERR(err, "inflate"); - - d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ - err = inflateSync(&d_stream); /* but skip the damaged part */ - CHECK_ERR(err, "inflateSync"); - - err = inflate(&d_stream, Z_FINISH); - if (err != Z_DATA_ERROR) { - fprintf(stderr, "inflate should report DATA_ERROR\n"); - /* Because of incorrect adler32 */ - exit(1); - } - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - printf("after inflateSync(): hel%s\n", (char *)uncompr); -} - -/* =========================================================================== - * Test deflate() with preset dictionary - */ -void test_dict_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - err = deflateSetDictionary(&c_stream, - (const Bytef*)dictionary, (int)sizeof(dictionary)); - CHECK_ERR(err, "deflateSetDictionary"); - - dictId = c_stream.adler; - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.avail_in = (uInt)strlen(hello)+1; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with a preset dictionary - */ -void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - for (;;) { - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - if (err == Z_NEED_DICT) { - if (d_stream.adler != dictId) { - fprintf(stderr, "unexpected dictionary"); - exit(1); - } - err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, - (int)sizeof(dictionary)); - } - CHECK_ERR(err, "inflate with dict"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate with dict\n"); - exit(1); - } else { - printf("inflate with dictionary: %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Usage: example [output.gz [input.gz]] - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - Byte *compr, *uncompr; - uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ - uLong uncomprLen = comprLen; - static const char* myVersion = ZLIB_VERSION; - - if (zlibVersion()[0] != myVersion[0]) { - fprintf(stderr, "incompatible zlib version\n"); - exit(1); - - } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { - fprintf(stderr, "warning: different zlib version\n"); - } - - printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", - ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); - - compr = (Byte*)calloc((uInt)comprLen, 1); - uncompr = (Byte*)calloc((uInt)uncomprLen, 1); - /* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - */ - if (compr == Z_NULL || uncompr == Z_NULL) { - printf("out of memory\n"); - exit(1); - } - -#ifdef Z_SOLO - (void)argc; - (void)argv; -#else - test_compress(compr, comprLen, uncompr, uncomprLen); - - test_gzio((argc > 1 ? argv[1] : TESTFILE), - uncompr, uncomprLen); -#endif - - test_deflate(compr, comprLen); - test_inflate(compr, comprLen, uncompr, uncomprLen); - - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - - test_flush(compr, &comprLen); - test_sync(compr, comprLen, uncompr, uncomprLen); - comprLen = uncomprLen; - - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - - free(compr); - free(uncompr); - - return 0; -} diff --git a/deps/zlib/test/infcover.c b/deps/zlib/test/infcover.c deleted file mode 100644 index 2be01646cec3c6..00000000000000 --- a/deps/zlib/test/infcover.c +++ /dev/null @@ -1,671 +0,0 @@ -/* infcover.c -- test zlib's inflate routines with full code coverage - * Copyright (C) 2011, 2016 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* to use, do: ./configure --cover && make cover */ - -#include -#include -#include -#include -#include "zlib.h" - -/* get definition of internal structure so we can mess with it (see pull()), - and so we can call inflate_trees() (see cover5()) */ -#define ZLIB_INTERNAL -#include "inftrees.h" -#include "inflate.h" - -#define local static - -/* -- memory tracking routines -- */ - -/* - These memory tracking routines are provided to zlib and track all of zlib's - allocations and deallocations, check for LIFO operations, keep a current - and high water mark of total bytes requested, optionally set a limit on the - total memory that can be allocated, and when done check for memory leaks. - - They are used as follows: - - z_stream strm; - mem_setup(&strm) initializes the memory tracking and sets the - zalloc, zfree, and opaque members of strm to use - memory tracking for all zlib operations on strm - mem_limit(&strm, limit) sets a limit on the total bytes requested -- a - request that exceeds this limit will result in an - allocation failure (returns NULL) -- setting the - limit to zero means no limit, which is the default - after mem_setup() - mem_used(&strm, "msg") prints to stderr "msg" and the total bytes used - mem_high(&strm, "msg") prints to stderr "msg" and the high water mark - mem_done(&strm, "msg") ends memory tracking, releases all allocations - for the tracking as well as leaked zlib blocks, if - any. If there was anything unusual, such as leaked - blocks, non-FIFO frees, or frees of addresses not - allocated, then "msg" and information about the - problem is printed to stderr. If everything is - normal, nothing is printed. mem_done resets the - strm members to Z_NULL to use the default memory - allocation routines on the next zlib initialization - using strm. - */ - -/* these items are strung together in a linked list, one for each allocation */ -struct mem_item { - void *ptr; /* pointer to allocated memory */ - size_t size; /* requested size of allocation */ - struct mem_item *next; /* pointer to next item in list, or NULL */ -}; - -/* this structure is at the root of the linked list, and tracks statistics */ -struct mem_zone { - struct mem_item *first; /* pointer to first item in list, or NULL */ - size_t total, highwater; /* total allocations, and largest total */ - size_t limit; /* memory allocation limit, or 0 if no limit */ - int notlifo, rogue; /* counts of non-LIFO frees and rogue frees */ -}; - -/* memory allocation routine to pass to zlib */ -local void *mem_alloc(void *mem, unsigned count, unsigned size) -{ - void *ptr; - struct mem_item *item; - struct mem_zone *zone = mem; - size_t len = count * (size_t)size; - - /* induced allocation failure */ - if (zone == NULL || (zone->limit && zone->total + len > zone->limit)) - return NULL; - - /* perform allocation using the standard library, fill memory with a - non-zero value to make sure that the code isn't depending on zeros */ - ptr = malloc(len); - if (ptr == NULL) - return NULL; - memset(ptr, 0xa5, len); - - /* create a new item for the list */ - item = malloc(sizeof(struct mem_item)); - if (item == NULL) { - free(ptr); - return NULL; - } - item->ptr = ptr; - item->size = len; - - /* insert item at the beginning of the list */ - item->next = zone->first; - zone->first = item; - - /* update the statistics */ - zone->total += item->size; - if (zone->total > zone->highwater) - zone->highwater = zone->total; - - /* return the allocated memory */ - return ptr; -} - -/* memory free routine to pass to zlib */ -local void mem_free(void *mem, void *ptr) -{ - struct mem_item *item, *next; - struct mem_zone *zone = mem; - - /* if no zone, just do a free */ - if (zone == NULL) { - free(ptr); - return; - } - - /* point next to the item that matches ptr, or NULL if not found -- remove - the item from the linked list if found */ - next = zone->first; - if (next) { - if (next->ptr == ptr) - zone->first = next->next; /* first one is it, remove from list */ - else { - do { /* search the linked list */ - item = next; - next = item->next; - } while (next != NULL && next->ptr != ptr); - if (next) { /* if found, remove from linked list */ - item->next = next->next; - zone->notlifo++; /* not a LIFO free */ - } - - } - } - - /* if found, update the statistics and free the item */ - if (next) { - zone->total -= next->size; - free(next); - } - - /* if not found, update the rogue count */ - else - zone->rogue++; - - /* in any case, do the requested free with the standard library function */ - free(ptr); -} - -/* set up a controlled memory allocation space for monitoring, set the stream - parameters to the controlled routines, with opaque pointing to the space */ -local void mem_setup(z_stream *strm) -{ - struct mem_zone *zone; - - zone = malloc(sizeof(struct mem_zone)); - assert(zone != NULL); - zone->first = NULL; - zone->total = 0; - zone->highwater = 0; - zone->limit = 0; - zone->notlifo = 0; - zone->rogue = 0; - strm->opaque = zone; - strm->zalloc = mem_alloc; - strm->zfree = mem_free; -} - -/* set a limit on the total memory allocation, or 0 to remove the limit */ -local void mem_limit(z_stream *strm, size_t limit) -{ - struct mem_zone *zone = strm->opaque; - - zone->limit = limit; -} - -/* show the current total requested allocations in bytes */ -local void mem_used(z_stream *strm, char *prefix) -{ - struct mem_zone *zone = strm->opaque; - - fprintf(stderr, "%s: %lu allocated\n", prefix, zone->total); -} - -/* show the high water allocation in bytes */ -local void mem_high(z_stream *strm, char *prefix) -{ - struct mem_zone *zone = strm->opaque; - - fprintf(stderr, "%s: %lu high water mark\n", prefix, zone->highwater); -} - -/* release the memory allocation zone -- if there are any surprises, notify */ -local void mem_done(z_stream *strm, char *prefix) -{ - int count = 0; - struct mem_item *item, *next; - struct mem_zone *zone = strm->opaque; - - /* show high water mark */ - mem_high(strm, prefix); - - /* free leftover allocations and item structures, if any */ - item = zone->first; - while (item != NULL) { - free(item->ptr); - next = item->next; - free(item); - item = next; - count++; - } - - /* issue alerts about anything unexpected */ - if (count || zone->total) - fprintf(stderr, "** %s: %lu bytes in %d blocks not freed\n", - prefix, zone->total, count); - if (zone->notlifo) - fprintf(stderr, "** %s: %d frees not LIFO\n", prefix, zone->notlifo); - if (zone->rogue) - fprintf(stderr, "** %s: %d frees not recognized\n", - prefix, zone->rogue); - - /* free the zone and delete from the stream */ - free(zone); - strm->opaque = Z_NULL; - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; -} - -/* -- inflate test routines -- */ - -/* Decode a hexadecimal string, set *len to length, in[] to the bytes. This - decodes liberally, in that hex digits can be adjacent, in which case two in - a row writes a byte. Or they can be delimited by any non-hex character, - where the delimiters are ignored except when a single hex digit is followed - by a delimiter, where that single digit writes a byte. The returned data is - allocated and must eventually be freed. NULL is returned if out of memory. - If the length is not needed, then len can be NULL. */ -local unsigned char *h2b(const char *hex, unsigned *len) -{ - unsigned char *in, *re; - unsigned next, val; - - in = malloc((strlen(hex) + 1) >> 1); - if (in == NULL) - return NULL; - next = 0; - val = 1; - do { - if (*hex >= '0' && *hex <= '9') - val = (val << 4) + *hex - '0'; - else if (*hex >= 'A' && *hex <= 'F') - val = (val << 4) + *hex - 'A' + 10; - else if (*hex >= 'a' && *hex <= 'f') - val = (val << 4) + *hex - 'a' + 10; - else if (val != 1 && val < 32) /* one digit followed by delimiter */ - val += 240; /* make it look like two digits */ - if (val > 255) { /* have two digits */ - in[next++] = val & 0xff; /* save the decoded byte */ - val = 1; /* start over */ - } - } while (*hex++); /* go through the loop with the terminating null */ - if (len != NULL) - *len = next; - re = realloc(in, next); - return re == NULL ? in : re; -} - -/* generic inflate() run, where hex is the hexadecimal input data, what is the - text to include in an error message, step is how much input data to feed - inflate() on each call, or zero to feed it all, win is the window bits - parameter to inflateInit2(), len is the size of the output buffer, and err - is the error code expected from the first inflate() call (the second - inflate() call is expected to return Z_STREAM_END). If win is 47, then - header information is collected with inflateGetHeader(). If a zlib stream - is looking for a dictionary, then an empty dictionary is provided. - inflate() is run until all of the input data is consumed. */ -local void inf(char *hex, char *what, unsigned step, int win, unsigned len, - int err) -{ - int ret; - unsigned have; - unsigned char *in, *out; - z_stream strm, copy; - gz_header head; - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, win); - if (ret != Z_OK) { - mem_done(&strm, what); - return; - } - out = malloc(len); assert(out != NULL); - if (win == 47) { - head.extra = out; - head.extra_max = len; - head.name = out; - head.name_max = len; - head.comment = out; - head.comm_max = len; - ret = inflateGetHeader(&strm, &head); assert(ret == Z_OK); - } - in = h2b(hex, &have); assert(in != NULL); - if (step == 0 || step > have) - step = have; - strm.avail_in = step; - have -= step; - strm.next_in = in; - do { - strm.avail_out = len; - strm.next_out = out; - ret = inflate(&strm, Z_NO_FLUSH); assert(err == 9 || ret == err); - if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_NEED_DICT) - break; - if (ret == Z_NEED_DICT) { - ret = inflateSetDictionary(&strm, in, 1); - assert(ret == Z_DATA_ERROR); - mem_limit(&strm, 1); - ret = inflateSetDictionary(&strm, out, 0); - assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - ((struct inflate_state *)strm.state)->mode = DICT; - ret = inflateSetDictionary(&strm, out, 0); - assert(ret == Z_OK); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_BUF_ERROR); - } - ret = inflateCopy(©, &strm); assert(ret == Z_OK); - ret = inflateEnd(©); assert(ret == Z_OK); - err = 9; /* don't care next time around */ - have += strm.avail_in; - strm.avail_in = step > have ? have : step; - have -= strm.avail_in; - } while (strm.avail_in); - free(in); - free(out); - ret = inflateReset2(&strm, -8); assert(ret == Z_OK); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, what); -} - -/* cover all of the lines in inflate.c up to inflate() */ -local void cover_support(void) -{ - int ret; - z_stream strm; - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); assert(ret == Z_OK); - mem_used(&strm, "inflate init"); - ret = inflatePrime(&strm, 5, 31); assert(ret == Z_OK); - ret = inflatePrime(&strm, -1, 0); assert(ret == Z_OK); - ret = inflateSetDictionary(&strm, Z_NULL, 0); - assert(ret == Z_STREAM_ERROR); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "prime"); - - inf("63 0", "force window allocation", 0, -15, 1, Z_OK); - inf("63 18 5", "force window replacement", 0, -8, 259, Z_OK); - inf("63 18 68 30 d0 0 0", "force split window update", 4, -8, 259, Z_OK); - inf("3 0", "use fixed blocks", 0, -15, 1, Z_STREAM_END); - inf("", "bad window size", 0, 1, 0, Z_STREAM_ERROR); - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit_(&strm, ZLIB_VERSION - 1, (int)sizeof(z_stream)); - assert(ret == Z_VERSION_ERROR); - mem_done(&strm, "wrong version"); - - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); assert(ret == Z_OK); - ret = inflateEnd(&strm); assert(ret == Z_OK); - fputs("inflate built-in memory routines\n", stderr); -} - -/* cover all inflate() header and trailer cases and code after inflate() */ -local void cover_wrap(void) -{ - int ret; - z_stream strm, copy; - unsigned char dict[257]; - - ret = inflate(Z_NULL, 0); assert(ret == Z_STREAM_ERROR); - ret = inflateEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); - ret = inflateCopy(Z_NULL, Z_NULL); assert(ret == Z_STREAM_ERROR); - fputs("inflate bad parameters\n", stderr); - - inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR); - inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR); - inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR); - inf("8 99", "set window size from header", 0, 0, 0, Z_OK); - inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR); - inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END); - inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1, - Z_DATA_ERROR); - inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length", - 0, 47, 0, Z_STREAM_END); - inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR); - inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT); - inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK); - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -8); - strm.avail_in = 2; - strm.next_in = (void *)"\x63"; - strm.avail_out = 1; - strm.next_out = (void *)&ret; - mem_limit(&strm, 1); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - memset(dict, 0, 257); - ret = inflateSetDictionary(&strm, dict, 257); - assert(ret == Z_OK); - mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256); - ret = inflatePrime(&strm, 16, 0); assert(ret == Z_OK); - strm.avail_in = 2; - strm.next_in = (void *)"\x80"; - ret = inflateSync(&strm); assert(ret == Z_DATA_ERROR); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_STREAM_ERROR); - strm.avail_in = 4; - strm.next_in = (void *)"\0\0\xff\xff"; - ret = inflateSync(&strm); assert(ret == Z_OK); - (void)inflateSyncPoint(&strm); - ret = inflateCopy(©, &strm); assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - ret = inflateUndermine(&strm, 1); assert(ret == Z_DATA_ERROR); - (void)inflateMark(&strm); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "miscellaneous, force memory errors"); -} - -/* input and output functions for inflateBack() */ -local unsigned pull(void *desc, unsigned char **buf) -{ - static unsigned int next = 0; - static unsigned char dat[] = {0x63, 0, 2, 0}; - struct inflate_state *state; - - if (desc == Z_NULL) { - next = 0; - return 0; /* no input (already provided at next_in) */ - } - state = (void *)((z_stream *)desc)->state; - if (state != Z_NULL) - state->mode = SYNC; /* force an otherwise impossible situation */ - return next < sizeof(dat) ? (*buf = dat + next++, 1) : 0; -} - -local int push(void *desc, unsigned char *buf, unsigned len) -{ - buf += len; - return desc != Z_NULL; /* force error if desc not null */ -} - -/* cover inflateBack() up to common deflate data cases and after those */ -local void cover_back(void) -{ - int ret; - z_stream strm; - unsigned char win[32768]; - - ret = inflateBackInit_(Z_NULL, 0, win, 0, 0); - assert(ret == Z_VERSION_ERROR); - ret = inflateBackInit(Z_NULL, 0, win); assert(ret == Z_STREAM_ERROR); - ret = inflateBack(Z_NULL, Z_NULL, Z_NULL, Z_NULL, Z_NULL); - assert(ret == Z_STREAM_ERROR); - ret = inflateBackEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); - fputs("inflateBack bad parameters\n", stderr); - - mem_setup(&strm); - ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); - strm.avail_in = 2; - strm.next_in = (void *)"\x03"; - ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); - assert(ret == Z_STREAM_END); - /* force output error */ - strm.avail_in = 3; - strm.next_in = (void *)"\x63\x00"; - ret = inflateBack(&strm, pull, Z_NULL, push, &strm); - assert(ret == Z_BUF_ERROR); - /* force mode error by mucking with state */ - ret = inflateBack(&strm, pull, &strm, push, Z_NULL); - assert(ret == Z_STREAM_ERROR); - ret = inflateBackEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "inflateBack bad state"); - - ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); - ret = inflateBackEnd(&strm); assert(ret == Z_OK); - fputs("inflateBack built-in memory routines\n", stderr); -} - -/* do a raw inflate of data in hexadecimal with both inflate and inflateBack */ -local int try(char *hex, char *id, int err) -{ - int ret; - unsigned len, size; - unsigned char *in, *out, *win; - char *prefix; - z_stream strm; - - /* convert to hex */ - in = h2b(hex, &len); - assert(in != NULL); - - /* allocate work areas */ - size = len << 3; - out = malloc(size); - assert(out != NULL); - win = malloc(32768); - assert(win != NULL); - prefix = malloc(strlen(id) + 6); - assert(prefix != NULL); - - /* first with inflate */ - strcpy(prefix, id); - strcat(prefix, "-late"); - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, err < 0 ? 47 : -15); - assert(ret == Z_OK); - strm.avail_in = len; - strm.next_in = in; - do { - strm.avail_out = size; - strm.next_out = out; - ret = inflate(&strm, Z_TREES); - assert(ret != Z_STREAM_ERROR && ret != Z_MEM_ERROR); - if (ret == Z_DATA_ERROR || ret == Z_NEED_DICT) - break; - } while (strm.avail_in || strm.avail_out == 0); - if (err) { - assert(ret == Z_DATA_ERROR); - assert(strcmp(id, strm.msg) == 0); - } - inflateEnd(&strm); - mem_done(&strm, prefix); - - /* then with inflateBack */ - if (err >= 0) { - strcpy(prefix, id); - strcat(prefix, "-back"); - mem_setup(&strm); - ret = inflateBackInit(&strm, 15, win); - assert(ret == Z_OK); - strm.avail_in = len; - strm.next_in = in; - ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); - assert(ret != Z_STREAM_ERROR); - if (err) { - assert(ret == Z_DATA_ERROR); - assert(strcmp(id, strm.msg) == 0); - } - inflateBackEnd(&strm); - mem_done(&strm, prefix); - } - - /* clean up */ - free(prefix); - free(win); - free(out); - free(in); - return ret; -} - -/* cover deflate data cases in both inflate() and inflateBack() */ -local void cover_inflate(void) -{ - try("0 0 0 0 0", "invalid stored block lengths", 1); - try("3 0", "fixed", 0); - try("6", "invalid block type", 1); - try("1 1 0 fe ff 0", "stored", 0); - try("fc 0 0", "too many length or distance symbols", 1); - try("4 0 fe ff", "invalid code lengths set", 1); - try("4 0 24 49 0", "invalid bit length repeat", 1); - try("4 0 24 e9 ff ff", "invalid bit length repeat", 1); - try("4 0 24 e9 ff 6d", "invalid code -- missing end-of-block", 1); - try("4 80 49 92 24 49 92 24 71 ff ff 93 11 0", - "invalid literal/lengths set", 1); - try("4 80 49 92 24 49 92 24 f b4 ff ff c3 84", "invalid distances set", 1); - try("4 c0 81 8 0 0 0 0 20 7f eb b 0 0", "invalid literal/length code", 1); - try("2 7e ff ff", "invalid distance code", 1); - try("c c0 81 0 0 0 0 0 90 ff 6b 4 0", "invalid distance too far back", 1); - - /* also trailer mismatch just in inflate() */ - try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1", "incorrect data check", -1); - try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1", - "incorrect length check", -1); - try("5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c", "pull 17", 0); - try("5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f", - "long code", 0); - try("ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f", "length extra", 0); - try("ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c", - "long distance and extra", 0); - try("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", "window end", 0); - inf("2 8 20 80 0 3 0", "inflate_fast TYPE return", 0, -15, 258, - Z_STREAM_END); - inf("63 18 5 40 c 0", "window wrap", 3, -8, 300, Z_OK); -} - -/* cover remaining lines in inftrees.c */ -local void cover_trees(void) -{ - int ret; - unsigned bits; - unsigned short lens[16], work[16]; - code *next, table[ENOUGH_DISTS]; - - /* 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++) - lens[bits] = (unsigned short)(bits + 1); - lens[15] = 15; - next = table; - bits = 15; - ret = inflate_table(DISTS, lens, 16, &next, &bits, work); - assert(ret == 1); - next = table; - bits = 1; - ret = inflate_table(DISTS, lens, 16, &next, &bits, work); - assert(ret == 1); - fputs("inflate_table not enough errors\n", stderr); -} - -/* cover remaining inffast.c decoding and window copying */ -local void cover_fast(void) -{ - inf("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", "fast length extra bits", 0, -8, 258, Z_DATA_ERROR); - inf("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", "fast distance extra bits", 0, -8, 258, - Z_DATA_ERROR); - inf("3 7e 0 0 0 0 0", "fast invalid distance code", 0, -8, 258, - Z_DATA_ERROR); - inf("1b 7 0 0 0 0 0", "fast invalid literal/length code", 0, -8, 258, - Z_DATA_ERROR); - inf("d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0", - "fast 2nd level codes and too far back", 0, -8, 258, Z_DATA_ERROR); - inf("63 18 5 8c 10 8 0 0 0 0", "very common case", 0, -8, 259, Z_OK); - inf("63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0", - "contiguous and wrap around window", 6, -8, 259, Z_OK); - inf("63 0 3 0 0 0 0 0", "copy direct from output", 0, -8, 259, - Z_STREAM_END); -} - -int main(void) -{ - fprintf(stderr, "%s\n", zlibVersion()); - cover_support(); - cover_wrap(); - cover_back(); - cover_inflate(); - cover_trees(); - cover_fast(); - return 0; -} diff --git a/deps/zlib/test/minigzip.c b/deps/zlib/test/minigzip.c deleted file mode 100644 index e22fb08c0a2921..00000000000000 --- a/deps/zlib/test/minigzip.c +++ /dev/null @@ -1,651 +0,0 @@ -/* minigzip.c -- simulate gzip using the zlib compression library - * Copyright (C) 1995-2006, 2010, 2011, 2016 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * minigzip is a minimal implementation of the gzip utility. This is - * only an example of using zlib and isn't meant to replace the - * full-featured gzip. No attempt is made to deal with file systems - * limiting names to 14 or 8+3 characters, etc... Error checking is - * very limited. So use minigzip only for testing; use gzip for the - * real thing. On MSDOS, use only on file names without extension - * or in pipe mode. - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#ifdef USE_MMAP -# include -# include -# include -#endif - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# ifdef UNDER_CE -# include -# endif -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#if defined(_MSC_VER) && _MSC_VER < 1900 -# define snprintf _snprintf -#endif - -#ifdef VMS -# define unlink delete -# define GZ_SUFFIX "-gz" -#endif -#ifdef RISCOS -# define unlink remove -# define GZ_SUFFIX "-gz" -# define fileno(file) file->__file -#endif -#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fileno */ -#endif - -#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) -#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ - extern int unlink OF((const char *)); -#endif -#endif - -#if defined(UNDER_CE) -# include -# define perror(s) pwinerror(s) - -/* Map the Windows error number in ERROR to a locale-dependent error - message string and return a pointer to it. Typically, the values - for ERROR come from GetLastError. - - The string pointed to shall not be modified by the application, - but may be overwritten by a subsequent call to strwinerror - - The strwinerror function does not change the current setting - of GetLastError. */ - -static char *strwinerror (error) - DWORD error; -{ - static char buf[1024]; - - wchar_t *msgbuf; - DWORD lasterr = GetLastError(); - DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, - error, - 0, /* Default language */ - (LPVOID)&msgbuf, - 0, - NULL); - if (chars != 0) { - /* If there is an \r\n appended, zap it. */ - if (chars >= 2 - && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { - chars -= 2; - msgbuf[chars] = 0; - } - - if (chars > sizeof (buf) - 1) { - chars = sizeof (buf) - 1; - msgbuf[chars] = 0; - } - - wcstombs(buf, msgbuf, chars + 1); - LocalFree(msgbuf); - } - else { - sprintf(buf, "unknown win32 error (%ld)", error); - } - - SetLastError(lasterr); - return buf; -} - -static void pwinerror (s) - const char *s; -{ - if (s && *s) - fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); - else - fprintf(stderr, "%s\n", strwinerror(GetLastError ())); -} - -#endif /* UNDER_CE */ - -#ifndef GZ_SUFFIX -# define GZ_SUFFIX ".gz" -#endif -#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) - -#define BUFLEN 16384 -#define MAX_NAME_LEN 1024 - -#ifdef MAXSEG_64K -# define local static - /* Needed for systems with limitation on stack size. */ -#else -# define local -#endif - -#ifdef Z_SOLO -/* for Z_SOLO, create simplified gz* functions using deflate and inflate */ - -#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE) -# include /* for unlink() */ -#endif - -void *myalloc OF((void *, unsigned, unsigned)); -void myfree OF((void *, void *)); - -void *myalloc(q, n, m) - void *q; - unsigned n, m; -{ - (void)q; - return calloc(n, m); -} - -void myfree(q, p) - void *q, *p; -{ - (void)q; - free(p); -} - -typedef struct gzFile_s { - FILE *file; - int write; - int err; - char *msg; - z_stream strm; -} *gzFile; - -gzFile gzopen OF((const char *, const char *)); -gzFile gzdopen OF((int, const char *)); -gzFile gz_open OF((const char *, int, const char *)); - -gzFile gzopen(path, mode) -const char *path; -const char *mode; -{ - return gz_open(path, -1, mode); -} - -gzFile gzdopen(fd, mode) -int fd; -const char *mode; -{ - return gz_open(NULL, fd, mode); -} - -gzFile gz_open(path, fd, mode) - const char *path; - int fd; - const char *mode; -{ - gzFile gz; - int ret; - - gz = malloc(sizeof(struct gzFile_s)); - if (gz == NULL) - return NULL; - gz->write = strchr(mode, 'w') != NULL; - gz->strm.zalloc = myalloc; - gz->strm.zfree = myfree; - gz->strm.opaque = Z_NULL; - if (gz->write) - ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0); - else { - gz->strm.next_in = 0; - gz->strm.avail_in = Z_NULL; - ret = inflateInit2(&(gz->strm), 15 + 16); - } - if (ret != Z_OK) { - free(gz); - return NULL; - } - gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") : - fopen(path, gz->write ? "wb" : "rb"); - if (gz->file == NULL) { - gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm)); - free(gz); - return NULL; - } - gz->err = 0; - gz->msg = ""; - return gz; -} - -int gzwrite OF((gzFile, const void *, unsigned)); - -int gzwrite(gz, buf, len) - gzFile gz; - const void *buf; - unsigned len; -{ - z_stream *strm; - unsigned char out[BUFLEN]; - - if (gz == NULL || !gz->write) - return 0; - strm = &(gz->strm); - strm->next_in = (void *)buf; - strm->avail_in = len; - do { - strm->next_out = out; - strm->avail_out = BUFLEN; - (void)deflate(strm, Z_NO_FLUSH); - fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); - } while (strm->avail_out == 0); - return len; -} - -int gzread OF((gzFile, void *, unsigned)); - -int gzread(gz, buf, len) - gzFile gz; - void *buf; - unsigned len; -{ - int ret; - unsigned got; - unsigned char in[1]; - z_stream *strm; - - if (gz == NULL || gz->write) - return 0; - if (gz->err) - return 0; - strm = &(gz->strm); - strm->next_out = (void *)buf; - strm->avail_out = len; - do { - got = fread(in, 1, 1, gz->file); - if (got == 0) - break; - strm->next_in = in; - strm->avail_in = 1; - ret = inflate(strm, Z_NO_FLUSH); - if (ret == Z_DATA_ERROR) { - gz->err = Z_DATA_ERROR; - gz->msg = strm->msg; - return 0; - } - if (ret == Z_STREAM_END) - inflateReset(strm); - } while (strm->avail_out); - return len - strm->avail_out; -} - -int gzclose OF((gzFile)); - -int gzclose(gz) - gzFile gz; -{ - z_stream *strm; - unsigned char out[BUFLEN]; - - if (gz == NULL) - return Z_STREAM_ERROR; - strm = &(gz->strm); - if (gz->write) { - strm->next_in = Z_NULL; - strm->avail_in = 0; - do { - strm->next_out = out; - strm->avail_out = BUFLEN; - (void)deflate(strm, Z_FINISH); - fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); - } while (strm->avail_out == 0); - deflateEnd(strm); - } - else - inflateEnd(strm); - fclose(gz->file); - free(gz); - return Z_OK; -} - -const char *gzerror OF((gzFile, int *)); - -const char *gzerror(gz, err) - gzFile gz; - int *err; -{ - *err = gz->err; - return gz->msg; -} - -#endif - -static char *prog; - -void error OF((const char *msg)); -void gz_compress OF((FILE *in, gzFile out)); -#ifdef USE_MMAP -int gz_compress_mmap OF((FILE *in, gzFile out)); -#endif -void gz_uncompress OF((gzFile in, FILE *out)); -void file_compress OF((char *file, char *mode)); -void file_uncompress OF((char *file)); -int main OF((int argc, char *argv[])); - -/* =========================================================================== - * Display error message and exit - */ -void error(msg) - const char *msg; -{ - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); -} - -/* =========================================================================== - * Compress input to output then close both files. - */ - -void gz_compress(in, out) - FILE *in; - gzFile out; -{ - local char buf[BUFLEN]; - int len; - int err; - -#ifdef USE_MMAP - /* Try first compressing with mmap. If mmap fails (minigzip used in a - * pipe), use the normal fread loop. - */ - if (gz_compress_mmap(in, out) == Z_OK) return; -#endif - for (;;) { - len = (int)fread(buf, 1, sizeof(buf), in); - if (ferror(in)) { - perror("fread"); - exit(1); - } - if (len == 0) break; - - if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); - } - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); -} - -#ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ - -/* Try compressing the input file at once using mmap. Return Z_OK if - * if success, Z_ERRNO otherwise. - */ -int gz_compress_mmap(in, out) - FILE *in; - gzFile out; -{ - int len; - int err; - int ifd = fileno(in); - caddr_t buf; /* mmap'ed buffer for the entire input file */ - off_t buf_len; /* length of the input file */ - struct stat sb; - - /* Determine the size of the file, needed for mmap: */ - if (fstat(ifd, &sb) < 0) return Z_ERRNO; - buf_len = sb.st_size; - if (buf_len <= 0) return Z_ERRNO; - - /* Now do the actual mmap: */ - buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); - if (buf == (caddr_t)(-1)) return Z_ERRNO; - - /* Compress the whole file at once: */ - len = gzwrite(out, (char *)buf, (unsigned)buf_len); - - if (len != (int)buf_len) error(gzerror(out, &err)); - - munmap(buf, buf_len); - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); - return Z_OK; -} -#endif /* USE_MMAP */ - -/* =========================================================================== - * Uncompress input to output then close both files. - */ -void gz_uncompress(in, out) - gzFile in; - FILE *out; -{ - local char buf[BUFLEN]; - int len; - int err; - - for (;;) { - len = gzread(in, buf, sizeof(buf)); - if (len < 0) error (gzerror(in, &err)); - if (len == 0) break; - - if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { - error("failed fwrite"); - } - } - if (fclose(out)) error("failed fclose"); - - if (gzclose(in) != Z_OK) error("failed gzclose"); -} - - -/* =========================================================================== - * Compress the given file: create a corresponding .gz file and remove the - * original. - */ -void file_compress(file, mode) - char *file; - char *mode; -{ - local char outfile[MAX_NAME_LEN]; - FILE *in; - gzFile out; - - if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(outfile, sizeof(outfile), "%s%s", file, GZ_SUFFIX); -#else - strcpy(outfile, file); - strcat(outfile, GZ_SUFFIX); -#endif - - in = fopen(file, "rb"); - if (in == NULL) { - perror(file); - exit(1); - } - out = gzopen(outfile, mode); - if (out == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); - exit(1); - } - gz_compress(in, out); - - unlink(file); -} - - -/* =========================================================================== - * Uncompress the given file and remove the original. - */ -void file_uncompress(file) - char *file; -{ - local char buf[MAX_NAME_LEN]; - char *infile, *outfile; - FILE *out; - gzFile in; - unsigned len = strlen(file); - - if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(buf, sizeof(buf), "%s", file); -#else - strcpy(buf, file); -#endif - - if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { - infile = file; - outfile = buf; - outfile[len-3] = '\0'; - } else { - outfile = file; - infile = buf; -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(buf + len, sizeof(buf) - len, "%s", GZ_SUFFIX); -#else - strcat(infile, GZ_SUFFIX); -#endif - } - in = gzopen(infile, "rb"); - if (in == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); - exit(1); - } - out = fopen(outfile, "wb"); - if (out == NULL) { - perror(file); - exit(1); - } - - gz_uncompress(in, out); - - unlink(infile); -} - - -/* =========================================================================== - * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] - * -c : write to standard output - * -d : decompress - * -f : compress with Z_FILTERED - * -h : compress with Z_HUFFMAN_ONLY - * -r : compress with Z_RLE - * -1 to -9 : compression level - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - int copyout = 0; - int uncompr = 0; - gzFile file; - char *bname, outmode[20]; - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(outmode, sizeof(outmode), "%s", "wb6 "); -#else - strcpy(outmode, "wb6 "); -#endif - - prog = argv[0]; - bname = strrchr(argv[0], '/'); - if (bname) - bname++; - else - bname = argv[0]; - argc--, argv++; - - if (!strcmp(bname, "gunzip")) - uncompr = 1; - else if (!strcmp(bname, "zcat")) - copyout = uncompr = 1; - - while (argc > 0) { - if (strcmp(*argv, "-c") == 0) - copyout = 1; - else if (strcmp(*argv, "-d") == 0) - uncompr = 1; - else if (strcmp(*argv, "-f") == 0) - outmode[3] = 'f'; - else if (strcmp(*argv, "-h") == 0) - outmode[3] = 'h'; - else if (strcmp(*argv, "-r") == 0) - outmode[3] = 'R'; - else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && - (*argv)[2] == 0) - outmode[2] = (*argv)[1]; - else - break; - argc--, argv++; - } - if (outmode[3] == ' ') - outmode[3] = 0; - if (argc == 0) { - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - if (uncompr) { - file = gzdopen(fileno(stdin), "rb"); - if (file == NULL) error("can't gzdopen stdin"); - gz_uncompress(file, stdout); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - gz_compress(stdin, file); - } - } else { - if (copyout) { - SET_BINARY_MODE(stdout); - } - do { - if (uncompr) { - if (copyout) { - file = gzopen(*argv, "rb"); - if (file == NULL) - fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); - else - gz_uncompress(file, stdout); - } else { - file_uncompress(*argv); - } - } else { - if (copyout) { - FILE * in = fopen(*argv, "rb"); - - if (in == NULL) { - perror(*argv); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - - gz_compress(in, file); - } - - } else { - file_compress(*argv, outmode); - } - } - } while (argv++, --argc); - } - return 0; -} diff --git a/deps/zlib/treebuild.xml b/deps/zlib/treebuild.xml deleted file mode 100644 index fd75525f99595d..00000000000000 --- a/deps/zlib/treebuild.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - zip compression library - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/zlib/trees.c b/deps/zlib/trees.c index 50cf4b4571cfec..5f89d056ef9692 100644 --- a/deps/zlib/trees.c +++ b/deps/zlib/trees.c @@ -416,7 +416,7 @@ local void init_block(s) s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; + s->sym_next = s->matches = 0; } #define SMALLEST 1 @@ -947,7 +947,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); + s->sym_next / 3)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; @@ -1016,8 +1016,9 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; + s->sym_buf[s->sym_next++] = dist; + s->sym_buf[s->sym_next++] = dist >> 8; + s->sym_buf[s->sym_next++] = lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; @@ -1032,30 +1033,7 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ + return (s->sym_next == s->sym_end); } /* =========================================================================== @@ -1068,13 +1046,14 @@ local void compress_block(s, ltree, dtree) { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ + unsigned sx = 0; /* running index in sym_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; + if (s->sym_next != 0) do { + dist = s->sym_buf[sx++] & 0xff; + dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; + lc = s->sym_buf[sx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); @@ -1099,11 +1078,10 @@ local void compress_block(s, ltree, dtree) } } /* literal or match pair ? */ - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); + /* Check that the overlay between pending_buf and sym_buf is ok: */ + Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); - } while (lx < s->last_lit); + } while (sx < s->sym_next); send_code(s, END_BLOCK, ltree); } diff --git a/deps/zlib/watcom/watcom_f.mak b/deps/zlib/watcom/watcom_f.mak deleted file mode 100644 index 37f4d74c19c0a3..00000000000000 --- a/deps/zlib/watcom/watcom_f.mak +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for zlib -# OpenWatcom flat model -# Last updated: 28-Dec-2005 - -# To use, do "wmake -f watcom_f.mak" - -C_SOURCE = adler32.c compress.c crc32.c deflate.c & - gzclose.c gzlib.c gzread.c gzwrite.c & - infback.c inffast.c inflate.c inftrees.c & - trees.c uncompr.c zutil.c - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj & - gzclose.obj gzlib.obj gzread.obj gzwrite.obj & - infback.obj inffast.obj inflate.obj inftrees.obj & - trees.obj uncompr.obj zutil.obj - -CC = wcc386 -LINKER = wcl386 -CFLAGS = -zq -mf -3r -fp3 -s -bt=dos -oilrtfm -fr=nul -wx -ZLIB_LIB = zlib_f.lib - -.C.OBJ: - $(CC) $(CFLAGS) $[@ - -all: $(ZLIB_LIB) example.exe minigzip.exe - -$(ZLIB_LIB): $(OBJS) - wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj - wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj - wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj - wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj - wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj - -example.exe: $(ZLIB_LIB) example.obj - $(LINKER) -ldos32a -fe=example.exe example.obj $(ZLIB_LIB) - -minigzip.exe: $(ZLIB_LIB) minigzip.obj - $(LINKER) -ldos32a -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) - -clean: .SYMBOLIC - del *.obj - del $(ZLIB_LIB) - @echo Cleaning done diff --git a/deps/zlib/watcom/watcom_l.mak b/deps/zlib/watcom/watcom_l.mak deleted file mode 100644 index 193eed7b318a60..00000000000000 --- a/deps/zlib/watcom/watcom_l.mak +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for zlib -# OpenWatcom large model -# Last updated: 28-Dec-2005 - -# To use, do "wmake -f watcom_l.mak" - -C_SOURCE = adler32.c compress.c crc32.c deflate.c & - gzclose.c gzlib.c gzread.c gzwrite.c & - infback.c inffast.c inflate.c inftrees.c & - trees.c uncompr.c zutil.c - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj & - gzclose.obj gzlib.obj gzread.obj gzwrite.obj & - infback.obj inffast.obj inflate.obj inftrees.obj & - trees.obj uncompr.obj zutil.obj - -CC = wcc -LINKER = wcl -CFLAGS = -zq -ml -s -bt=dos -oilrtfm -fr=nul -wx -ZLIB_LIB = zlib_l.lib - -.C.OBJ: - $(CC) $(CFLAGS) $[@ - -all: $(ZLIB_LIB) example.exe minigzip.exe - -$(ZLIB_LIB): $(OBJS) - wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj - wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj - wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj - wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj - wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj - -example.exe: $(ZLIB_LIB) example.obj - $(LINKER) -fe=example.exe example.obj $(ZLIB_LIB) - -minigzip.exe: $(ZLIB_LIB) minigzip.obj - $(LINKER) -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) - -clean: .SYMBOLIC - del *.obj - del $(ZLIB_LIB) - @echo Cleaning done diff --git a/deps/zlib/win32/DLL_FAQ.txt b/deps/zlib/win32/DLL_FAQ.txt deleted file mode 100644 index 12c009018c3775..00000000000000 --- a/deps/zlib/win32/DLL_FAQ.txt +++ /dev/null @@ -1,397 +0,0 @@ - - Frequently Asked Questions about ZLIB1.DLL - - -This document describes the design, the rationale, and the usage -of the official DLL build of zlib, named ZLIB1.DLL. If you have -general questions about zlib, you should see the file "FAQ" found -in the zlib distribution, or at the following location: - http://www.gzip.org/zlib/zlib_faq.html - - - 1. What is ZLIB1.DLL, and how can I get it? - - - ZLIB1.DLL is the official build of zlib as a DLL. - (Please remark the character '1' in the name.) - - Pointers to a precompiled ZLIB1.DLL can be found in the zlib - web site at: - http://www.zlib.net/ - - Applications that link to ZLIB1.DLL can rely on the following - specification: - - * The exported symbols are exclusively defined in the source - files "zlib.h" and "zlib.def", found in an official zlib - source distribution. - * The symbols are exported by name, not by ordinal. - * The exported names are undecorated. - * The calling convention of functions is "C" (CDECL). - * The ZLIB1.DLL binary is linked to MSVCRT.DLL. - - The archive in which ZLIB1.DLL is bundled contains compiled - test programs that must run with a valid build of ZLIB1.DLL. - It is recommended to download the prebuilt DLL from the zlib - web site, instead of building it yourself, to avoid potential - incompatibilities that could be introduced by your compiler - and build settings. If you do build the DLL yourself, please - make sure that it complies with all the above requirements, - and it runs with the precompiled test programs, bundled with - the original ZLIB1.DLL distribution. - - If, for any reason, you need to build an incompatible DLL, - please use a different file name. - - - 2. Why did you change the name of the DLL to ZLIB1.DLL? - What happened to the old ZLIB.DLL? - - - The old ZLIB.DLL, built from zlib-1.1.4 or earlier, required - compilation settings that were incompatible to those used by - a static build. The DLL settings were supposed to be enabled - by defining the macro ZLIB_DLL, before including "zlib.h". - Incorrect handling of this macro was silently accepted at - build time, resulting in two major problems: - - * ZLIB_DLL was missing from the old makefile. When building - the DLL, not all people added it to the build options. In - consequence, incompatible incarnations of ZLIB.DLL started - to circulate around the net. - - * When switching from using the static library to using the - DLL, applications had to define the ZLIB_DLL macro and - to recompile all the sources that contained calls to zlib - functions. Failure to do so resulted in creating binaries - that were unable to run with the official ZLIB.DLL build. - - The only possible solution that we could foresee was to make - a binary-incompatible change in the DLL interface, in order to - remove the dependency on the ZLIB_DLL macro, and to release - the new DLL under a different name. - - We chose the name ZLIB1.DLL, where '1' indicates the major - zlib version number. We hope that we will not have to break - the binary compatibility again, at least not as long as the - zlib-1.x series will last. - - There is still a ZLIB_DLL macro, that can trigger a more - efficient build and use of the DLL, but compatibility no - longer dependents on it. - - - 3. Can I build ZLIB.DLL from the new zlib sources, and replace - an old ZLIB.DLL, that was built from zlib-1.1.4 or earlier? - - - In principle, you can do it by assigning calling convention - keywords to the macros ZEXPORT and ZEXPORTVA. In practice, - it depends on what you mean by "an old ZLIB.DLL", because the - old DLL exists in several mutually-incompatible versions. - You have to find out first what kind of calling convention is - being used in your particular ZLIB.DLL build, and to use the - same one in the new build. If you don't know what this is all - about, you might be better off if you would just leave the old - DLL intact. - - - 4. Can I compile my application using the new zlib interface, and - link it to an old ZLIB.DLL, that was built from zlib-1.1.4 or - earlier? - - - The official answer is "no"; the real answer depends again on - what kind of ZLIB.DLL you have. Even if you are lucky, this - course of action is unreliable. - - If you rebuild your application and you intend to use a newer - version of zlib (post- 1.1.4), it is strongly recommended to - link it to the new ZLIB1.DLL. - - - 5. Why are the zlib symbols exported by name, and not by ordinal? - - - Although exporting symbols by ordinal is a little faster, it - is risky. Any single glitch in the maintenance or use of the - DEF file that contains the ordinals can result in incompatible - builds and frustrating crashes. Simply put, the benefits of - exporting symbols by ordinal do not justify the risks. - - Technically, it should be possible to maintain ordinals in - the DEF file, and still export the symbols by name. Ordinals - exist in every DLL, and even if the dynamic linking performed - at the DLL startup is searching for names, ordinals serve as - hints, for a faster name lookup. However, if the DEF file - contains ordinals, the Microsoft linker automatically builds - an implib that will cause the executables linked to it to use - those ordinals, and not the names. It is interesting to - notice that the GNU linker for Win32 does not suffer from this - problem. - - It is possible to avoid the DEF file if the exported symbols - are accompanied by a "__declspec(dllexport)" attribute in the - source files. You can do this in zlib by predefining the - ZLIB_DLL macro. - - - 6. I see that the ZLIB1.DLL functions use the "C" (CDECL) calling - convention. Why not use the STDCALL convention? - STDCALL is the standard convention in Win32, and I need it in - my Visual Basic project! - - (For readability, we use CDECL to refer to the convention - triggered by the "__cdecl" keyword, STDCALL to refer to - the convention triggered by "__stdcall", and FASTCALL to - refer to the convention triggered by "__fastcall".) - - - Most of the native Windows API functions (without varargs) use - indeed the WINAPI convention (which translates to STDCALL in - Win32), but the standard C functions use CDECL. If a user - application is intrinsically tied to the Windows API (e.g. - it calls native Windows API functions such as CreateFile()), - sometimes it makes sense to decorate its own functions with - WINAPI. But if ANSI C or POSIX portability is a goal (e.g. - it calls standard C functions such as fopen()), it is not a - sound decision to request the inclusion of , or to - use non-ANSI constructs, for the sole purpose to make the user - functions STDCALL-able. - - The functionality offered by zlib is not in the category of - "Windows functionality", but is more like "C functionality". - - Technically, STDCALL is not bad; in fact, it is slightly - faster than CDECL, and it works with variable-argument - functions, just like CDECL. It is unfortunate that, in spite - of using STDCALL in the Windows API, it is not the default - convention used by the C compilers that run under Windows. - The roots of the problem reside deep inside the unsafety of - the K&R-style function prototypes, where the argument types - are not specified; but that is another story for another day. - - The remaining fact is that CDECL is the default convention. - Even if an explicit convention is hard-coded into the function - prototypes inside C headers, problems may appear. The - necessity to expose the convention in users' callbacks is one - of these problems. - - The calling convention issues are also important when using - zlib in other programming languages. Some of them, like Ada - (GNAT) and Fortran (GNU G77), have C bindings implemented - initially on Unix, and relying on the C calling convention. - On the other hand, the pre- .NET versions of Microsoft Visual - Basic require STDCALL, while Borland Delphi prefers, although - it does not require, FASTCALL. - - In fairness to all possible uses of zlib outside the C - programming language, we choose the default "C" convention. - Anyone interested in different bindings or conventions is - encouraged to maintain specialized projects. The "contrib/" - directory from the zlib distribution already holds a couple - of foreign bindings, such as Ada, C++, and Delphi. - - - 7. I need a DLL for my Visual Basic project. What can I do? - - - Define the ZLIB_WINAPI macro before including "zlib.h", when - building both the DLL and the user application (except that - you don't need to define anything when using the DLL in Visual - Basic). The ZLIB_WINAPI macro will switch on the WINAPI - (STDCALL) convention. The name of this DLL must be different - than the official ZLIB1.DLL. - - Gilles Vollant has contributed a build named ZLIBWAPI.DLL, - with the ZLIB_WINAPI macro turned on, and with the minizip - functionality built in. For more information, please read - the notes inside "contrib/vstudio/readme.txt", found in the - zlib distribution. - - - 8. I need to use zlib in my Microsoft .NET project. What can I - do? - - - Henrik Ravn has contributed a .NET wrapper around zlib. Look - into contrib/dotzlib/, inside the zlib distribution. - - - 9. If my application uses ZLIB1.DLL, should I link it to - MSVCRT.DLL? Why? - - - It is not required, but it is recommended to link your - application to MSVCRT.DLL, if it uses ZLIB1.DLL. - - The executables (.EXE, .DLL, etc.) that are involved in the - same process and are using the C run-time library (i.e. they - are calling standard C functions), must link to the same - library. There are several libraries in the Win32 system: - CRTDLL.DLL, MSVCRT.DLL, the static C libraries, etc. - Since ZLIB1.DLL is linked to MSVCRT.DLL, the executables that - depend on it should also be linked to MSVCRT.DLL. - - -10. Why are you saying that ZLIB1.DLL and my application should - be linked to the same C run-time (CRT) library? I linked my - application and my DLLs to different C libraries (e.g. my - application to a static library, and my DLLs to MSVCRT.DLL), - and everything works fine. - - - If a user library invokes only pure Win32 API (accessible via - and the related headers), its DLL build will work - in any context. But if this library invokes standard C API, - things get more complicated. - - There is a single Win32 library in a Win32 system. Every - function in this library resides in a single DLL module, that - is safe to call from anywhere. On the other hand, there are - multiple versions of the C library, and each of them has its - own separate internal state. Standalone executables and user - DLLs that call standard C functions must link to a C run-time - (CRT) library, be it static or shared (DLL). Intermixing - occurs when an executable (not necessarily standalone) and a - DLL are linked to different CRTs, and both are running in the - same process. - - Intermixing multiple CRTs is possible, as long as their - internal states are kept intact. The Microsoft Knowledge Base - articles KB94248 "HOWTO: Use the C Run-Time" and KB140584 - "HOWTO: Link with the Correct C Run-Time (CRT) Library" - mention the potential problems raised by intermixing. - - If intermixing works for you, it's because your application - and DLLs are avoiding the corruption of each of the CRTs' - internal states, maybe by careful design, or maybe by fortune. - - Also note that linking ZLIB1.DLL to non-Microsoft CRTs, such - as those provided by Borland, raises similar problems. - - -11. Why are you linking ZLIB1.DLL to MSVCRT.DLL? - - - MSVCRT.DLL exists on every Windows 95 with a new service pack - installed, or with Microsoft Internet Explorer 4 or later, and - on all other Windows 4.x or later (Windows 98, Windows NT 4, - or later). It is freely distributable; if not present in the - system, it can be downloaded from Microsoft or from other - software provider for free. - - The fact that MSVCRT.DLL does not exist on a virgin Windows 95 - is not so problematic. Windows 95 is scarcely found nowadays, - Microsoft ended its support a long time ago, and many recent - applications from various vendors, including Microsoft, do not - even run on it. Furthermore, no serious user should run - Windows 95 without a proper update installed. - - -12. Why are you not linking ZLIB1.DLL to - <> ? - - - We considered and abandoned the following alternatives: - - * Linking ZLIB1.DLL to a static C library (LIBC.LIB, or - LIBCMT.LIB) is not a good option. People are using the DLL - mainly to save disk space. If you are linking your program - to a static C library, you may as well consider linking zlib - in statically, too. - - * Linking ZLIB1.DLL to CRTDLL.DLL looks appealing, because - CRTDLL.DLL is present on every Win32 installation. - Unfortunately, it has a series of problems: it does not - work properly with Microsoft's C++ libraries, it does not - provide support for 64-bit file offsets, (and so on...), - and Microsoft discontinued its support a long time ago. - - * Linking ZLIB1.DLL to MSVCR70.DLL or MSVCR71.DLL, supplied - with the Microsoft .NET platform, and Visual C++ 7.0/7.1, - raises problems related to the status of ZLIB1.DLL as a - system component. According to the Microsoft Knowledge Base - article KB326922 "INFO: Redistribution of the Shared C - Runtime Component in Visual C++ .NET", MSVCR70.DLL and - MSVCR71.DLL are not supposed to function as system DLLs, - because they may clash with MSVCRT.DLL. Instead, the - application's installer is supposed to put these DLLs - (if needed) in the application's private directory. - If ZLIB1.DLL depends on a non-system runtime, it cannot - function as a redistributable system component. - - * Linking ZLIB1.DLL to non-Microsoft runtimes, such as - Borland's, or Cygwin's, raises problems related to the - reliable presence of these runtimes on Win32 systems. - It's easier to let the DLL build of zlib up to the people - who distribute these runtimes, and who may proceed as - explained in the answer to Question 14. - - -13. If ZLIB1.DLL cannot be linked to MSVCR70.DLL or MSVCR71.DLL, - how can I build/use ZLIB1.DLL in Microsoft Visual C++ 7.0 - (Visual Studio .NET) or newer? - - - Due to the problems explained in the Microsoft Knowledge Base - article KB326922 (see the previous answer), the C runtime that - comes with the VC7 environment is no longer considered a - system component. That is, it should not be assumed that this - runtime exists, or may be installed in a system directory. - Since ZLIB1.DLL is supposed to be a system component, it may - not depend on a non-system component. - - In order to link ZLIB1.DLL and your application to MSVCRT.DLL - in VC7, you need the library of Visual C++ 6.0 or older. If - you don't have this library at hand, it's probably best not to - use ZLIB1.DLL. - - We are hoping that, in the future, Microsoft will provide a - way to build applications linked to a proper system runtime, - from the Visual C++ environment. Until then, you have a - couple of alternatives, such as linking zlib in statically. - If your application requires dynamic linking, you may proceed - as explained in the answer to Question 14. - - -14. I need to link my own DLL build to a CRT different than - MSVCRT.DLL. What can I do? - - - Feel free to rebuild the DLL from the zlib sources, and link - it the way you want. You should, however, clearly state that - your build is unofficial. You should give it a different file - name, and/or install it in a private directory that can be - accessed by your application only, and is not visible to the - others (i.e. it's neither in the PATH, nor in the SYSTEM or - SYSTEM32 directories). Otherwise, your build may clash with - applications that link to the official build. - - For example, in Cygwin, zlib is linked to the Cygwin runtime - CYGWIN1.DLL, and it is distributed under the name CYGZ.DLL. - - -15. May I include additional pieces of code that I find useful, - link them in ZLIB1.DLL, and export them? - - - No. A legitimate build of ZLIB1.DLL must not include code - that does not originate from the official zlib source code. - But you can make your own private DLL build, under a different - file name, as suggested in the previous answer. - - For example, zlib is a part of the VCL library, distributed - with Borland Delphi and C++ Builder. The DLL build of VCL - is a redistributable file, named VCLxx.DLL. - - -16. May I remove some functionality out of ZLIB1.DLL, by enabling - macros like NO_GZCOMPRESS or NO_GZIP at compile time? - - - No. A legitimate build of ZLIB1.DLL must provide the complete - zlib functionality, as implemented in the official zlib source - code. But you can make your own private DLL build, under a - different file name, as suggested in the previous answer. - - -17. I made my own ZLIB1.DLL build. Can I test it for compliance? - - - We prefer that you download the official DLL from the zlib - web site. If you need something peculiar from this DLL, you - can send your suggestion to the zlib mailing list. - - However, in case you do rebuild the DLL yourself, you can run - it with the test programs found in the DLL distribution. - Running these test programs is not a guarantee of compliance, - but a failure can imply a detected problem. - -** - -This document is written and maintained by -Cosmin Truta diff --git a/deps/zlib/win32/Makefile.bor b/deps/zlib/win32/Makefile.bor deleted file mode 100644 index d152bbb7ffd951..00000000000000 --- a/deps/zlib/win32/Makefile.bor +++ /dev/null @@ -1,110 +0,0 @@ -# Makefile for zlib -# Borland C++ for Win32 -# -# Usage: -# make -f win32/Makefile.bor -# make -f win32/Makefile.bor LOCAL_ZLIB=-DASMV OBJA=match.obj OBJPA=+match.obj - -# ------------ Borland C++ ------------ - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or -# added to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -CC = bcc32 -AS = bcc32 -LD = bcc32 -AR = tlib -CFLAGS = -a -d -k- -O2 $(LOC) -ASFLAGS = $(LOC) -LDFLAGS = $(LOC) - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -#OBJA = -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj -#OBJPA= - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $< - -.asm.obj: - $(AS) -c $(ASFLAGS) $< - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) $(OBJA) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - $(AR) $(ZLIB_LIB) $(OBJPA) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del $(ZLIB_LIB) - -del *.obj - -del *.exe - -del *.tds - -del zlib.bak - -del foo.gz diff --git a/deps/zlib/win32/Makefile.gcc b/deps/zlib/win32/Makefile.gcc deleted file mode 100644 index 305be50afef665..00000000000000 --- a/deps/zlib/win32/Makefile.gcc +++ /dev/null @@ -1,182 +0,0 @@ -# Makefile for zlib, derived from Makefile.dj2. -# Modified for mingw32 by C. Spieler, 6/16/98. -# Updated for zlib 1.2.x by Christian Spieler and Cosmin Truta, Mar-2003. -# Last updated: Mar 2012. -# Tested under Cygwin and MinGW. - -# Copyright (C) 1995-2003 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type from the top level zlib directory: -# -# make -fwin32/Makefile.gcc; make test testdll -fwin32/Makefile.gcc -# -# To use the asm code, type: -# cp contrib/asm?86/match.S ./match.S -# make LOC=-DASMV OBJA=match.o -fwin32/Makefile.gcc -# -# To install libz.a, zconf.h and zlib.h in the system directories, type: -# -# make install -fwin32/Makefile.gcc -# -# BINARY_PATH, INCLUDE_PATH and LIBRARY_PATH must be set. -# -# To install the shared lib, append SHARED_MODE=1 to the make command : -# -# make install -fwin32/Makefile.gcc SHARED_MODE=1 - -# Note: -# If the platform is *not* MinGW (e.g. it is Cygwin or UWIN), -# the DLL name should be changed from "zlib1.dll". - -STATICLIB = libz.a -SHAREDLIB = zlib1.dll -IMPLIB = libz.dll.a - -# -# Set to 1 if shared object needs to be installed -# -SHARED_MODE=0 - -#LOC = -DASMV -#LOC = -DZLIB_DEBUG -g - -PREFIX = -CC = $(PREFIX)gcc -CFLAGS = $(LOC) -O3 -Wall - -AS = $(CC) -ASFLAGS = $(LOC) -Wall - -LD = $(CC) -LDFLAGS = $(LOC) - -AR = $(PREFIX)ar -ARFLAGS = rcs - -RC = $(PREFIX)windres -RCFLAGS = --define GCC_WINDRES - -STRIP = $(PREFIX)strip - -CP = cp -fp -# If GNU install is available, replace $(CP) with install. -INSTALL = $(CP) -RM = rm -f - -prefix ?= /usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ - gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o -OBJA = - -all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) example.exe minigzip.exe example_d.exe minigzip_d.exe - -test: example.exe minigzip.exe - ./example - echo hello world | ./minigzip | ./minigzip -d - -testdll: example_d.exe minigzip_d.exe - ./example_d - echo hello world | ./minigzip_d | ./minigzip_d -d - -.c.o: - $(CC) $(CFLAGS) -c -o $@ $< - -.S.o: - $(AS) $(ASFLAGS) -c -o $@ $< - -$(STATICLIB): $(OBJS) $(OBJA) - $(AR) $(ARFLAGS) $@ $(OBJS) $(OBJA) - -$(IMPLIB): $(SHAREDLIB) - -$(SHAREDLIB): win32/zlib.def $(OBJS) $(OBJA) zlibrc.o - $(CC) -shared -Wl,--out-implib,$(IMPLIB) $(LDFLAGS) \ - -o $@ win32/zlib.def $(OBJS) $(OBJA) zlibrc.o - $(STRIP) $@ - -example.exe: example.o $(STATICLIB) - $(LD) $(LDFLAGS) -o $@ example.o $(STATICLIB) - $(STRIP) $@ - -minigzip.exe: minigzip.o $(STATICLIB) - $(LD) $(LDFLAGS) -o $@ minigzip.o $(STATICLIB) - $(STRIP) $@ - -example_d.exe: example.o $(IMPLIB) - $(LD) $(LDFLAGS) -o $@ example.o $(IMPLIB) - $(STRIP) $@ - -minigzip_d.exe: minigzip.o $(IMPLIB) - $(LD) $(LDFLAGS) -o $@ minigzip.o $(IMPLIB) - $(STRIP) $@ - -example.o: test/example.c zlib.h zconf.h - $(CC) $(CFLAGS) -I. -c -o $@ test/example.c - -minigzip.o: test/minigzip.c zlib.h zconf.h - $(CC) $(CFLAGS) -I. -c -o $@ test/minigzip.c - -zlibrc.o: win32/zlib1.rc - $(RC) $(RCFLAGS) -o $@ win32/zlib1.rc - -.PHONY: install uninstall clean - -install: zlib.h zconf.h $(STATICLIB) $(IMPLIB) - @if test -z "$(DESTDIR)$(INCLUDE_PATH)" -o -z "$(DESTDIR)$(LIBRARY_PATH)" -o -z "$(DESTDIR)$(BINARY_PATH)"; then \ - echo INCLUDE_PATH, LIBRARY_PATH, and BINARY_PATH must be specified; \ - exit 1; \ - fi - -@mkdir -p '$(DESTDIR)$(INCLUDE_PATH)' - -@mkdir -p '$(DESTDIR)$(LIBRARY_PATH)' '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig - -if [ "$(SHARED_MODE)" = "1" ]; then \ - mkdir -p '$(DESTDIR)$(BINARY_PATH)'; \ - $(INSTALL) $(SHAREDLIB) '$(DESTDIR)$(BINARY_PATH)'; \ - $(INSTALL) $(IMPLIB) '$(DESTDIR)$(LIBRARY_PATH)'; \ - fi - -$(INSTALL) zlib.h '$(DESTDIR)$(INCLUDE_PATH)' - -$(INSTALL) zconf.h '$(DESTDIR)$(INCLUDE_PATH)' - -$(INSTALL) $(STATICLIB) '$(DESTDIR)$(LIBRARY_PATH)' - sed \ - -e 's|@prefix@|${prefix}|g' \ - -e 's|@exec_prefix@|${exec_prefix}|g' \ - -e 's|@libdir@|$(LIBRARY_PATH)|g' \ - -e 's|@sharedlibdir@|$(LIBRARY_PATH)|g' \ - -e 's|@includedir@|$(INCLUDE_PATH)|g' \ - -e 's|@VERSION@|'`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' zlib.h`'|g' \ - zlib.pc.in > '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig/zlib.pc - -uninstall: - -if [ "$(SHARED_MODE)" = "1" ]; then \ - $(RM) '$(DESTDIR)$(BINARY_PATH)'/$(SHAREDLIB); \ - $(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(IMPLIB); \ - fi - -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zlib.h - -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zconf.h - -$(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(STATICLIB) - -clean: - -$(RM) $(STATICLIB) - -$(RM) $(SHAREDLIB) - -$(RM) $(IMPLIB) - -$(RM) *.o - -$(RM) *.exe - -$(RM) foo.gz - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: crc32.h zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -gzclose.o: zlib.h zconf.h gzguts.h -gzlib.o: zlib.h zconf.h gzguts.h -gzread.o: zlib.h zconf.h gzguts.h -gzwrite.o: zlib.h zconf.h gzguts.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/win32/Makefile.msc b/deps/zlib/win32/Makefile.msc deleted file mode 100644 index 6831882de43e6c..00000000000000 --- a/deps/zlib/win32/Makefile.msc +++ /dev/null @@ -1,163 +0,0 @@ -# Makefile for zlib using Microsoft (Visual) C -# zlib is copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler -# -# Usage: -# nmake -f win32/Makefile.msc (standard build) -# nmake -f win32/Makefile.msc LOC=-DFOO (nonstandard build) -# nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" \ -# OBJA="inffas32.obj match686.obj" (use ASM code, x86) -# nmake -f win32/Makefile.msc AS=ml64 LOC="-DASMV -DASMINF -I." \ -# OBJA="inffasx64.obj gvmat64.obj inffas8664.obj" (use ASM code, x64) - -# The toplevel directory of the source tree. -# -TOP = . - -# optional build flags -LOC = - -# variables -STATICLIB = zlib.lib -SHAREDLIB = zlib1.dll -IMPLIB = zdll.lib - -CC = cl -AS = ml -LD = link -AR = lib -RC = rc -CFLAGS = -nologo -MD -W3 -O2 -Oy- -Zi -Fd"zlib" $(LOC) -WFLAGS = -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -ASFLAGS = -coff -Zi $(LOC) -LDFLAGS = -nologo -debug -incremental:no -opt:ref -ARFLAGS = -nologo -RCFLAGS = /dWIN32 /r - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj \ - gzwrite.obj infback.obj inflate.obj inftrees.obj inffast.obj trees.obj uncompr.obj zutil.obj -OBJA = - - -# targets -all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \ - example.exe minigzip.exe example_d.exe minigzip_d.exe - -$(STATICLIB): $(OBJS) $(OBJA) - $(AR) $(ARFLAGS) -out:$@ $(OBJS) $(OBJA) - -$(IMPLIB): $(SHAREDLIB) - -$(SHAREDLIB): $(TOP)/win32/zlib.def $(OBJS) $(OBJA) zlib1.res - $(LD) $(LDFLAGS) -def:$(TOP)/win32/zlib.def -dll -implib:$(IMPLIB) \ - -out:$@ -base:0x5A4C0000 $(OBJS) $(OBJA) zlib1.res - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;2 - -example.exe: example.obj $(STATICLIB) - $(LD) $(LDFLAGS) example.obj $(STATICLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -minigzip.exe: minigzip.obj $(STATICLIB) - $(LD) $(LDFLAGS) minigzip.obj $(STATICLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -example_d.exe: example.obj $(IMPLIB) - $(LD) $(LDFLAGS) -out:$@ example.obj $(IMPLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -minigzip_d.exe: minigzip.obj $(IMPLIB) - $(LD) $(LDFLAGS) -out:$@ minigzip.obj $(IMPLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -{$(TOP)}.c.obj: - $(CC) -c $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/test}.c.obj: - $(CC) -c -I$(TOP) $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/contrib/masmx64}.c.obj: - $(CC) -c $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/contrib/masmx64}.asm.obj: - $(AS) -c $(ASFLAGS) $< - -{$(TOP)/contrib/masmx86}.asm.obj: - $(AS) -c $(ASFLAGS) $< - -adler32.obj: $(TOP)/adler32.c $(TOP)/zlib.h $(TOP)/zconf.h - -compress.obj: $(TOP)/compress.c $(TOP)/zlib.h $(TOP)/zconf.h - -crc32.obj: $(TOP)/crc32.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/crc32.h - -deflate.obj: $(TOP)/deflate.c $(TOP)/deflate.h $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h - -gzclose.obj: $(TOP)/gzclose.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzlib.obj: $(TOP)/gzlib.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzread.obj: $(TOP)/gzread.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzwrite.obj: $(TOP)/gzwrite.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -infback.obj: $(TOP)/infback.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h $(TOP)/inffixed.h - -inffast.obj: $(TOP)/inffast.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h - -inflate.obj: $(TOP)/inflate.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h $(TOP)/inffixed.h - -inftrees.obj: $(TOP)/inftrees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h - -trees.obj: $(TOP)/trees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/deflate.h $(TOP)/trees.h - -uncompr.obj: $(TOP)/uncompr.c $(TOP)/zlib.h $(TOP)/zconf.h - -zutil.obj: $(TOP)/zutil.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h - -gvmat64.obj: $(TOP)/contrib\masmx64\gvmat64.asm - -inffasx64.obj: $(TOP)/contrib\masmx64\inffasx64.asm - -inffas8664.obj: $(TOP)/contrib\masmx64\inffas8664.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h \ - $(TOP)/inftrees.h $(TOP)/inflate.h $(TOP)/inffast.h - -inffas32.obj: $(TOP)/contrib\masmx86\inffas32.asm - -match686.obj: $(TOP)/contrib\masmx86\match686.asm - -example.obj: $(TOP)/test/example.c $(TOP)/zlib.h $(TOP)/zconf.h - -minigzip.obj: $(TOP)/test/minigzip.c $(TOP)/zlib.h $(TOP)/zconf.h - -zlib1.res: $(TOP)/win32/zlib1.rc - $(RC) $(RCFLAGS) /fo$@ $(TOP)/win32/zlib1.rc - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -testdll: example_d.exe minigzip_d.exe - example_d - echo hello world | minigzip_d | minigzip_d -d - - -# cleanup -clean: - -del $(STATICLIB) - -del $(SHAREDLIB) - -del $(IMPLIB) - -del *.obj - -del *.res - -del *.exp - -del *.exe - -del *.pdb - -del *.manifest - -del foo.gz diff --git a/deps/zlib/win32/README-WIN32.txt b/deps/zlib/win32/README-WIN32.txt deleted file mode 100644 index df7ab7f4b34f90..00000000000000 --- a/deps/zlib/win32/README-WIN32.txt +++ /dev/null @@ -1,103 +0,0 @@ -ZLIB DATA COMPRESSION LIBRARY - -zlib 1.2.11 is a general purpose data compression library. All the code is -thread safe. The data format used by the zlib library is described by RFCs -(Request for Comments) 1950 to 1952 in the files -http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) -and rfc1952.txt (gzip format). - -All functions of the compression library are documented in the file zlib.h -(volunteer to write man pages welcome, contact zlib@gzip.org). Two compiled -examples are distributed in this package, example and minigzip. The example_d -and minigzip_d flavors validate that the zlib1.dll file is working correctly. - -Questions about zlib should be sent to . The zlib home page -is http://zlib.net/ . Before reporting a problem, please check this site to -verify that you have the latest version of zlib; otherwise get the latest -version and check whether the problem still exists or not. - -PLEASE read DLL_FAQ.txt, and the the zlib FAQ http://zlib.net/zlib_faq.html -before asking for help. - - -Manifest: - -The package zlib-1.2.11-win32-x86.zip will contain the following files: - - README-WIN32.txt This document - ChangeLog Changes since previous zlib packages - DLL_FAQ.txt Frequently asked questions about zlib1.dll - zlib.3.pdf Documentation of this library in Adobe Acrobat format - - example.exe A statically-bound example (using zlib.lib, not the dll) - example.pdb Symbolic information for debugging example.exe - - example_d.exe A zlib1.dll bound example (using zdll.lib) - example_d.pdb Symbolic information for debugging example_d.exe - - minigzip.exe A statically-bound test program (using zlib.lib, not the dll) - minigzip.pdb Symbolic information for debugging minigzip.exe - - minigzip_d.exe A zlib1.dll bound test program (using zdll.lib) - minigzip_d.pdb Symbolic information for debugging minigzip_d.exe - - zlib.h Install these files into the compilers' INCLUDE path to - zconf.h compile programs which use zlib.lib or zdll.lib - - zdll.lib Install these files into the compilers' LIB path if linking - zdll.exp a compiled program to the zlib1.dll binary - - zlib.lib Install these files into the compilers' LIB path to link zlib - zlib.pdb into compiled programs, without zlib1.dll runtime dependency - (zlib.pdb provides debugging info to the compile time linker) - - zlib1.dll Install this binary shared library into the system PATH, or - the program's runtime directory (where the .exe resides) - zlib1.pdb Install in the same directory as zlib1.dll, in order to debug - an application crash using WinDbg or similar tools. - -All .pdb files above are entirely optional, but are very useful to a developer -attempting to diagnose program misbehavior or a crash. Many additional -important files for developers can be found in the zlib127.zip source package -available from http://zlib.net/ - review that package's README file for details. - - -Acknowledgments: - -The deflate format used by zlib was defined by Phil Katz. The deflate and -zlib specifications were written by L. Peter Deutsch. Thanks to all the -people who reported problems and suggested various improvements in zlib; they -are too numerous to cite here. - - -Copyright notice: - - (C) 1995-2017 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - -If you use the zlib library in a product, we would appreciate *not* receiving -lengthy legal documents to sign. The sources are provided for free but without -warranty of any kind. The library has been entirely written by Jean-loup -Gailly and Mark Adler; it does not include third-party code. - -If you redistribute modified sources, we would appreciate that you include in -the file ChangeLog history information documenting your changes. Please read -the FAQ for more information on the distribution of modified source versions. diff --git a/deps/zlib/win32/VisualC.txt b/deps/zlib/win32/VisualC.txt deleted file mode 100644 index 1005b219410c77..00000000000000 --- a/deps/zlib/win32/VisualC.txt +++ /dev/null @@ -1,3 +0,0 @@ - -To build zlib using the Microsoft Visual C++ environment, -use the appropriate project from the contrib/vstudio/ directory. diff --git a/deps/zlib/win32/zlib1.rc b/deps/zlib/win32/zlib1.rc deleted file mode 100644 index 234e641c32947a..00000000000000 --- a/deps/zlib/win32/zlib1.rc +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include "../zlib.h" - -#ifdef GCC_WINDRES -VS_VERSION_INFO VERSIONINFO -#else -VS_VERSION_INFO VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE -#endif - FILEVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 - PRODUCTVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS 1 -#else - FILEFLAGS 0 -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - BEGIN - VALUE "FileDescription", "zlib data compression library\0" - VALUE "FileVersion", ZLIB_VERSION "\0" - VALUE "InternalName", "zlib1.dll\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - VALUE "OriginalFilename", "zlib1.dll\0" - VALUE "ProductName", "zlib\0" - VALUE "ProductVersion", ZLIB_VERSION "\0" - VALUE "Comments", "For more information visit http://www.zlib.net/\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/x86.c b/deps/zlib/x86.c new file mode 100644 index 00000000000000..7488ad08b976c8 --- /dev/null +++ b/deps/zlib/x86.c @@ -0,0 +1,101 @@ +/* + * x86 feature check + * + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Author: + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "x86.h" +#include "zutil.h" + +int ZLIB_INTERNAL x86_cpu_enable_ssse3 = 0; +int ZLIB_INTERNAL x86_cpu_enable_simd = 0; + +#ifndef _MSC_VER +#include + +pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; +static void _x86_check_features(void); + +void x86_check_features(void) +{ + pthread_once(&cpu_check_inited_once, _x86_check_features); +} + +static void _x86_check_features(void) +{ + int x86_cpu_has_sse2; + int x86_cpu_has_ssse3; + int x86_cpu_has_sse42; + int x86_cpu_has_pclmulqdq; + unsigned eax, ebx, ecx, edx; + + eax = 1; +#ifdef __i386__ + __asm__ __volatile__ ( + "xchg %%ebx, %1\n\t" + "cpuid\n\t" + "xchg %1, %%ebx\n\t" + : "+a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx) + ); +#else + __asm__ __volatile__ ( + "cpuid\n\t" + : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) + ); +#endif /* (__i386__) */ + + x86_cpu_has_sse2 = edx & 0x4000000; + x86_cpu_has_ssse3 = ecx & 0x000200; + x86_cpu_has_sse42 = ecx & 0x100000; + x86_cpu_has_pclmulqdq = ecx & 0x2; + + x86_cpu_enable_ssse3 = x86_cpu_has_ssse3; + + x86_cpu_enable_simd = x86_cpu_has_sse2 && + x86_cpu_has_sse42 && + x86_cpu_has_pclmulqdq; +} +#else +#include +#include + +static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, + PVOID param, + PVOID *context); +static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; + +void x86_check_features(void) +{ + InitOnceExecuteOnce(&cpu_check_inited_once, _x86_check_features, + NULL, NULL); +} + +static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, + PVOID param, + PVOID *context) +{ + int x86_cpu_has_sse2; + int x86_cpu_has_ssse3; + int x86_cpu_has_sse42; + int x86_cpu_has_pclmulqdq; + int regs[4]; + + __cpuid(regs, 1); + + x86_cpu_has_sse2 = regs[3] & 0x4000000; + x86_cpu_has_ssse3 = regs[2] & 0x000200; + x86_cpu_has_sse42 = regs[2] & 0x100000; + x86_cpu_has_pclmulqdq = regs[2] & 0x2; + + x86_cpu_enable_ssse3 = x86_cpu_has_ssse3; + + x86_cpu_enable_simd = x86_cpu_has_sse2 && + x86_cpu_has_sse42 && + x86_cpu_has_pclmulqdq; + return TRUE; +} +#endif /* _MSC_VER */ diff --git a/deps/zlib/x86.h b/deps/zlib/x86.h new file mode 100644 index 00000000000000..7205d50265c356 --- /dev/null +++ b/deps/zlib/x86.h @@ -0,0 +1,16 @@ +/* x86.h -- check for x86 CPU features +* Copyright (C) 2013 Intel Corporation Jim Kukunas +* For conditions of distribution and use, see copyright notice in zlib.h +*/ + +#ifndef X86_H +#define X86_H + +#include "zlib.h" + +extern int x86_cpu_enable_ssse3; +extern int x86_cpu_enable_simd; + +void x86_check_features(void); + +#endif /* X86_H */ diff --git a/deps/zlib/zconf.h b/deps/zlib/zconf.h index 5e1d68a004e974..353fd36f17e3e5 100644 --- a/deps/zlib/zconf.h +++ b/deps/zlib/zconf.h @@ -8,6 +8,18 @@ #ifndef ZCONF_H #define ZCONF_H +/* + * This library is also built as a part of AOSP, which does not need to include + * chromeconf.h. This config does not want chromeconf.h, so it can set this + * macro to opt out. While this works today, there's no guarantee that building + * zlib outside of Chromium keeps working in the future. + */ +#if !defined(CHROMIUM_ZLIB_NO_CHROMECONF) +/* This include does prefixing as below, but with an updated set of names. Also + * sets up export macros in component builds. */ +//#include "chromeconf.h" +#endif + /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. @@ -386,6 +398,9 @@ #ifndef FAR # define FAR #endif +#ifndef far +# define far +#endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ @@ -431,7 +446,7 @@ typedef uLong FAR uLongf; typedef unsigned long z_crc_t; #endif -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +#if !defined(_WIN32) # define Z_HAVE_UNISTD_H #endif diff --git a/deps/zlib/zconf.h.cmakein b/deps/zlib/zconf.h.cmakein deleted file mode 100644 index a7f24cce60ff7a..00000000000000 --- a/deps/zlib/zconf.h.cmakein +++ /dev/null @@ -1,536 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H -#cmakedefine Z_PREFIX -#cmakedefine Z_HAVE_UNISTD_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols and init macros */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define adler32_z z_adler32_z -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define crc32_z z_crc32_z -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateGetDictionary z_deflateGetDictionary -# define deflateInit z_deflateInit -# define deflateInit2 z_deflateInit2 -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzfread z_gzfread -# define gzfwrite z_gzfwrite -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzvprintf z_gzvprintf -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit z_inflateBackInit -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCodesUsed z_inflateCodesUsed -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetDictionary z_inflateGetDictionary -# define inflateGetHeader z_inflateGetHeader -# define inflateInit z_inflateInit -# define inflateInit2 z_inflateInit2 -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateResetKeep z_inflateResetKeep -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateValidate z_inflateValidate -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# define uncompress2 z_uncompress2 -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -#ifdef Z_SOLO - typedef unsigned long z_size_t; -#else -# define z_longlong long long -# if defined(NO_SIZE_T) - typedef unsigned NO_SIZE_T z_size_t; -# elif defined(STDC) -# include - typedef size_t z_size_t; -# else - typedef unsigned long z_size_t; -# endif -# undef z_longlong -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus about 7 kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/deps/zlib/zconf.h.in b/deps/zlib/zconf.h.in deleted file mode 100644 index 5e1d68a004e974..00000000000000 --- a/deps/zlib/zconf.h.in +++ /dev/null @@ -1,534 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols and init macros */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define adler32_z z_adler32_z -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define crc32_z z_crc32_z -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateGetDictionary z_deflateGetDictionary -# define deflateInit z_deflateInit -# define deflateInit2 z_deflateInit2 -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzfread z_gzfread -# define gzfwrite z_gzfwrite -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzvprintf z_gzvprintf -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit z_inflateBackInit -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCodesUsed z_inflateCodesUsed -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetDictionary z_inflateGetDictionary -# define inflateGetHeader z_inflateGetHeader -# define inflateInit z_inflateInit -# define inflateInit2 z_inflateInit2 -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateResetKeep z_inflateResetKeep -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateValidate z_inflateValidate -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# define uncompress2 z_uncompress2 -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -#ifdef Z_SOLO - typedef unsigned long z_size_t; -#else -# define z_longlong long long -# if defined(NO_SIZE_T) - typedef unsigned NO_SIZE_T z_size_t; -# elif defined(STDC) -# include - typedef size_t z_size_t; -# else - typedef unsigned long z_size_t; -# endif -# undef z_longlong -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus about 7 kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/deps/zlib/zlib.3 b/deps/zlib/zlib.3 deleted file mode 100644 index bda4eb0737090c..00000000000000 --- a/deps/zlib/zlib.3 +++ /dev/null @@ -1,149 +0,0 @@ -.TH ZLIB 3 "15 Jan 2017" -.SH NAME -zlib \- compression/decompression library -.SH SYNOPSIS -[see -.I zlib.h -for full description] -.SH DESCRIPTION -The -.I zlib -library is a general purpose data compression library. -The code is thread safe, assuming that the standard library functions -used are thread safe, such as memory allocation routines. -It provides in-memory compression and decompression functions, -including integrity checks of the uncompressed data. -This version of the library supports only one compression method (deflation) -but other algorithms may be added later -with the same stream interface. -.LP -Compression can be done in a single step if the buffers are large enough -or can be done by repeated calls of the compression function. -In the latter case, -the application must provide more input and/or consume the output -(providing more output space) before each call. -.LP -The library also supports reading and writing files in -.IR gzip (1) -(.gz) format -with an interface similar to that of stdio. -.LP -The library does not install any signal handler. -The decoder checks the consistency of the compressed data, -so the library should never crash even in the case of corrupted input. -.LP -All functions of the compression library are documented in the file -.IR zlib.h . -The distribution source includes examples of use of the library -in the files -.I test/example.c -and -.IR test/minigzip.c, -as well as other examples in the -.IR examples/ -directory. -.LP -Changes to this version are documented in the file -.I ChangeLog -that accompanies the source. -.LP -.I zlib -is built in to many languages and operating systems, including but not limited to -Java, Python, .NET, PHP, Perl, Ruby, Swift, and Go. -.LP -An experimental package to read and write files in the .zip format, -written on top of -.I zlib -by Gilles Vollant (info@winimage.com), -is available at: -.IP -http://www.winimage.com/zLibDll/minizip.html -and also in the -.I contrib/minizip -directory of the main -.I zlib -source distribution. -.SH "SEE ALSO" -The -.I zlib -web site can be found at: -.IP -http://zlib.net/ -.LP -The data format used by the -.I zlib -library is described by RFC -(Request for Comments) 1950 to 1952 in the files: -.IP -http://tools.ietf.org/html/rfc1950 (for the zlib header and trailer format) -.br -http://tools.ietf.org/html/rfc1951 (for the deflate compressed data format) -.br -http://tools.ietf.org/html/rfc1952 (for the gzip header and trailer format) -.LP -Mark Nelson wrote an article about -.I zlib -for the Jan. 1997 issue of Dr. Dobb's Journal; -a copy of the article is available at: -.IP -http://marknelson.us/1997/01/01/zlib-engine/ -.SH "REPORTING PROBLEMS" -Before reporting a problem, -please check the -.I zlib -web site to verify that you have the latest version of -.IR zlib ; -otherwise, -obtain the latest version and see if the problem still exists. -Please read the -.I zlib -FAQ at: -.IP -http://zlib.net/zlib_faq.html -.LP -before asking for help. -Send questions and/or comments to zlib@gzip.org, -or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). -.SH AUTHORS AND LICENSE -Version 1.2.11 -.LP -Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler -.LP -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. -.LP -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: -.LP -.nr step 1 1 -.IP \n[step]. 3 -The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software -in a product, an acknowledgment in the product documentation would be -appreciated but is not required. -.IP \n+[step]. -Altered source versions must be plainly marked as such, and must not be -misrepresented as being the original software. -.IP \n+[step]. -This notice may not be removed or altered from any source distribution. -.LP -Jean-loup Gailly Mark Adler -.br -jloup@gzip.org madler@alumni.caltech.edu -.LP -The deflate format used by -.I zlib -was defined by Phil Katz. -The deflate and -.I zlib -specifications were written by L. Peter Deutsch. -Thanks to all the people who reported problems and suggested various -improvements in -.IR zlib ; -who are too numerous to cite here. -.LP -UNIX manual page by R. P. C. Rodgers, -U.S. National Library of Medicine (rodgers@nlm.nih.gov). -.\" end of man page diff --git a/deps/zlib/zlib.3.pdf b/deps/zlib/zlib.3.pdf deleted file mode 100644 index 6fa519c5bdf5df..00000000000000 Binary files a/deps/zlib/zlib.3.pdf and /dev/null differ diff --git a/deps/zlib/zlib.gyp b/deps/zlib/zlib.gyp index 970bc787bae1ea..c73b9adba902de 100644 --- a/deps/zlib/zlib.gyp +++ b/deps/zlib/zlib.gyp @@ -4,7 +4,9 @@ { 'variables': { - 'use_system_zlib%': 0 + 'use_system_zlib%': 0, + 'arm_fpu%': '', + 'llvm_version%': '0.0', }, 'conditions': [ ['use_system_zlib==0', { @@ -15,6 +17,7 @@ 'sources': [ 'adler32.c', 'compress.c', + 'contrib/optimizations/insert_string.h', 'crc32.c', 'crc32.h', 'deflate.c', @@ -28,13 +31,13 @@ 'inffast.c', 'inffast.h', 'inffixed.h', - 'inflate.c', 'inflate.h', 'inftrees.c', 'inftrees.h', 'trees.c', 'trees.h', 'uncompr.c', + 'x86.h', 'zconf.h', 'zlib.h', 'zutil.c', @@ -51,7 +54,7 @@ 'conditions': [ ['OS!="win"', { 'cflags!': [ '-ansi' ], - 'defines': [ 'Z_HAVE_UNISTD_H', 'HAVE_HIDDEN' ], + 'defines': [ 'HAVE_HIDDEN' ], }], ['OS=="mac" or OS=="ios" or OS=="freebsd" or OS=="android"', { # Mac, Android and the BSDs don't have fopen64, ftello64, or @@ -61,6 +64,93 @@ 'USE_FILE32API' ], }], + ['(target_arch in "ia32 x64 x32" and OS!="ios") or arm_fpu=="neon"', { + 'sources': [ + 'adler32_simd.c', + 'adler32_simd.h', + 'contrib/optimizations/chunkcopy.h', + 'contrib/optimizations/inffast_chunk.c', + 'contrib/optimizations/inffast_chunk.h', + 'contrib/optimizations/inflate.c', + ], + }, { + 'sources': [ 'inflate.c', ], + }], + # Incorporate optimizations where possible + ['target_arch in "ia32 x64 x32" and OS!="ios"', { + 'defines': [ + 'ADLER32_SIMD_SSSE3', + 'INFLATE_CHUNK_SIMD_SSE2', + 'CRC32_SIMD_SSE42_PCLMUL', + ], + 'sources': [ + 'crc32_simd.c', + 'crc32_simd.h', + 'crc_folding.c', + 'fill_window_sse.c', + 'x86.c', + ], + 'conditions': [ + ['OS!="win" or llvm_version!="0.0"', { + 'cflags': [ + '-mssse3', + '-msse4.2', + '-mpclmul', + ], + 'xcode_settings': { + 'OTHER_CFLAGS': [ + '-mssse3', + '-msse4.2', + '-mpclmul', + ], + }, + }], + ['target_arch=="x64"', { + 'defines': [ 'INFLATE_CHUNK_READ_64LE' ], + }], + ], + }, { + 'sources': [ 'simd_stub.c', ], + }], + ['arm_fpu=="neon"', { + 'defines': [ + 'ADLER32_SIMD_NEON', + 'INFLATE_CHUNK_SIMD_NEON', + ], + 'sources': [ + 'contrib/optimizations/slide_hash_neon.h', + ], + 'conditions': [ + ['OS!="ios"', { + 'defines': [ 'CRC32_ARMV8_CRC32' ], + 'sources': [ + 'arm_features.c', + 'arm_features.h', + 'crc32_simd.c', + 'crc32_simd.h', + ], + 'conditions': [ + ['OS=="android"', { + 'defines': [ 'ARMV8_OS_ANDROID' ], + }], + ['OS=="linux"', { + 'defines': [ 'ARMV8_OS_LINUX' ], + }], + ['OS="win"', { + 'defines': [ 'ARMV8_OS_WINDOWS' ], + }], + ['OS!="android" and OS!="win" and llvm_version=="0.0"', { + 'cflags': [ + '-march=armv8-a+crc', + ], + }], + ], + }], + ['target_arch=="arm64"', { + 'defines': [ 'INFLATE_CHUNK_READ_64LE' ], + }], + ], + }], ], }, ], diff --git a/deps/zlib/zlib.h b/deps/zlib/zlib.h index f09cdaf1e0543d..99fd467f6b1a54 100644 --- a/deps/zlib/zlib.h +++ b/deps/zlib/zlib.h @@ -1824,6 +1824,11 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ # undef z_gzgetc # define z_gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#elif defined(Z_CR_PREFIX_SET) +# undef gzgetc +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) \ + : (Cr_z_gzgetc)(g)) #else # define gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) @@ -1853,11 +1858,29 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ # define z_adler32_combine z_adler32_combine64 # define z_crc32_combine z_crc32_combine64 # else +# ifdef gzopen +# undef gzopen +# endif # define gzopen gzopen64 +# ifdef gzseek +# undef gzseek +# endif # define gzseek gzseek64 +# ifdef gztell +# undef gztell +# endif # define gztell gztell64 +# ifdef gzoffset +# undef gzoffset +# endif # define gzoffset gzoffset64 +# ifdef adler32_combine +# undef adler32_combine +# endif # define adler32_combine adler32_combine64 +# ifdef crc32_combine +# undef crc32_combine +# endif # define crc32_combine crc32_combine64 # endif # ifndef Z_LARGE64 diff --git a/deps/zlib/zlib.map b/deps/zlib/zlib.map deleted file mode 100644 index 82ce98cf7decc9..00000000000000 --- a/deps/zlib/zlib.map +++ /dev/null @@ -1,94 +0,0 @@ -ZLIB_1.2.0 { - global: - compressBound; - deflateBound; - inflateBack; - inflateBackEnd; - inflateBackInit_; - inflateCopy; - local: - deflate_copyright; - inflate_copyright; - inflate_fast; - inflate_table; - zcalloc; - zcfree; - z_errmsg; - gz_error; - gz_intmax; - _*; -}; - -ZLIB_1.2.0.2 { - gzclearerr; - gzungetc; - zlibCompileFlags; -} ZLIB_1.2.0; - -ZLIB_1.2.0.8 { - deflatePrime; -} ZLIB_1.2.0.2; - -ZLIB_1.2.2 { - adler32_combine; - crc32_combine; - deflateSetHeader; - inflateGetHeader; -} ZLIB_1.2.0.8; - -ZLIB_1.2.2.3 { - deflateTune; - gzdirect; -} ZLIB_1.2.2; - -ZLIB_1.2.2.4 { - inflatePrime; -} ZLIB_1.2.2.3; - -ZLIB_1.2.3.3 { - adler32_combine64; - crc32_combine64; - gzopen64; - gzseek64; - gztell64; - inflateUndermine; -} ZLIB_1.2.2.4; - -ZLIB_1.2.3.4 { - inflateReset2; - inflateMark; -} ZLIB_1.2.3.3; - -ZLIB_1.2.3.5 { - gzbuffer; - gzoffset; - gzoffset64; - gzclose_r; - gzclose_w; -} ZLIB_1.2.3.4; - -ZLIB_1.2.5.1 { - deflatePending; -} ZLIB_1.2.3.5; - -ZLIB_1.2.5.2 { - deflateResetKeep; - gzgetc_; - inflateResetKeep; -} ZLIB_1.2.5.1; - -ZLIB_1.2.7.1 { - inflateGetDictionary; - gzvprintf; -} ZLIB_1.2.5.2; - -ZLIB_1.2.9 { - inflateCodesUsed; - inflateValidate; - uncompress2; - gzfread; - gzfwrite; - deflateGetDictionary; - adler32_z; - crc32_z; -} ZLIB_1.2.7.1; diff --git a/deps/zlib/zlib.pc.cmakein b/deps/zlib/zlib.pc.cmakein deleted file mode 100644 index a5e642938c6985..00000000000000 --- a/deps/zlib/zlib.pc.cmakein +++ /dev/null @@ -1,13 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=@CMAKE_INSTALL_PREFIX@ -libdir=@INSTALL_LIB_DIR@ -sharedlibdir=@INSTALL_LIB_DIR@ -includedir=@INSTALL_INC_DIR@ - -Name: zlib -Description: zlib compression library -Version: @VERSION@ - -Requires: -Libs: -L${libdir} -L${sharedlibdir} -lz -Cflags: -I${includedir} diff --git a/deps/zlib/zlib.pc.in b/deps/zlib/zlib.pc.in deleted file mode 100644 index 7e5acf9c77e774..00000000000000 --- a/deps/zlib/zlib.pc.in +++ /dev/null @@ -1,13 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -sharedlibdir=@sharedlibdir@ -includedir=@includedir@ - -Name: zlib -Description: zlib compression library -Version: @VERSION@ - -Requires: -Libs: -L${libdir} -L${sharedlibdir} -lz -Cflags: -I${includedir} diff --git a/deps/zlib/zlib2ansi b/deps/zlib/zlib2ansi deleted file mode 100755 index 15e3e165f37dec..00000000000000 --- a/deps/zlib/zlib2ansi +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/perl - -# Transform K&R C function definitions into ANSI equivalent. -# -# Author: Paul Marquess -# Version: 1.0 -# Date: 3 October 2006 - -# TODO -# -# Asumes no function pointer parameters. unless they are typedefed. -# Assumes no literal strings that look like function definitions -# Assumes functions start at the beginning of a line - -use strict; -use warnings; - -local $/; -$_ = <>; - -my $sp = qr{ \s* (?: /\* .*? \*/ )? \s* }x; # assume no nested comments - -my $d1 = qr{ $sp (?: [\w\*\s]+ $sp)* $sp \w+ $sp [\[\]\s]* $sp }x ; -my $decl = qr{ $sp (?: \w+ $sp )+ $d1 }xo ; -my $dList = qr{ $sp $decl (?: $sp , $d1 )* $sp ; $sp }xo ; - - -while (s/^ - ( # Start $1 - ( # Start $2 - .*? # Minimal eat content - ( ^ \w [\w\s\*]+ ) # $3 -- function name - \s* # optional whitespace - ) # $2 - Matched up to before parameter list - - \( \s* # Literal "(" + optional whitespace - ( [^\)]+ ) # $4 - one or more anythings except ")" - \s* \) # optional whitespace surrounding a Literal ")" - - ( (?: $dList )+ ) # $5 - - $sp ^ { # literal "{" at start of line - ) # Remember to $1 - //xsom - ) -{ - my $all = $1 ; - my $prefix = $2; - my $param_list = $4 ; - my $params = $5; - - StripComments($params); - StripComments($param_list); - $param_list =~ s/^\s+//; - $param_list =~ s/\s+$//; - - my $i = 0 ; - my %pList = map { $_ => $i++ } - split /\s*,\s*/, $param_list; - my $pMatch = '(\b' . join('|', keys %pList) . '\b)\W*$' ; - - my @params = split /\s*;\s*/, $params; - my @outParams = (); - foreach my $p (@params) - { - if ($p =~ /,/) - { - my @bits = split /\s*,\s*/, $p; - my $first = shift @bits; - $first =~ s/^\s*//; - push @outParams, $first; - $first =~ /^(\w+\s*)/; - my $type = $1 ; - push @outParams, map { $type . $_ } @bits; - } - else - { - $p =~ s/^\s+//; - push @outParams, $p; - } - } - - - my %tmp = map { /$pMatch/; $_ => $pList{$1} } - @outParams ; - - @outParams = map { " $_" } - sort { $tmp{$a} <=> $tmp{$b} } - @outParams ; - - print $prefix ; - print "(\n" . join(",\n", @outParams) . ")\n"; - print "{" ; - -} - -# Output any trailing code. -print ; -exit 0; - - -sub StripComments -{ - - no warnings; - - # Strip C & C++ coments - # From the perlfaq - $_[0] =~ - - s{ - /\* ## Start of /* ... */ comment - [^*]*\*+ ## Non-* followed by 1-or-more *'s - ( - [^/*][^*]*\*+ - )* ## 0-or-more things which don't start with / - ## but do end with '*' - / ## End of /* ... */ comment - - | ## OR C++ Comment - // ## Start of C++ comment // - [^\n]* ## followed by 0-or-more non end of line characters - - | ## OR various things which aren't comments: - - ( - " ## Start of " ... " string - ( - \\. ## Escaped char - | ## OR - [^"\\] ## Non "\ - )* - " ## End of " ... " string - - | ## OR - - ' ## Start of ' ... ' string - ( - \\. ## Escaped char - | ## OR - [^'\\] ## Non '\ - )* - ' ## End of ' ... ' string - - | ## OR - - . ## Anything other char - [^/"'\\]* ## Chars which doesn't start a comment, string or escape - ) - }{$2}gxs; - -} diff --git a/deps/zlib/zutil.h b/deps/zlib/zutil.h index b079ea6a80f5ab..4425bcf75eb38c 100644 --- a/deps/zlib/zutil.h +++ b/deps/zlib/zutil.h @@ -28,6 +28,21 @@ # include # include #endif +#ifdef NO_ERRNO_H +# ifdef _WIN32_WCE + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. We rename it to + * avoid conflict with other libraries that use the same workaround. + */ +# define errno z_errno +# endif + extern int errno; +#else +# ifndef _WIN32_WCE +# include +# endif +#endif #ifdef Z_SOLO typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ @@ -268,4 +283,10 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) +#ifdef _MSC_VER +#define zalign(x) __declspec(align(x)) +#else +#define zalign(x) __attribute__((aligned((x)))) +#endif + #endif /* ZUTIL_H */ diff --git a/doc/api/addons.md b/doc/api/addons.md index d011af902d19c4..6b77338348ed96 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -40,7 +40,7 @@ involving knowledge of several components and APIs: other libraries are located in the `deps/` directory in the Node.js source tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully re-exported by Node.js and may be used to various extents by Addons. See - [Linking to Node.js' own dependencies][] for additional information. + [Linking to libraries included with Node.js][] for additional information. All of the following examples are available for [download][] and may be used as the starting-point for an Addon. @@ -373,7 +373,7 @@ try { } ``` -### Linking to Node.js' own dependencies +### Linking to libraries included with Node.js Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All Addons are required to link to V8 and may link to any of the other dependencies @@ -1361,7 +1361,7 @@ console.log(result); [`Worker`]: worker_threads.html#worker_threads_class_worker [Electron]: https://electronjs.org/ [Embedder's Guide]: https://github.com/v8/v8/wiki/Embedder's%20Guide -[Linking to Node.js' own dependencies]: #addons_linking_to_node_js_own_dependencies +[Linking to libraries included with Node.js]: #addons_linking_to_libraries_included_with_node_js [Native Abstractions for Node.js]: https://github.com/nodejs/nan [bindings]: https://github.com/TooTallNate/node-bindings [download]: https://github.com/nodejs/node-addon-examples diff --git a/doc/api/assert.md b/doc/api/assert.md index 0598ee8be10880..809dc01340fcd7 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -5,8 +5,87 @@ > Stability: 2 - Stable The `assert` module provides a set of assertion functions for verifying -invariants. The module provides a recommended [`strict` mode][] and a more -lenient legacy mode. +invariants. + +## Strict assertion mode + + +In strict assertion mode, non-strict methods behave like their corresponding +strict methods. For example, [`assert.deepEqual()`][] will behave like +[`assert.deepStrictEqual()`][]. + +In strict assertion mode, error messages for objects display a diff. In legacy +assertion mode, error messages for objects display the objects, often truncated. + +To use strict assertion mode: + +```js +const assert = require('assert').strict; +``` + +Example error diff: + +```js +const assert = require('assert').strict; + +assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); +// AssertionError: Expected inputs to be strictly deep-equal: +// + actual - expected ... Lines skipped +// +// [ +// [ +// ... +// 2, +// + 3 +// - '3' +// ], +// ... +// 5 +// ] +``` + +To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` +environment variables. This will also deactivate the colors in the REPL. For +more on color support in terminal environments, read the tty +[getColorDepth()](tty.html#tty_writestream_getcolordepth_env) documentation. + +## Legacy assertion mode + +Legacy assertion mode uses the [Abstract Equality Comparison][] in: + +* [`assert.deepEqual()`][] +* [`assert.equal()`][] +* [`assert.notDeepEqual()`][] +* [`assert.notEqual()`][] + +To use legacy assertion mode: + +```js +const assert = require('assert'); +``` + +Whenever possible, use the [strict assertion mode][] instead. Otherwise, the +[Abstract Equality Comparison][] may cause surprising results. This is +especially true for [`assert.deepEqual()`][], where the comparison rules are +lax: + +```js +// WARNING: This does not throw an AssertionError! +assert.deepEqual(/a/gi, new Date()); +``` ## Class: assert.AssertionError @@ -68,84 +147,6 @@ try { } ``` -## Strict mode - - -In `strict` mode (not to be confused with `"use strict"`), `assert` functions -use the comparison in the corresponding strict functions. For example, -[`assert.deepEqual()`][] will behave like [`assert.deepStrictEqual()`][]. - -In `strict` mode, error messages for objects display a diff. In legacy mode, -error messages for objects display the objects, often truncated. - -To use `strict` mode: - -```js -const assert = require('assert').strict; -``` - -Example error diff: - -```js -const assert = require('assert').strict; - -assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); -// AssertionError: Expected inputs to be strictly deep-equal: -// + actual - expected ... Lines skipped -// -// [ -// [ -// ... -// 2, -// + 3 -// - '3' -// ], -// ... -// 5 -// ] -``` - -To deactivate the colors, use the `NO_COLOR` or -`NODE_DISABLE_COLORS` environment variable. -This will also deactivate the colors in the REPL. - -For more on the color support in terminal environments, read -the tty [getColorDepth()](tty.html#tty_writestream_getcolordepth_env) doc. - -## Legacy mode - -Legacy mode uses the [Abstract Equality Comparison][] in: - -* [`assert.deepEqual()`][] -* [`assert.equal()`][] -* [`assert.notDeepEqual()`][] -* [`assert.notEqual()`][] - -To use legacy mode: - -```js -const assert = require('assert'); -``` - -Whenever possible, use the [`strict` mode][] instead. Otherwise, the -[Abstract Equality Comparison][] may cause surprising results. This is -especially true for [`assert.deepEqual()`][], where the comparison rules are -lax: - -```js -// WARNING: This does not throw an AssertionError! -assert.deepEqual(/a/gi, new Date()); -``` - ## `assert(value[, message])` + +* Returns: {Object} The resource representing the current execution. + Useful to store data within the resource. + +Resource objects returned by `executionAsyncResource()` are most often internal +Node.js handle objects with undocumented APIs. Using any functions or properties +on the object is likely to crash your application and should be avoided. + +Using `executionAsyncResource()` in the top-level execution context will +return an empty object as there is no handle or request object to use, +but having an object representing the top-level can be helpful. + +```js +const { open } = require('fs'); +const { executionAsyncId, executionAsyncResource } = require('async_hooks'); + +console.log(executionAsyncId(), executionAsyncResource()); // 1 {} +open(__filename, 'r', (err, fd) => { + console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap +}); +``` + +This can be used to implement continuation local storage without the +use of a tracking `Map` to store the metadata: + +```js +const { createServer } = require('http'); +const { + executionAsyncId, + executionAsyncResource, + createHook +} = require('async_hooks'); +const sym = Symbol('state'); // Private symbol to avoid pollution + +createHook({ + init(asyncId, type, triggerAsyncId, resource) { + const cr = executionAsyncResource(); + if (cr) { + resource[sym] = cr[sym]; + } + } +}).enable(); + +const server = createServer(function(req, res) { + executionAsyncResource()[sym] = { state: req.url }; + setTimeout(function() { + res.end(JSON.stringify(executionAsyncResource()[sym])); + }, 100); +}).listen(3000); +``` + #### `async_hooks.executionAsyncId()` Aborting instead of exiting causes a core file to be generated for post-mortem @@ -156,6 +156,13 @@ Enable experimental Source Map V3 support for stack traces. Currently, overriding `Error.prepareStackTrace` is ignored when the `--enable-source-maps` flag is set. +### `--experimental-import-meta-resolve` + + +Enable experimental `import.meta.resolve()` support. + ### `--experimental-json-modules` + +Prints a stack trace on SIGINT. + ### `--trace-sync-io` * `--enable-fips` * `--enable-source-maps` +* `--experimental-import-meta-resolve` * `--experimental-json-modules` * `--experimental-loader` * `--experimental-modules` @@ -1122,6 +1137,7 @@ Node.js options that are allowed are: * `--trace-event-file-pattern` * `--trace-events-enabled` * `--trace-exit` +* `--trace-sigint` * `--trace-sync-io` * `--trace-tls` * `--trace-uncaught` diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 4562f71e0b2343..e15c7f1d6bf764 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1232,6 +1232,9 @@ passing keys as strings or `Buffer`s due to improved security features. + +* `options`: {Object} + * `privateKey`: {KeyObject} + * `publicKey`: {KeyObject} +* Returns: {Buffer} + +Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. +Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` +(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + ### `crypto.generateKeyPair(type, options, callback)` * `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, - `'x25519'`, or `'x448'`. + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * `callback`: {Function} @@ -2115,8 +2141,8 @@ changes: * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, @@ -2154,6 +2180,9 @@ a `Promise` for an `Object` with `publicKey` and `privateKey` properties. -* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, or `'ed448'`. +* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * Returns: {Object} * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, diff --git a/doc/api/errors.md b/doc/api/errors.md index 63d2e1c20d5346..74a4faa88b929f 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -776,6 +776,11 @@ be called no more than one time per instance of a `Hash` object. [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. + +### `ERR_CRYPTO_INCOMPATIBLE_KEY` + +The given crypto keys are incompatible with the attempted operation. + ### `ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS` @@ -826,6 +831,17 @@ A signing `key` was not provided to the [`sign.sign()`][] method. [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. + +### `ERR_CRYPTO_UNKNOWN_CIPHER` + +An unknown cipher was specified. + + +### `ERR_CRYPTO_UNKNOWN_DH_GROUP` + +An unknown Diffie-Hellman group name was given. See +[`crypto.getDiffieHellman()`][] for a list of valid group names. + ### `ERR_DIR_CLOSED` @@ -1168,7 +1184,7 @@ To fix the error, open an issue at https://github.com/nodejs/node/issues. ### `ERR_INCOMPATIBLE_OPTION_PAIR` -An option pair is incompatible with each other and can not be used at the same +An option pair is incompatible with each other and cannot be used at the same time. @@ -1514,6 +1530,12 @@ strict compliance with the API specification (which in some cases may accept An [ES Module][] loader hook specified `format: 'dynamic'` but did not provide a `dynamicInstantiate` hook. + +### `ERR_MISSING_OPTION` + +For APIs that accept options objects, some options might be mandatory. This code +is thrown if a required option is missing. + ### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` @@ -2031,6 +2053,11 @@ The WASI instance has already started. The `execArgv` option passed to the `Worker` constructor contains invalid flags. + +### `ERR_WORKER_NOT_RUNNING` + +An operation failed because the `Worker` instance is not currently running. + ### `ERR_WORKER_OUT_OF_MEMORY` @@ -2423,6 +2450,7 @@ such as `process.stdout.on('data')`. [`Writable`]: stream.html#stream_class_stream_writable [`child_process`]: child_process.html [`cipher.getAuthTag()`]: crypto.html#crypto_cipher_getauthtag +[`crypto.getDiffieHellman()`]: crypto.html#crypto_crypto_getdiffiehellman_groupname [`crypto.scrypt()`]: crypto.html#crypto_crypto_scrypt_password_salt_keylen_options_callback [`crypto.scryptSync()`]: crypto.html#crypto_crypto_scryptsync_password_salt_keylen_options [`crypto.timingSafeEqual()`]: crypto.html#crypto_crypto_timingsafeequal_a_b diff --git a/doc/api/esm.md b/doc/api/esm.md index e5271b5b343a84..f1378b59ad10a2 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -33,9 +33,8 @@ initial input, or when referenced by `import` statements within ES module code: * Files ending in `.mjs`. -* Files ending in `.js`, or extensionless files, when the nearest parent - `package.json` file contains a top-level field `"type"` with a value of - `"module"`. +* Files ending in `.js` when the nearest parent `package.json` file contains a + top-level field `"type"` with a value of `"module"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=module`. @@ -50,18 +49,17 @@ or when referenced by `import` statements within ES module code: * Files ending in `.cjs`. -* Files ending in `.js`, or extensionless files, when the nearest parent - `package.json` file contains a top-level field `"type"` with a value of - `"commonjs"`. +* Files ending in `.js` when the nearest parent `package.json` file contains a + top-level field `"type"` with a value of `"commonjs"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=commonjs`. ### `package.json` `"type"` field -Files ending with `.js` or lacking any extension will be loaded as ES modules -when the nearest parent `package.json` file contains a top-level field `"type"` -with a value of `"module"`. +Files ending with `.js` will be loaded as ES modules when the nearest parent +`package.json` file contains a top-level field `"type"` with a value of +`"module"`. The nearest parent `package.json` is defined as the first `package.json` found when searching in the current folder, that folder’s parent, and so on up @@ -81,14 +79,12 @@ node my-app.js # Runs as ES module ``` If the nearest parent `package.json` lacks a `"type"` field, or contains -`"type": "commonjs"`, extensionless and `.js` files are treated as CommonJS. -If the volume root is reached and no `package.json` is found, -Node.js defers to the default, a `package.json` with no `"type"` -field. "Extensionless" refers to file paths which do not contain -an extension as opposed to optionally dropping a file extension in a specifier. +`"type": "commonjs"`, `.js` files are treated as CommonJS. If the volume root is +reached and no `package.json` is found, Node.js defers to the default, a +`package.json` with no `"type"` field. -`import` statements of `.js` and extensionless files are treated as ES modules -if the nearest parent `package.json` contains `"type": "module"`. +`import` statements of `.js` files are treated as ES modules if the nearest +parent `package.json` contains `"type": "module"`. ```js // my-app.js, part of the same example as above @@ -106,14 +102,13 @@ as ES modules and `.cjs` files are always treated as CommonJS. ### Package Scope and File Extensions -A folder containing a `package.json` file, and all subfolders below that -folder down until the next folder containing another `package.json`, is -considered a _package scope_. The `"type"` field defines how `.js` and -extensionless files should be treated within a particular `package.json` file’s -package scope. Every package in a project’s `node_modules` folder contains its -own `package.json` file, so each project’s dependencies have their own package -scopes. A `package.json` lacking a `"type"` field is treated as if it contained -`"type": "commonjs"`. +A folder containing a `package.json` file, and all subfolders below that folder +down until the next folder containing another `package.json`, is considered a +_package scope_. The `"type"` field defines how `.js` files should be treated +within a particular `package.json` file’s package scope. Every package in a +project’s `node_modules` folder contains its own `package.json` file, so each +project’s dependencies have their own package scopes. A `package.json` lacking a +`"type"` field is treated as if it contained `"type": "commonjs"`. The package scope applies not only to initial entry points (`node my-app.js`) but also to files referenced by `import` statements and `import()` expressions. @@ -791,6 +786,32 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); ``` +### No `require.resolve` + +Former use cases relying on `require.resolve` to determine the resolved path +of a module can be supported via `import.meta.resolve`, which is experimental +and supported via the `--experimental-import-meta-resolve` flag: + +```js +(async () => { + const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); +})(); +``` + +`import.meta.resolve` also accepts a second argument which is the parent module +from which to resolve from: + +```js +(async () => { + // Equivalent to import.meta.resolve('./dep') + await import.meta.resolve('./dep', import.meta.url); +})(); +``` + +This function is asynchronous since the ES module resolver in Node.js is +asynchronous. With the introduction of [Top-Level Await][], these use cases +will be easier as they won't require an async function wrapper. + ### No `require.extensions` `require.extensions` is not used by `import`. The expectation is that loader @@ -1355,13 +1376,14 @@ The resolver has the following properties: The algorithm to load an ES module specifier is given through the **ESM_RESOLVE** method below. It returns the resolved URL for a -module specifier relative to a parentURL, in addition to the unique module -format for that resolved URL given by the **ESM_FORMAT** routine. +module specifier relative to a parentURL. -The _"module"_ format is returned for an ECMAScript Module, while the -_"commonjs"_ format is used to indicate loading through the legacy -CommonJS loader. Additional formats such as _"addon"_ can be extended in future -updates. +The algorithm to determine the module format of a resolved URL is +provided by **ESM_FORMAT**, which returns the unique module +format for any file. The _"module"_ format is returned for an ECMAScript +Module, while the _"commonjs"_ format is used to indicate loading through the +legacy CommonJS loader. Additional formats such as _"addon"_ can be extended in +future updates. In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise. @@ -1390,11 +1412,13 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _resolvedURL_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ > and _"%5C"_ respectively), then > 1. Throw an _Invalid Specifier_ error. -> 1. If the file at _resolvedURL_ does not exist, then +> 1. If _resolvedURL_ does not end with a trailing _"/"_ and the file at +> _resolvedURL_ does not exist, then > 1. Throw a _Module Not Found_ error. > 1. Set _resolvedURL_ to the real path of _resolvedURL_. > 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_). > 1. Load _resolvedURL_ as module format, _format_. +> 1. Return _resolvedURL_. **PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) @@ -1422,7 +1446,7 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _selfUrl_ isn't empty, return _selfUrl_. > 1. If _packageSubpath_ is _undefined_ and _packageName_ is a Node.js builtin > module, then -> 1. Return the string _"node:"_ concatenated with _packageSpecifier_. +> 1. Return the string _"nodejs:"_ concatenated with _packageSpecifier_. > 1. While _parentURL_ is not the file system root, > 1. Let _packageURL_ be the URL resolution of _"node_modules/"_ > concatenated with _packageSpecifier_, relative to _parentURL_. @@ -1431,6 +1455,8 @@ _defaultEnv_ is the conditional environment name priority array, > 1. Set _parentURL_ to the parent URL path of _parentURL_. > 1. Continue the next loop iteration. > 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). +> 1. If _packageSubpath_ is equal to _"./"_, then +> 1. Return _packageURL_ + _"/"_. > 1. If _packageSubpath_ is _undefined__, then > 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, > _pjson_). @@ -1452,6 +1478,8 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _pjson_ does not include an _"exports"_ property, then > 1. Return **undefined**. > 1. If _pjson.name_ is equal to _packageName_, then +> 1. If _packageSubpath_ is equal to _"./"_, then +> 1. Return _packageURL_ + _"/"_. > 1. If _packageSubpath_ is _undefined_, then > 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, _pjson_). > 1. Otherwise, @@ -1548,19 +1576,17 @@ _defaultEnv_ is the conditional environment name priority array, **ESM_FORMAT**(_url_) -> 1. Assert: _url_ corresponds to an existing file pathname. +> 1. Assert: _url_ corresponds to an existing file. > 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). > 1. If _url_ ends in _".mjs"_, then > 1. Return _"module"_. > 1. If _url_ ends in _".cjs"_, then > 1. Return _"commonjs"_. > 1. If _pjson?.type_ exists and is _"module"_, then -> 1. If _url_ ends in _".js"_ or lacks a file extension, then +> 1. If _url_ ends in _".js"_, then > 1. Return _"module"_. > 1. Throw an _Unsupported File Extension_ error. > 1. Otherwise, -> 1. If _url_ lacks a file extension, then -> 1. Return _"commonjs"_. > 1. Throw an _Unsupported File Extension_ error. **READ_PACKAGE_SCOPE**(_url_) @@ -1632,3 +1658,4 @@ success! [the official standard format]: https://tc39.github.io/ecma262/#sec-modules [transpiler loader example]: #esm_transpiler_loader [6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index +[Top-Level Await]: https://github.com/tc39/proposal-top-level-await diff --git a/doc/api/fs.md b/doc/api/fs.md index 035d70b4808e3f..921decd751cba8 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1960,7 +1960,7 @@ Node.js callbacks. `fs.existsSync()` does not use a callback. ```js if (fs.existsSync('/etc/passwd')) { - console.log('The file exists.'); + console.log('The path exists.'); } ``` @@ -4941,6 +4941,18 @@ will be passed as `Buffer` objects. If `options.withFileTypes` is set to `true`, the resolved array will contain [`fs.Dirent`][] objects. +```js +const fs = require('fs'); + +async function print(path) { + const files = await fs.promises.readdir(path); + for (const file of files) { + console.log(file); + } +} +print('./').catch(console.error); +``` + ### `fsPromises.readFile(path[, options])` -* {number} **Default:** `120000` (2 minutes) +* {number} **Default:** 0 (no timeout) See [`http.Server#timeout`][]. diff --git a/doc/api/modules.md b/doc/api/modules.md index a8f9a60a683382..d69a2a2f1516d7 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -82,7 +82,7 @@ by checking `require.main.filename`. -The semantics of Node.js's `require()` function were designed to be general +The semantics of the Node.js `require()` function were designed to be general enough to support reasonable directory structures. Package manager programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to build native packages from Node.js modules without modification. @@ -162,7 +162,7 @@ require(X) from module at path Y c. THROW "not found" 4. LOAD_SELF_REFERENCE(X, dirname(Y)) 5. LOAD_NODE_MODULES(X, dirname(Y)) -7. THROW "not found" +6. THROW "not found" LOAD_AS_FILE(X) 1. If X is a file, load X as JavaScript text. STOP @@ -290,7 +290,7 @@ irrespective of whether or not `./foo` and `./FOO` are the same file. Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. -The core modules are defined within Node.js's source and are located in the +The core modules are defined within the Node.js source and are located in the `lib/` folder. Core modules are always preferentially loaded if their identifier is @@ -409,7 +409,7 @@ If this was in a folder at `./some-library`, then `require('./some-library')` would attempt to load `./some-library/lib/some-library.js`. -This is the extent of Node.js's awareness of `package.json` files. +This is the extent of the awareness of `package.json` files within Node.js. If there is no `package.json` file present in the directory, or if the `'main'` entry is missing or cannot be resolved, then Node.js @@ -485,7 +485,7 @@ Additionally, Node.js will search in the following list of GLOBAL_FOLDERS: * 2: `$HOME/.node_libraries` * 3: `$PREFIX/lib/node` -Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's +Where `$HOME` is the user's home directory, and `$PREFIX` is the Node.js configured `node_prefix`. These are mostly for historic reasons. @@ -618,10 +618,13 @@ Used to import modules, `JSON`, and local files. Modules can be imported from `node_modules`. Local modules and JSON files can be imported using a relative path (e.g. `./`, `./foo`, `./bar/baz`, `../foo`) that will be resolved against the directory named by [`__dirname`][] (if defined) or -the current working directory. +the current working directory. The relative paths of POSIX style are resolved +in an OS independent fashion, meaning that the examples above will work on +Windows in the same way they would on Unix systems. ```js -// Importing a local module: +// Importing a local module with a path relative to the `__dirname` or current +// working directory. (On Windows, this would resolve to .\path\myLocalModule.) const myLocalModule = require('./path/myLocalModule'); // Importing a JSON file: diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 80efc7aa48a66a..43e970cd080039 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -1436,7 +1436,7 @@ napiVersion: 1 ```C NAPI_EXTERN napi_status napi_reference_unref(napi_env env, napi_ref ref, - uint32_t* result);); + uint32_t* result); ``` * `[in] env`: The environment that the API is invoked under. @@ -4994,12 +4994,12 @@ napiVersion: 1 ```C napi_status napi_is_promise(napi_env env, - napi_value promise, + napi_value value, bool* is_promise); ``` * `[in] env`: The environment that the API is invoked under. -* `[in] promise`: The promise to examine +* `[in] value`: The value to examine * `[out] is_promise`: Flag indicating whether `promise` is a native promise object (that is, a promise object created by the underlying engine). diff --git a/doc/api/net.md b/doc/api/net.md index d04e7eff0789a7..84bda5e4e9bfed 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -26,18 +26,16 @@ sockets on other operating systems. [`socket.connect()`][] take a `path` parameter to identify IPC endpoints. On Unix, the local domain is also known as the Unix domain. The path is a -filesystem pathname. It gets truncated to a length of -`sizeof(sockaddr_un.sun_path) - 1`, which varies 91 and 107 bytes depending on -the operating system. The typical values are 107 on Linux and 103 on macOS. The -path is subject to the same naming conventions and permissions checks as would -be done on file creation. If the Unix domain socket (that is visible as a file -system path) is created and used in conjunction with one of Node.js' API -abstractions such as [`net.createServer()`][], it will be unlinked as part of -[`server.close()`][]. On the other hand, if it is created and used outside of -these abstractions, the user will need to manually remove it. The same applies -when the path was created by a Node.js API but the program crashes abruptly. -In short, a Unix domain socket once successfully created will be visible in the -filesystem, and will persist until unlinked. +filesystem pathname. It gets truncated to an OS-dependent length of +`sizeof(sockaddr_un.sun_path) - 1`. Typical values are 107 bytes on Linux and +103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, +it will unlink the Unix domain socket as well. For example, +[`net.createServer()`][] may create a Unix domain socket and +[`server.close()`][] will unlink it. But if a user creates the Unix domain +socket outside of these abstractions, the user will need to remove it. The same +applies when a Node.js API creates a Unix domain socket but the program then +crashes. In short, a Unix domain socket will be visible in the filesystem and +will persist until unlinked. On Windows, the local domain is implemented using a named pipe. The path *must* refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted, @@ -879,9 +877,16 @@ added: v0.1.90 * `noDelay` {boolean} **Default:** `true` * Returns: {net.Socket} The socket itself. -Disables the Nagle algorithm. By default TCP connections use the Nagle -algorithm, they buffer data before sending it off. Setting `true` for -`noDelay` will immediately fire off data each time `socket.write()` is called. +Enable/disable the use of Nagle's algorithm. + +When a TCP connection is created, it will have Nagle's algorithm enabled. + +Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency. + +Passing `true` for `noDelay` or not passing an argument will disable Nagle's +algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's +algorithm. ### `socket.setTimeout(timeout[, callback])` + +* {number} + +When `performanceEntry.entryType` is equal to `'gc'`, the `performance.flags` +property contains additional information about garbage collection operation. +The value may be one of: + +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE` + ## Class: `PerformanceNodeTiming extends PerformanceEntry` + +[`Worker`][] threads can create reports in the same way that the main thread +does. + +Reports will include information on any Workers that are children of the current +thread as part of the `workers` section, with each Worker generating a report +in the standard report format. + +The thread which is generating the report will wait for the reports from Worker +threads to finish. However, the latency for this will usually be low, as both +running JavaScript and the event loop are interrupted to generate the report. + [`process API documentation`]: process.html +[`Worker`]: worker_threads.html diff --git a/doc/api/stream.md b/doc/api/stream.md index a33bcdc56aa4f0..92dfe1a42a39bb 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1886,8 +1886,8 @@ methods only. The `writable._writev()` method may be implemented in addition or alternatively to `writable._write()` in stream implementations that are capable of processing -multiple chunks of data at once. If implemented, the method will be called with -all chunks of data currently buffered in the write queue. +multiple chunks of data at once. If implemented and if there is buffered data +from previous writes, `_writev()` will be called instead of `_write()`. The `writable._writev()` method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by @@ -2644,12 +2644,22 @@ const finished = util.promisify(stream.finished); const writable = fs.createWriteStream('./file'); +function drain(writable) { + if (writable.destroyed) { + return Promise.reject(new Error('premature close')); + } + return Promise.race([ + once(writable, 'drain'), + once(writable, 'close') + .then(() => Promise.reject(new Error('premature close'))) + ]); +} + async function pump(iterable, writable) { for await (const chunk of iterable) { // Handle backpressure on write(). if (!writable.write(chunk)) { - if (writable.destroyed) return; - await once(writable, 'drain'); + await drain(writable); } } writable.end(); diff --git a/doc/api/util.md b/doc/api/util.md index 9f48a5b8fd72e0..151e4769930280 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -4,9 +4,9 @@ > Stability: 2 - Stable -The `util` module is primarily designed to support the needs of Node.js' own -internal APIs. However, many of the utilities are useful for application and -module developers as well. It can be accessed using: +The `util` module supports the needs of Node.js internal APIs. Many of the +utilities are useful for application and module developers as well. To access +it: ```js const util = require('util'); diff --git a/doc/api/v8.md b/doc/api/v8.md index 1513f75ad0c12f..97ca7e0a2b3138 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -268,7 +268,9 @@ if (isMainThread) { The serialization API provides means of serializing JavaScript values in a way that is compatible with the [HTML structured clone algorithm][]. + The format is backward-compatible (i.e. safe to store to disk). +Equal JavaScript values may result in different serialized output. ### `v8.serialize(value)` + +* Returns: {Promise} A promise for a Readable Stream containing + a V8 heap snapshot + +Returns a readable stream for a V8 snapshot of the current state of the Worker. +See [`v8.getHeapSnapshot()`][] for more details. + +If the Worker thread is no longer running, which may occur before the +[`'exit'` event][] is emitted, the returned `Promise` will be rejected +immediately with an [`ERR_WORKER_NOT_RUNNING`][] error. + ### `worker.terminate()` /;var p=/^<\?/;var h=/\?>/;var v=/^/;var d=/^/;var m=/^$/;var E=new RegExp(n.source+"\\s*$");function blockHtml(e,r,t){var n=this;var b=n.options.blocks.join("|");var A=new RegExp("^|$))","i");var C=r.length;var w=0;var F;var y;var S;var _;var B;var O;var k;var x=[[a,f,true],[c,l,true],[p,h,true],[v,D,true],[d,g,true],[A,m,true],[E,m,false]];while(w{if(typeof r.expandRange==="function"){return r.expandRange(...e,r)}e.sort();const t=`[${e.join("-")}]`;try{new RegExp(t)}catch(r){return e.map(e=>i.escapeRegex(e)).join("..")}return t};const l=(e,r)=>{return`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`};const p=(e,r)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=f[e]||e;const t={...r};const p=typeof t.maxLength==="number"?Math.min(u,t.maxLength):u;let h=e.length;if(h>p){throw new SyntaxError(`Input length: ${h}, exceeds maximum allowed length: ${p}`)}const v={type:"bos",value:"",output:t.prepend||""};const D=[v];const d=t.capture?"":"?:";const g=i.isWindows(r);const m=n.globChars(g);const E=n.extglobChars(m);const{DOT_LITERAL:b,PLUS_LITERAL:A,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:F,NO_DOT:y,NO_DOT_SLASH:S,NO_DOTS_SLASH:_,QMARK:B,QMARK_NO_DOT:O,STAR:k,START_ANCHOR:x}=m;const R=e=>{return`(${d}(?:(?!${x}${e.dot?F:b}).)*?)`};const T=t.dot?"":y;const I=t.dot?B:O;let L=t.bash===true?R(t):k;if(t.capture){L=`(${L})`}if(typeof t.noext==="boolean"){t.noextglob=t.noext}const M={input:e,index:-1,start:0,dot:t.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:D};e=i.removePrefix(e,M);h=e.length;const j=[];const P=[];const N=[];let $=v;let H;const U=()=>M.index===h-1;const W=M.peek=((r=1)=>e[M.index+r]);const G=M.advance=(()=>e[++M.index]);const q=()=>e.slice(M.index+1);const Y=(e="",r=0)=>{M.consumed+=e;M.index+=r};const z=e=>{M.output+=e.output!=null?e.output:e.value;Y(e.value)};const V=()=>{let e=1;while(W()==="!"&&(W(2)!=="("||W(3)==="?")){G();M.start++;e++}if(e%2===0){return false}M.negated=true;M.start++;return true};const J=e=>{M[e]++;N.push(e)};const Z=e=>{M[e]--;N.pop()};const Q=e=>{if($.type==="globstar"){const r=M.braces>0&&(e.type==="comma"||e.type==="brace");const t=e.extglob===true||j.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!r&&!t){M.output=M.output.slice(0,-$.output.length);$.type="star";$.value="*";$.output=L;M.output+=$.output}}if(j.length&&e.type!=="paren"&&!E[e.value]){j[j.length-1].inner+=e.value}if(e.value||e.output)z(e);if($&&$.type==="text"&&e.type==="text"){$.value+=e.value;$.output=($.output||"")+e.value;return}e.prev=$;D.push(e);$=e};const X=(e,r)=>{const n={...E[r],conditions:1,inner:""};n.prev=$;n.parens=M.parens;n.output=M.output;const i=(t.capture?"(":"")+n.open;J("parens");Q({type:e,value:r,output:M.output?"":w});Q({type:"paren",extglob:true,value:G(),output:i});j.push(n)};const K=e=>{let r=e.close+(t.capture?")":"");if(e.type==="negate"){let n=L;if(e.inner&&e.inner.length>1&&e.inner.includes("/")){n=R(t)}if(n!==L||U()||/^\)+$/.test(q())){r=e.close=`)$))${n}`}if(e.prev.type==="bos"&&U()){M.negatedExtglob=true}}Q({type:"paren",extglob:true,value:H,output:r});Z("parens")};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=false;let u=e.replace(a,(e,r,t,i,u,o)=>{if(i==="\\"){n=true;return e}if(i==="?"){if(r){return r+i+(u?B.repeat(u.length):"")}if(o===0){return I+(u?B.repeat(u.length):"")}return B.repeat(t.length)}if(i==="."){return b.repeat(t.length)}if(i==="*"){if(r){return r+i+(u?L:"")}return L}return r?e:`\\${e}`});if(n===true){if(t.unescape===true){u=u.replace(/\\/g,"")}else{u=u.replace(/\\+/g,e=>{return e.length%2===0?"\\\\":e?"\\":""})}}if(u===e&&t.contains===true){M.output=e;return M}M.output=i.wrapOutput(u,M,r);return M}while(!U()){H=G();if(H==="\0"){continue}if(H==="\\"){const e=W();if(e==="/"&&t.bash!==true){continue}if(e==="."||e===";"){continue}if(!e){H+="\\";Q({type:"text",value:H});continue}const r=/^\\+/.exec(q());let n=0;if(r&&r[0].length>2){n=r[0].length;M.index+=n;if(n%2!==0){H+="\\"}}if(t.unescape===true){H=G()||""}else{H+=G()||""}if(M.brackets===0){Q({type:"text",value:H});continue}}if(M.brackets>0&&(H!=="]"||$.value==="["||$.value==="[^")){if(t.posix!==false&&H===":"){const e=$.value.slice(1);if(e.includes("[")){$.posix=true;if(e.includes(":")){const e=$.value.lastIndexOf("[");const r=$.value.slice(0,e);const t=$.value.slice(e+2);const n=o[t];if(n){$.value=r+n;M.backtrack=true;G();if(!v.output&&D.indexOf($)===1){v.output=w}continue}}}}if(H==="["&&W()!==":"||H==="-"&&W()==="]"){H=`\\${H}`}if(H==="]"&&($.value==="["||$.value==="[^")){H=`\\${H}`}if(t.posix===true&&H==="!"&&$.value==="["){H="^"}$.value+=H;z({value:H});continue}if(M.quotes===1&&H!=='"'){H=i.escapeRegex(H);$.value+=H;z({value:H});continue}if(H==='"'){M.quotes=M.quotes===1?0:1;if(t.keepQuotes===true){Q({type:"text",value:H})}continue}if(H==="("){J("parens");Q({type:"paren",value:H});continue}if(H===")"){if(M.parens===0&&t.strictBrackets===true){throw new SyntaxError(l("opening","("))}const e=j[j.length-1];if(e&&M.parens===e.parens+1){K(j.pop());continue}Q({type:"paren",value:H,output:M.parens?")":"\\)"});Z("parens");continue}if(H==="["){if(t.nobracket===true||!q().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true){throw new SyntaxError(l("closing","]"))}H=`\\${H}`}else{J("brackets")}Q({type:"bracket",value:H});continue}if(H==="]"){if(t.nobracket===true||$&&$.type==="bracket"&&$.value.length===1){Q({type:"text",value:H,output:`\\${H}`});continue}if(M.brackets===0){if(t.strictBrackets===true){throw new SyntaxError(l("opening","["))}Q({type:"text",value:H,output:`\\${H}`});continue}Z("brackets");const e=$.value.slice(1);if($.posix!==true&&e[0]==="^"&&!e.includes("/")){H=`/${H}`}$.value+=H;z({value:H});if(t.literalBrackets===false||i.hasRegexChars(e)){continue}const r=i.escapeRegex($.value);M.output=M.output.slice(0,-$.value.length);if(t.literalBrackets===true){M.output+=r;$.value=r;continue}$.value=`(${d}${r}|${$.value})`;M.output+=$.value;continue}if(H==="{"&&t.nobrace!==true){J("braces");const e={type:"brace",value:H,output:"(",outputIndex:M.output.length,tokensIndex:M.tokens.length};P.push(e);Q(e);continue}if(H==="}"){const e=P[P.length-1];if(t.nobrace===true||!e){Q({type:"text",value:H,output:H});continue}let r=")";if(e.dots===true){const e=D.slice();const n=[];for(let r=e.length-1;r>=0;r--){D.pop();if(e[r].type==="brace"){break}if(e[r].type!=="dots"){n.unshift(e[r].value)}}r=c(n,t);M.backtrack=true}if(e.comma!==true&&e.dots!==true){const t=M.output.slice(0,e.outputIndex);const n=M.tokens.slice(e.tokensIndex);e.value=e.output="\\{";H=r=`\\}`;M.output=t;for(const e of n){M.output+=e.output||e.value}}Q({type:"brace",value:H,output:r});Z("braces");P.pop();continue}if(H==="|"){if(j.length>0){j[j.length-1].conditions++}Q({type:"text",value:H});continue}if(H===","){let e=H;const r=P[P.length-1];if(r&&N[N.length-1]==="braces"){r.comma=true;e="|"}Q({type:"comma",value:H,output:e});continue}if(H==="/"){if($.type==="dot"&&M.index===M.start+1){M.start=M.index+1;M.consumed="";M.output="";D.pop();$=v;continue}Q({type:"slash",value:H,output:C});continue}if(H==="."){if(M.braces>0&&$.type==="dot"){if($.value===".")$.output=b;const e=P[P.length-1];$.type="dots";$.output+=H;$.value+=H;e.dots=true;continue}if(M.braces+M.parens===0&&$.type!=="bos"&&$.type!=="slash"){Q({type:"text",value:H,output:b});continue}Q({type:"dot",value:H,output:b});continue}if(H==="?"){const e=$&&$.value==="(";if(!e&&t.noextglob!==true&&W()==="("&&W(2)!=="?"){X("qmark",H);continue}if($&&$.type==="paren"){const e=W();let r=H;if(e==="<"&&!i.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if($.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/<([!=]|\w+>)/.test(q())){r=`\\${H}`}Q({type:"text",value:H,output:r});continue}if(t.dot!==true&&($.type==="slash"||$.type==="bos")){Q({type:"qmark",value:H,output:O});continue}Q({type:"qmark",value:H,output:B});continue}if(H==="!"){if(t.noextglob!==true&&W()==="("){if(W(2)!=="?"||!/[!=<:]/.test(W(3))){X("negate",H);continue}}if(t.nonegate!==true&&M.index===0){V();continue}}if(H==="+"){if(t.noextglob!==true&&W()==="("&&W(2)!=="?"){X("plus",H);continue}if($&&$.value==="("||t.regex===false){Q({type:"plus",value:H,output:A});continue}if($&&($.type==="bracket"||$.type==="paren"||$.type==="brace")||M.parens>0){Q({type:"plus",value:H});continue}Q({type:"plus",value:A});continue}if(H==="@"){if(t.noextglob!==true&&W()==="("&&W(2)!=="?"){Q({type:"at",extglob:true,value:H,output:""});continue}Q({type:"text",value:H});continue}if(H!=="*"){if(H==="$"||H==="^"){H=`\\${H}`}const e=s.exec(q());if(e){H+=e[0];M.index+=e[0].length}Q({type:"text",value:H});continue}if($&&($.type==="globstar"||$.star===true)){$.type="star";$.star=true;$.value+=H;$.output=L;M.backtrack=true;M.globstar=true;Y(H);continue}let r=q();if(t.noextglob!==true&&/^\([^?]/.test(r)){X("star",H);continue}if($.type==="star"){if(t.noglobstar===true){Y(H);continue}const n=$.prev;const i=n.prev;const u=n.type==="slash"||n.type==="bos";const o=i&&(i.type==="star"||i.type==="globstar");if(t.bash===true&&(!u||r[0]&&r[0]!=="/")){Q({type:"star",value:H,output:""});continue}const s=M.braces>0&&(n.type==="comma"||n.type==="brace");const a=j.length&&(n.type==="pipe"||n.type==="paren");if(!u&&n.type!=="paren"&&!s&&!a){Q({type:"star",value:H,output:""});continue}while(r.slice(0,3)==="/**"){const t=e[M.index+4];if(t&&t!=="/"){break}r=r.slice(3);Y("/**",3)}if(n.type==="bos"&&U()){$.type="globstar";$.value+=H;$.output=R(t);M.output=$.output;M.globstar=true;Y(H);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&!o&&U()){M.output=M.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=R(t)+(t.strictSlashes?")":"|$)");$.value+=H;M.globstar=true;M.output+=n.output+$.output;Y(H);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&r[0]==="/"){const e=r[1]!==void 0?"|$":"";M.output=M.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=`${R(t)}${C}|${C}${e})`;$.value+=H;M.output+=n.output+$.output;M.globstar=true;Y(H+G());Q({type:"slash",value:"/",output:""});continue}if(n.type==="bos"&&r[0]==="/"){$.type="globstar";$.value+=H;$.output=`(?:^|${C}|${R(t)}${C})`;M.output=$.output;M.globstar=true;Y(H+G());Q({type:"slash",value:"/",output:""});continue}M.output=M.output.slice(0,-$.output.length);$.type="globstar";$.output=R(t);$.value+=H;M.output+=$.output;M.globstar=true;Y(H);continue}const n={type:"star",value:H,output:L};if(t.bash===true){n.output=".*?";if($.type==="bos"||$.type==="slash"){n.output=T+n.output}Q(n);continue}if($&&($.type==="bracket"||$.type==="paren")&&t.regex===true){n.output=H;Q(n);continue}if(M.index===M.start||$.type==="slash"||$.type==="dot"){if($.type==="dot"){M.output+=S;$.output+=S}else if(t.dot===true){M.output+=_;$.output+=_}else{M.output+=T;$.output+=T}if(W()!=="*"){M.output+=w;$.output+=w}}Q(n)}while(M.brackets>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing","]"));M.output=i.escapeLast(M.output,"[");Z("brackets")}while(M.parens>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing",")"));M.output=i.escapeLast(M.output,"(");Z("parens")}while(M.braces>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing","}"));M.output=i.escapeLast(M.output,"{");Z("braces")}if(t.strictSlashes!==true&&($.type==="star"||$.type==="bracket")){Q({type:"maybe_slash",value:"",output:`${C}?`})}if(M.backtrack===true){M.output="";for(const e of M.tokens){M.output+=e.output!=null?e.output:e.value;if(e.suffix){M.output+=e.suffix}}}return M};p.fastpaths=((e,r)=>{const t={...r};const o=typeof t.maxLength==="number"?Math.min(u,t.maxLength):u;const s=e.length;if(s>o){throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`)}e=f[e]||e;const a=i.isWindows(r);const{DOT_LITERAL:c,SLASH_LITERAL:l,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:v,NO_DOTS:D,NO_DOTS_SLASH:d,STAR:g,START_ANCHOR:m}=n.globChars(a);const E=t.dot?D:v;const b=t.dot?d:v;const A=t.capture?"":"?:";const C={negated:false,prefix:""};let w=t.bash===true?".*?":g;if(t.capture){w=`(${w})`}const F=e=>{if(e.noglobstar===true)return w;return`(${A}(?:(?!${m}${e.dot?h:c}).)*?)`};const y=e=>{switch(e){case"*":return`${E}${p}${w}`;case".*":return`${c}${p}${w}`;case"*.*":return`${E}${w}${c}${p}${w}`;case"*/*":return`${E}${w}${l}${p}${b}${w}`;case"**":return E+F(t);case"**/*":return`(?:${E}${F(t)}${l})?${b}${p}${w}`;case"**/*.*":return`(?:${E}${F(t)}${l})?${b}${w}${c}${p}${w}`;case"**/.*":return`(?:${E}${F(t)}${l})?${c}${p}${w}`;default:{const r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;const t=y(r[1]);if(!t)return;return t+c+r[2]}}};const S=i.removePrefix(e,C);let _=y(S);if(_&&t.strictSlashes!==true){_+=`${l}?`}return _});e.exports=p},function(e){"use strict";e.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:"\n",CHAR_NO_BREAK_SPACE:" ",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"}},,function(e,r,t){"use strict";var n=t(945);function resolveYamlNull(e){if(e===null)return true;var r=e.length;return r===1&&e==="~"||r===4&&(e==="null"||e==="Null"||e==="NULL")}function constructYamlNull(){return null}function isNull(e){return e===null}e.exports=new n("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},function(e){"use strict";e.exports=sort;var r={true:2,false:1,null:0,undefined:0};function sort(e){e.messages.sort(comparator);return e}function comparator(e,t){return check(e,t,"line")||check(e,t,"column")||r[t.fatal]-r[e.fatal]||compare(e,t,"source")||compare(e,t,"ruleId")||compare(e,t,"reason")||0}function check(e,r,t){return(e[t]||0)-(r[t]||0)}function compare(e,r,t){return(e[t]||"").localeCompare(r[t]||"")}},function(e){e.exports={addendum:"addenda",aircraft:"aircraft",alga:"algae",alumna:"alumnae",alumnus:"alumni",amoeba:"amoebae",analysis:"analyses",antenna:"antennae",antithesis:"antitheses",apex:"apices",appendix:"appendices",automaton:"automata",axis:"axes",bacillus:"bacilli",bacterium:"bacteria",barracks:"barracks",basis:"bases",beau:"beaux",bison:"bison",buffalo:"buffalo",bureau:"bureaus",cactus:"cacti",calf:"calves",carp:"carp",census:"censuses",chassis:"chassis",cherub:"cherubim",child:"children","château":"châteaus",cod:"cod",codex:"codices",concerto:"concerti",corpus:"corpora",crisis:"crises",criterion:"criteria",curriculum:"curricula",datum:"data",deer:"deer",diagnosis:"diagnoses",die:"dice",dwarf:"dwarfs",echo:"echoes",elf:"elves",elk:"elk",ellipsis:"ellipses",embargo:"embargoes",emphasis:"emphases",erratum:"errata","faux pas":"faux pas",fez:"fezes",firmware:"firmware",fish:"fish",focus:"foci",foot:"feet",formula:"formulae",fungus:"fungi",gallows:"gallows",genus:"genera",goose:"geese",graffito:"graffiti",grouse:"grouse",half:"halves",hero:"heroes",hoof:"hooves",hovercraft:"hovercraft",hypothesis:"hypotheses",index:"indices",kakapo:"kakapo",knife:"knives",larva:"larvae",leaf:"leaves",libretto:"libretti",life:"lives",loaf:"loaves",locus:"loci",louse:"lice",man:"men",matrix:"matrices",means:"means",medium:"media",memorandum:"memoranda",millennium:"millennia",minutia:"minutiae",moose:"moose",mouse:"mice",nebula:"nebulae",nemesis:"nemeses",neurosis:"neuroses",news:"news",nucleus:"nuclei",oasis:"oases",offspring:"offspring",opus:"opera",ovum:"ova",ox:"oxen",paralysis:"paralyses",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",phylum:"phyla",pike:"pike",polyhedron:"polyhedra",potato:"potatoes",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",salmon:"salmon",scarf:"scarves",self:"selves",series:"series",sheep:"sheep",shelf:"shelves",shrimp:"shrimp",spacecraft:"spacecraft",species:"species",spectrum:"spectra",squid:"squid",stimulus:"stimuli",stratum:"strata",swine:"swine",syllabus:"syllabi",symposium:"symposia",synopsis:"synopses",synthesis:"syntheses",tableau:"tableaus",that:"those",thesis:"theses",thief:"thieves",this:"these",tomato:"tomatoes",tooth:"teeth",trout:"trout",tuna:"tuna",vertebra:"vertebrae",vertex:"vertices",veto:"vetoes",vita:"vitae",vortex:"vortices",watercraft:"watercraft",wharf:"wharves",wife:"wives",wolf:"wolves",woman:"women"}},function(e){e.exports=function isBuffer(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}},,,,function(e,r,t){"use strict";var n=t(560);e.exports=trough;trough.wrap=n;var i=[].slice;function trough(){var e=[];var r={};r.run=run;r.use=use;return r;function run(){var r=-1;var t=i.call(arguments,0,-1);var u=arguments[arguments.length-1];if(typeof u!=="function"){throw new Error("Expected function as last argument, not "+u)}next.apply(null,[null].concat(t));function next(o){var s=e[++r];var a=i.call(arguments,0);var f=a.slice(1);var c=t.length;var l=-1;if(o){u(o);return}while(++lString(e));if(t>2){return`one of ${r} ${e.slice(0,t-1).join(", ")}, or `+e[t-1]}else if(t===2){return`one of ${r} ${e[0]} or ${e[1]}`}else{return`of ${r} ${e[0]}`}}else{return`of ${r} ${String(e)}`}}function startsWith(e,r,t){return e.substr(!t||t<0?0:+t,r.length)===r}function endsWith(e,r,t){if(t===undefined||t>e.length){t=e.length}return e.substring(t-r.length,t)===r}function includes(e,r,t){if(typeof t!=="number"){t=0}if(t+r.length>e.length){return false}else{return e.indexOf(r,t)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",function(e,r){return'The value "'+r+'" is invalid for option "'+e+'"'},TypeError);createErrorType("ERR_INVALID_ARG_TYPE",function(e,r,t){let n;if(typeof r==="string"&&startsWith(r,"not ")){n="must not be";r=r.replace(/^not /,"")}else{n="must be"}let i;if(endsWith(e," argument")){i=`The ${e} ${n} ${oneOf(r,"type")}`}else{const t=includes(e,".")?"property":"argument";i=`The "${e}" ${t} ${n} ${oneOf(r,"type")}`}i+=`. Received type ${typeof t}`;return i},TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.codes=r},,function(e,r,t){"use strict";var n=t(940);var i=t(277);e.exports=factory;function factory(e){decoder.raw=decodeRaw;return decoder;function normalize(r){var t=e.offset;var n=r.line;var i=[];while(++n){if(!(n in t)){break}i.push((t[n]||0)+1)}return{start:r,indent:i}}function decoder(r,t,n){i(r,{position:normalize(t),warning:handleWarning,text:n,reference:n,textContext:e,referenceContext:e})}function decodeRaw(e,r,t){return i(e,n(t,{position:normalize(r),warning:handleWarning}))}function handleWarning(r,t,n){if(n!==3){e.file.message(r,t)}}}},,,,,,,function(e,r,t){"use strict";var n=t(429);var i=create(Error);e.exports=i;i.eval=create(EvalError);i.range=create(RangeError);i.reference=create(ReferenceError);i.syntax=create(SyntaxError);i.type=create(TypeError);i.uri=create(URIError);i.create=create;function create(e){FormattedError.displayName=e.displayName||e.name;return FormattedError;function FormattedError(r){if(r){r=n.apply(null,arguments)}return new e(r)}}},,function(e){"use strict";e.exports=locate;function locate(e,r){return e.indexOf("~~",r)}},function(e,r,t){"use strict";var n=t(277);var i=t(578);var u=t(22);e.exports=url;url.locator=u;url.notInLink=true;var o='"';var s="'";var a="(";var f=")";var c=",";var l=".";var p=":";var h=";";var v="<";var D="@";var d="[";var g="]";var m="http://";var E="https://";var b="mailto:";var A=[m,E,b];var C=A.length;function url(e,r,t){var u=this;var m;var E;var w;var F;var y;var S;var _;var B;var O;var k;var x;var R;var T;if(!u.options.gfm){return}m="";F=-1;while(++Fr?unescape(r):t))}else{throw new Error(`Invalid Chalk template style argument: ${r} (in style '${e}')`)}}return t}function parseStyle(e){t.lastIndex=0;const r=[];let n;while((n=t.exec(e))!==null){const e=n[1];if(n[2]){const t=parseArguments(e,n[2]);r.push([e].concat(t))}else{r.push([e])}}return r}function buildStyle(e,r){const t={};for(const e of r){for(const r of e.styles){t[r[0]]=e.inverse?null:r.slice(1)}}let n=e;for(const e of Object.keys(t)){if(Array.isArray(t[e])){if(!(e in n)){throw new Error(`Unknown Chalk style: ${e}`)}if(t[e].length>0){n=n[e].apply(n,t[e])}else{n=n[e]}}}return n}e.exports=((e,t)=>{const n=[];const i=[];let u=[];t.replace(r,(r,t,o,s,a,f)=>{if(t){u.push(unescape(t))}else if(s){const r=u.join("");u=[];i.push(n.length===0?r:buildStyle(e,n)(r));n.push({inverse:o,styles:parseStyle(s)})}else if(a){if(n.length===0){throw new Error("Found extraneous } in Chalk template literal")}i.push(buildStyle(e,n)(u.join("")));u=[];n.pop()}else{u.push(f)}});i.push(u.join(""));if(n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${n.length===1?"":"s"} (\`}\`)`;throw new Error(e)}return i.join("")})},function(e,r,t){"use strict";var n=t(945);var i=Object.prototype.hasOwnProperty;var u=Object.prototype.toString;function resolveYamlOmap(e){if(e===null)return true;var r=[],t,n,o,s,a,f=e;for(t=0,n=f.length;t4&&e[3]==="\\"){var i=e[2];if((i==="?"||i===".")&&e.slice(0,2)==="\\\\"){e=e.slice(2);n="//"}}var u=e.split(/[/\\]+/);if(r!==false&&u[u.length-1]===""){u.pop()}return n+u.join("/")}},,,function(e,r,t){var n=t(741);var i=t(622).join;var u=t(203);var o="/etc";var s=process.platform==="win32";var a=s?process.env.USERPROFILE:process.env.HOME;e.exports=function(e,r,f,c){if("string"!==typeof e)throw new Error("rc(name): name *must* be string");if(!f)f=t(109)(process.argv.slice(2));r=("string"===typeof r?n.json(r):r)||{};c=c||n.parse;var l=n.env(e+"_");var p=[r];var h=[];function addConfigFile(e){if(h.indexOf(e)>=0)return;var r=n.file(e);if(r){p.push(c(r));h.push(e)}}if(!s)[i(o,e,"config"),i(o,e+"rc")].forEach(addConfigFile);if(a)[i(a,".config",e,"config"),i(a,".config",e),i(a,"."+e,"config"),i(a,"."+e+"rc")].forEach(addConfigFile);addConfigFile(n.find("."+e+"rc"));if(l.config)addConfigFile(l.config);if(f.config)addConfigFile(f.config);return u.apply(null,p.concat([l,f,h.length?{configs:h,config:h[h.length-1]}:undefined]))}},function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(162);var o=t(353);e.exports=n("remark-lint:heading-style",headingStyle);var s=["atx","atx-closed","setext"];function headingStyle(e,r,t){t=s.indexOf(t)===-1?null:t;i(e,"heading",visitor);function visitor(e){if(!o(e)){if(t){if(u(e,t)!==t){r.message("Headings should use "+t,e)}}else{t=u(e,t)}}}}},,function(e){e.exports=require("tty")},,,,function(e,r,t){"use strict";var n=t(997);e.exports=lint;function lint(){this.use(lintMessageControl)}function lintMessageControl(){return n({name:"lint",source:"remark-lint"})}},,function(e,r,t){"use strict";var n=t(608);var i=t(427);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:list-item-indent",listItemIndent);var a=o.start;var f={"tab-size":true,mixed:true,space:true};function listItemIndent(e,r,t){var n=String(r);t=typeof t==="string"?t:"tab-size";if(f[t]!==true){r.fail("Invalid list-item indent style `"+t+"`: use either `'tab-size'`, `'space'`, or `'mixed'`")}u(e,"list",visitor);function visitor(e){var u=e.spread||e.loose;if(!s(e)){e.children.forEach(visitItem)}function visitItem(e){var o=e.children[0];var s=a(o);var f;var c;var l;var p;var h;f=n.slice(a(e).offset,s.offset).replace(/\[[x ]?]\s*$/i,"");c=f.trimRight().length;l=t==="tab-size"||t==="mixed"&&u?Math.ceil(c/4)*4:c+1;if(f.length!==l){p=l-f.length;h="Incorrect list-item indent: "+(p>0?"add":"remove")+" "+Math.abs(p)+" "+i("space",p);r.message(h,s)}}}}},,function(e,r,t){"use strict";var n=t(8);e.exports=strong;function strong(e){var r=n(this.options.strong,2);return r+this.all(e).join("")+r}},,,,,function(e,r,t){const n=t(299);let i;let u;let o;let s;let a;let f;let c;let l;let p;e.exports=function parse(e,r){i=String(e);u="start";o=[];s=0;a=1;f=0;c=undefined;l=undefined;p=undefined;do{c=lex();E[u]()}while(c.type!=="eof");if(typeof r==="function"){return internalize({"":p},"",r)}return p};function internalize(e,r,t){const n=e[r];if(n!=null&&typeof n==="object"){for(const e in n){const r=internalize(n,e,t);if(r===undefined){delete n[e]}else{n[e]=r}}}return t.call(e,r,n)}let h;let v;let D;let d;let g;function lex(){h="default";v="";D=false;d=1;for(;;){g=peek();const e=m[h]();if(e){return e}}}function peek(){if(i[s]){return String.fromCodePoint(i.codePointAt(s))}}function read(){const e=peek();if(e==="\n"){a++;f=0}else if(e){f+=e.length}else{f++}if(e){s+=e.length}return e}const m={default(){switch(g){case"\t":case"\v":case"\f":case" ":case" ":case"\ufeff":case"\n":case"\r":case"\u2028":case"\u2029":read();return;case"/":read();h="comment";return;case undefined:read();return newToken("eof")}if(n.isSpaceSeparator(g)){read();return}return m[u]()},comment(){switch(g){case"*":read();h="multiLineComment";return;case"/":read();h="singleLineComment";return}throw invalidChar(read())},multiLineComment(){switch(g){case"*":read();h="multiLineCommentAsterisk";return;case undefined:throw invalidChar(read())}read()},multiLineCommentAsterisk(){switch(g){case"*":read();return;case"/":read();h="default";return;case undefined:throw invalidChar(read())}read();h="multiLineComment"},singleLineComment(){switch(g){case"\n":case"\r":case"\u2028":case"\u2029":read();h="default";return;case undefined:read();return newToken("eof")}read()},value(){switch(g){case"{":case"[":return newToken("punctuator",read());case"n":read();literal("ull");return newToken("null",null);case"t":read();literal("rue");return newToken("boolean",true);case"f":read();literal("alse");return newToken("boolean",false);case"-":case"+":if(read()==="-"){d=-1}h="sign";return;case".":v=read();h="decimalPointLeading";return;case"0":v=read();h="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":v=read();h="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",Infinity);case"N":read();literal("aN");return newToken("numeric",NaN);case'"':case"'":D=read()==='"';v="";h="string";return}throw invalidChar(read())},identifierNameStartEscape(){if(g!=="u"){throw invalidChar(read())}read();const e=unicodeEscape();switch(e){case"$":case"_":break;default:if(!n.isIdStartChar(e)){throw invalidIdentifier()}break}v+=e;h="identifierName"},identifierName(){switch(g){case"$":case"_":case"‌":case"‍":v+=read();return;case"\\":read();h="identifierNameEscape";return}if(n.isIdContinueChar(g)){v+=read();return}return newToken("identifier",v)},identifierNameEscape(){if(g!=="u"){throw invalidChar(read())}read();const e=unicodeEscape();switch(e){case"$":case"_":case"‌":case"‍":break;default:if(!n.isIdContinueChar(e)){throw invalidIdentifier()}break}v+=e;h="identifierName"},sign(){switch(g){case".":v=read();h="decimalPointLeading";return;case"0":v=read();h="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":v=read();h="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",d*Infinity);case"N":read();literal("aN");return newToken("numeric",NaN)}throw invalidChar(read())},zero(){switch(g){case".":v+=read();h="decimalPoint";return;case"e":case"E":v+=read();h="decimalExponent";return;case"x":case"X":v+=read();h="hexadecimal";return}return newToken("numeric",d*0)},decimalInteger(){switch(g){case".":v+=read();h="decimalPoint";return;case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},decimalPointLeading(){if(n.isDigit(g)){v+=read();h="decimalFraction";return}throw invalidChar(read())},decimalPoint(){switch(g){case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();h="decimalFraction";return}return newToken("numeric",d*Number(v))},decimalFraction(){switch(g){case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},decimalExponent(){switch(g){case"+":case"-":v+=read();h="decimalExponentSign";return}if(n.isDigit(g)){v+=read();h="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentSign(){if(n.isDigit(g)){v+=read();h="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentInteger(){if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},hexadecimal(){if(n.isHexDigit(g)){v+=read();h="hexadecimalInteger";return}throw invalidChar(read())},hexadecimalInteger(){if(n.isHexDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},string(){switch(g){case"\\":read();v+=escape();return;case'"':if(D){read();return newToken("string",v)}v+=read();return;case"'":if(!D){read();return newToken("string",v)}v+=read();return;case"\n":case"\r":throw invalidChar(read());case"\u2028":case"\u2029":separatorChar(g);break;case undefined:throw invalidChar(read())}v+=read()},start(){switch(g){case"{":case"[":return newToken("punctuator",read())}h="value"},beforePropertyName(){switch(g){case"$":case"_":v=read();h="identifierName";return;case"\\":read();h="identifierNameStartEscape";return;case"}":return newToken("punctuator",read());case'"':case"'":D=read()==='"';h="string";return}if(n.isIdStartChar(g)){v+=read();h="identifierName";return}throw invalidChar(read())},afterPropertyName(){if(g===":"){return newToken("punctuator",read())}throw invalidChar(read())},beforePropertyValue(){h="value"},afterPropertyValue(){switch(g){case",":case"}":return newToken("punctuator",read())}throw invalidChar(read())},beforeArrayValue(){if(g==="]"){return newToken("punctuator",read())}h="value"},afterArrayValue(){switch(g){case",":case"]":return newToken("punctuator",read())}throw invalidChar(read())},end(){throw invalidChar(read())}};function newToken(e,r){return{type:e,value:r,line:a,column:f}}function literal(e){for(const r of e){const e=peek();if(e!==r){throw invalidChar(read())}read()}}function escape(){const e=peek();switch(e){case"b":read();return"\b";case"f":read();return"\f";case"n":read();return"\n";case"r":read();return"\r";case"t":read();return"\t";case"v":read();return"\v";case"0":read();if(n.isDigit(peek())){throw invalidChar(read())}return"\0";case"x":read();return hexEscape();case"u":read();return unicodeEscape();case"\n":case"\u2028":case"\u2029":read();return"";case"\r":read();if(peek()==="\n"){read()}return"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw invalidChar(read());case undefined:throw invalidChar(read())}return read()}function hexEscape(){let e="";let r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read();r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read();return String.fromCodePoint(parseInt(e,16))}function unicodeEscape(){let e="";let r=4;while(r-- >0){const r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read()}return String.fromCodePoint(parseInt(e,16))}const E={start(){if(c.type==="eof"){throw invalidEOF()}push()},beforePropertyName(){switch(c.type){case"identifier":case"string":l=c.value;u="afterPropertyName";return;case"punctuator":pop();return;case"eof":throw invalidEOF()}},afterPropertyName(){if(c.type==="eof"){throw invalidEOF()}u="beforePropertyValue"},beforePropertyValue(){if(c.type==="eof"){throw invalidEOF()}push()},beforeArrayValue(){if(c.type==="eof"){throw invalidEOF()}if(c.type==="punctuator"&&c.value==="]"){pop();return}push()},afterPropertyValue(){if(c.type==="eof"){throw invalidEOF()}switch(c.value){case",":u="beforePropertyName";return;case"}":pop()}},afterArrayValue(){if(c.type==="eof"){throw invalidEOF()}switch(c.value){case",":u="beforeArrayValue";return;case"]":pop()}},end(){}};function push(){let e;switch(c.type){case"punctuator":switch(c.value){case"{":e={};break;case"[":e=[];break}break;case"null":case"boolean":case"numeric":case"string":e=c.value;break}if(p===undefined){p=e}else{const r=o[o.length-1];if(Array.isArray(r)){r.push(e)}else{r[l]=e}}if(e!==null&&typeof e==="object"){o.push(e);if(Array.isArray(e)){u="beforeArrayValue"}else{u="beforePropertyName"}}else{const e=o[o.length-1];if(e==null){u="end"}else if(Array.isArray(e)){u="afterArrayValue"}else{u="afterPropertyValue"}}}function pop(){o.pop();const e=o[o.length-1];if(e==null){u="end"}else if(Array.isArray(e)){u="afterArrayValue"}else{u="afterPropertyValue"}}function invalidChar(e){if(e===undefined){return syntaxError(`JSON5: invalid end of input at ${a}:${f}`)}return syntaxError(`JSON5: invalid character '${formatChar(e)}' at ${a}:${f}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${a}:${f}`)}function invalidIdentifier(){f-=5;return syntaxError(`JSON5: invalid identifier character at ${a}:${f}`)}function separatorChar(e){console.warn(`JSON5: '${formatChar(e)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(e){const r={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(r[e]){return r[e]}if(e<" "){const r=e.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return e}function syntaxError(e){const r=new SyntaxError(e);r.lineNumber=a;r.columnNumber=f;return r}},function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(827);var o=t(784)("unified-engine:find-up");var s=t(145);e.exports=FindUp;var a=n.readFile;var f=i.resolve;var c=i.relative;var l=i.join;var p=i.dirname;FindUp.prototype.load=load;function FindUp(e){var r=this;var t=e.filePath;r.cache={};r.cwd=e.cwd;r.detect=e.detect;r.names=e.names;r.create=e.create;if(t){r.givenFilePath=f(e.cwd,t)}}function load(e,r){var t=this;var n=t.cache;var i=t.givenFilePath;var h=t.givenFile;var v=t.names;var D=t.create;var d=t.cwd;var g;if(i){if(h){apply(r,h)}else{h=[r];t.givenFile=h;o("Checking given file `%s`",i);a(i,loadGiven)}return}if(!t.detect){return r()}e=f(d,e);g=p(e);if(g in n){apply(r,n[g])}else{n[g]=[r];find(g)}function loadGiven(e,r){var n=t.givenFile;var s;if(e){s=u("Cannot read given file `%s`\n%s",c(d,i),e.stack);s.code="ENOENT";s.path=e.path;s.syscall=e.syscall}else{try{s=D(r,i);o("Read given file `%s`",i)}catch(e){s=u("Cannot parse given file `%s`\n%s",c(d,i),e.stack);o(e.message)}}h=s;t.givenFile=s;applyAll(n,s)}function find(r){var t=-1;var i=v.length;next();function next(){var u;if(++tt&&u0?"Remove":"Add")+" "+Math.abs(v)+" "+o("space",v)+" before this heading’s content";r.message(g,f(i[0]))}}if(s==="atx-closed"){h=c(i[i.length-1]);v=c(e).column-h.column-1-n;if(v){g="Remove "+v+" "+o("space",v)+" after this heading’s content";r.message(g,h)}}}}},,,,,,,,function(e,r,t){"use strict";var n=t(43);e.exports=n.DEFAULT=new n({include:[t(723)],explicit:[t(386),t(629),t(352)]})},,function(e,r,t){"use strict";var n=t(608);e.exports=n("remark-lint:no-file-name-consecutive-dashes",noFileNameConsecutiveDashes);var i="Do not use consecutive dashes in a file name";function noFileNameConsecutiveDashes(e,r){if(r.stem&&/-{2,}/.test(r.stem)){r.message(i)}}},function(e,r,t){"use strict";var n;try{var i=require;n=i("buffer").Buffer}catch(e){}var u=t(945);var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";function resolveYamlBinary(e){if(e===null)return false;var r,t,n=0,i=e.length,u=o;for(t=0;t64)continue;if(r<0)return false;n+=6}return n%8===0}function constructYamlBinary(e){var r,t,i=e.replace(/[\r\n=]/g,""),u=i.length,s=o,a=0,f=[];for(r=0;r>16&255);f.push(a>>8&255);f.push(a&255)}a=a<<6|s.indexOf(i.charAt(r))}t=u%4*6;if(t===0){f.push(a>>16&255);f.push(a>>8&255);f.push(a&255)}else if(t===18){f.push(a>>10&255);f.push(a>>2&255)}else if(t===12){f.push(a>>4&255)}if(n){return n.from?n.from(f):new n(f)}return f}function representYamlBinary(e){var r="",t=0,n,i,u=e.length,s=o;for(n=0;n>18&63];r+=s[t>>12&63];r+=s[t>>6&63];r+=s[t&63]}t=(t<<8)+e[n]}i=u%3;if(i===0){r+=s[t>>18&63];r+=s[t>>12&63];r+=s[t>>6&63];r+=s[t&63]}else if(i===2){r+=s[t>>10&63];r+=s[t>>4&63];r+=s[t<<2&63];r+=s[64]}else if(i===1){r+=s[t>>2&63];r+=s[t<<4&63];r+=s[64];r+=s[64]}return r}function isBinary(e){return n&&n.isBuffer(e)}e.exports=new u("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary})},function(e){"use strict";e.exports=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false}},,,function(e,r,t){e.exports=t(669).deprecate},,,,function(e,r,t){"use strict";var n=t(945);e.exports=new n("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return e!==null?e:[]}})},,function(e,r,t){"use strict";var n=t(433);var i=t(940);var u=t(458);e.exports=parse;parse.Parser=u;function parse(e){var r=this.data("settings");var t=n(u);t.prototype.options=i(t.prototype.options,r,e);this.Parser=t}},,function(e,r,t){"use strict";const n=t(622);const i=t(282);const u=t(747);const o=(e,r,t)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof r!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof r}\``)}try{e=u.realpathSync(e)}catch(r){if(r.code==="ENOENT"){e=n.resolve(e)}else if(t){return}else{throw r}}const o=n.join(e,"noop.js");const s=()=>i._resolveFilename(r,{id:o,filename:o,paths:i._nodeModulePaths(e)});if(t){try{return s()}catch(e){return}}return s()};e.exports=((e,r)=>o(e,r));e.exports.silent=((e,r)=>o(e,r,true))},function(e){"use strict";e.exports=decimal;function decimal(e){var r=typeof e==="string"?e.charCodeAt(0):e;return r>=48&&r<=57}},,function(e){"use strict";e.exports=hexadecimal;function hexadecimal(e){var r=typeof e==="string"?e.charCodeAt(0):e;return r>=97&&r<=102||r>=65&&r<=70||r>=48&&r<=57}},,function(e){"use strict";e.exports=markdownTable;var r=/\./;var t=/\.[^.]*$/;var n=" ";var i="\n";var u="-";var o=".";var s=":";var a="c";var f="l";var c="r";var l="|";var p=3;function markdownTable(e,t){var h=t||{};var v=h.delimiter;var D=h.start;var d=h.end;var g=h.align;var m=h.stringLength||lengthNoop;var E=0;var b=-1;var A=e.length;var C=[];var w;var F;var y;var S;var _;var B;var O;var k;var x;var R;var T;var I;g=g?g.concat():[];if(v===null||v===undefined){v=n+l+n}if(D===null||D===undefined){D=l+n}if(d===null||d===undefined){d=n+l}while(++bE){E=S.length}while(++BC[B]){C[B]=O}}}if(typeof g==="string"){g=pad(E,g).split("")}B=-1;while(++BC[B]){C[B]=k}}}b=-1;while(++bp?R:p}else{R=C[B]}w=g[B];x=w===c||w===""?u:s;x+=pad(R-2,u);x+=w!==f&&w!==""?s:u;F[B]=x}y.splice(1,0,F.join(v))}return D+y.join(d+i+D)+d}function stringify(e){return e===null||e===undefined?"":String(e)}function lengthNoop(e){return String(e).length}function pad(e,r){return new Array(e+1).join(r||n)}function dotindex(e){var r=t.exec(e);return r?r.index+1:e.length}},,function(e){"use strict";e.exports=trimTrailingLines;var r="\n";function trimTrailingLines(e){var t=String(e);var n=t.length;while(t.charAt(--n)===r){}return t.slice(0,n+1)}},,function(e){"use strict";var r=new Set;function emitExperimentalWarning(e){if(r.has(e))return;var t=e+" is an experimental feature. This feature could "+"change at any time";r.add(e);process.emitWarning(t,"ExperimentalWarning")}function noop(){}e.exports.emitExperimentalWarning=process.emitWarning?emitExperimentalWarning:noop},,function(e){"use strict";e.exports=factory;var r="\\";function factory(e,t){return unescape;function unescape(n){var i=0;var u=n.indexOf(r);var o=e[t];var s=[];var a;while(u!==-1){s.push(n.slice(i,u));i=u+1;a=n.charAt(i);if(!a||o.indexOf(a)===-1){s.push(r)}u=n.indexOf(r,i+1)}s.push(n.slice(i));return s.join("")}}},,,,function(e){e.exports=extend;var r=Object.prototype.hasOwnProperty;function extend(){var e={};for(var t=0;t0}function Chalk(e){if(!this||!(this instanceof Chalk)||this.template){const r={};applyOptions(r,e);r.template=function(){const e=[].slice.call(arguments);return chalkTag.apply(null,[r.template].concat(e))};Object.setPrototypeOf(r,Chalk.prototype);Object.setPrototypeOf(r.template,r);r.template.constructor=Chalk;return r.template}applyOptions(this,e)}if(s){i.blue.open=""}for(const e of Object.keys(i)){i[e].closeRe=new RegExp(n(i[e].close),"g");c[e]={get(){const r=i[e];return build.call(this,this._styles?this._styles.concat(r):[r],this._empty,e)}}}c.visible={get(){return build.call(this,this._styles||[],true,"visible")}};i.color.closeRe=new RegExp(n(i.color.close),"g");for(const e of Object.keys(i.color.ansi)){if(f.has(e)){continue}c[e]={get(){const r=this.level;return function(){const t=i.color[a[r]][e].apply(null,arguments);const n={open:t,close:i.color.close,closeRe:i.color.closeRe};return build.call(this,this._styles?this._styles.concat(n):[n],this._empty,e)}}}}i.bgColor.closeRe=new RegExp(n(i.bgColor.close),"g");for(const e of Object.keys(i.bgColor.ansi)){if(f.has(e)){continue}const r="bg"+e[0].toUpperCase()+e.slice(1);c[r]={get(){const r=this.level;return function(){const t=i.bgColor[a[r]][e].apply(null,arguments);const n={open:t,close:i.bgColor.close,closeRe:i.bgColor.closeRe};return build.call(this,this._styles?this._styles.concat(n):[n],this._empty,e)}}}}const l=Object.defineProperties(()=>{},c);function build(e,r,t){const n=function(){return applyStyle.apply(n,arguments)};n._styles=e;n._empty=r;const i=this;Object.defineProperty(n,"level",{enumerable:true,get(){return i.level},set(e){i.level=e}});Object.defineProperty(n,"enabled",{enumerable:true,get(){return i.enabled},set(e){i.enabled=e}});n.hasGrey=this.hasGrey||t==="gray"||t==="grey";n.__proto__=l;return n}function applyStyle(){const e=arguments;const r=e.length;let t=String(arguments[0]);if(r===0){return""}if(r>1){for(let n=1;ni){return false}}return check(e,n,t)&&check(e,g)}function isKnown(e,r,t){var n=a?a.indexOf(e)!==-1:true;if(!n){p.warn("Unknown rule: cannot "+r+" `'"+e+"'`",t)}return n}function getState(e){var r=e?d[e]:g;if(r&&r.length!==0){return r[r.length-1].state}if(!e){return!f}if(f){return c.indexOf(e)!==-1}return l.indexOf(e)===-1}function toggle(e,r,t){var n=t?d[t]:g;var i;var u;if(!n){n=[];d[t]=n}u=getState(t);i=r;if(i!==u){n.push({state:i,position:e})}if(!t){for(t in d){toggle(e,r,t)}}}function check(e,r,t){var n=r&&r.length;var i=-1;var u;while(--n>i){u=r[n];if(!u.position||!u.position.line||!u.position.column){continue}if(u.position.line=e){return}if(o){s.push({start:i,end:e});o=false}i=e}}},,,,function(e,r,t){"use strict";var n=t(797);e.exports=copy;var i="&";var u=/[-!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~_]/;function copy(e,r){var t=e.length;var o=r.length;var s=[];var a=0;var f=0;var c;while(f0){t=Math.min(10,Math.floor(t));a=" ".substr(0,t)}}else if(typeof t==="string"){a=t.substr(0,10)}return serializeProperty("",{"":e});function serializeProperty(e,r){let t=r[e];if(t!=null){if(typeof t.toJSON5==="function"){t=t.toJSON5(e)}else if(typeof t.toJSON==="function"){t=t.toJSON(e)}}if(s){t=s.call(r,e,t)}if(t instanceof Number){t=Number(t)}else if(t instanceof String){t=String(t)}else if(t instanceof Boolean){t=t.valueOf()}switch(t){case null:return"null";case true:return"true";case false:return"false"}if(typeof t==="string"){return quoteString(t,false)}if(typeof t==="number"){return String(t)}if(typeof t==="object"){return Array.isArray(t)?serializeArray(t):serializeObject(t)}return undefined}function quoteString(e){const r={"'":.1,'"':.2};const t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let i="";for(let u=0;ur[e]=0){throw TypeError("Converting circular structure to JSON5")}i.push(e);let r=u;u=u+a;let t=o||Object.keys(e);let n=[];for(const r of t){const t=serializeProperty(r,e);if(t!==undefined){let e=serializeKey(r)+":";if(a!==""){e+=" "}e+=t;n.push(e)}}let s;if(n.length===0){s="{}"}else{let e;if(a===""){e=n.join(",");s="{"+e+"}"}else{let t=",\n"+u;e=n.join(t);s="{\n"+u+e+",\n"+r+"}"}}i.pop();u=r;return s}function serializeKey(e){if(e.length===0){return quoteString(e,true)}const r=String.fromCodePoint(e.codePointAt(0));if(!n.isIdStartChar(r)){return quoteString(e,true)}for(let t=r.length;t=0){throw TypeError("Converting circular structure to JSON5")}i.push(e);let r=u;u=u+a;let t=[];for(let r=0;r2)t=r.call(arguments,1);if(e){try{n=u.throw(e)}catch(e){return exit(e)}}if(!e){try{n=u.next(t)}catch(e){return exit(e)}}if(n.done)return exit(null,n.value);n.value=toThunk(n.value,i);if("function"==typeof n.value){var o=false;try{n.value.call(i,function(){if(o)return;o=true;next.apply(i,arguments)})}catch(e){setImmediate(function(){if(o)return;o=true;next(e)})}return}next(new TypeError("You may only yield a function, promise, generator, array, or object, "+'but the following was passed: "'+String(n.value)+'"'))}}}function toThunk(e,r){if(isGeneratorFunction(e)){return co(e.call(r))}if(isGenerator(e)){return co(e)}if(isPromise(e)){return promiseToThunk(e)}if("function"==typeof e){return e}if(isObject(e)||Array.isArray(e)){return objectToThunk.call(r,e)}return e}function objectToThunk(e){var r=this;var t=Array.isArray(e);return function(n){var i=Object.keys(e);var u=i.length;var o=t?new Array(u):new e.constructor;var s;if(!u){setImmediate(function(){n(null,o)});return}if(!t){for(var a=0;a params.length; + var result; + + if (callback) { + params.push(done); + } + + try { + result = fn.apply(null, params); + } catch (error) { + // Well, this is quite the pickle. + // `fn` received a callback and invoked it (thus continuing the pipeline), + // but later also threw an error. + // We’re not about to restart the pipeline again, so the only thing left + // to do is to throw the thing instead. + if (callback && invoked) { + throw error + } + + return done(error) + } + + if (!callback) { + if (result && typeof result.then === 'function') { + result.then(then, done); + } else if (result instanceof Error) { + done(result); + } else { + then(result); + } + } + } + + // Invoke `next`, only once. + function done() { + if (!invoked) { + invoked = true; + + callback.apply(null, arguments); + } + } + + // Invoke `done` with one value. + // Tracks if an error is passed, too. + function then(value) { + done(null, value); + } +} + +var trough_1 = trough; + +trough.wrap = wrap_1; + +var slice$1 = [].slice; + +// Create new middleware. +function trough() { + var fns = []; + var middleware = {}; + + middleware.run = run; + middleware.use = use; + + return middleware + + // Run `fns`. Last argument must be a completion handler. + function run() { + var index = -1; + var input = slice$1.call(arguments, 0, -1); + var done = arguments[arguments.length - 1]; + + if (typeof done !== 'function') { + throw new Error('Expected function as last argument, not ' + done) + } + + next.apply(null, [null].concat(input)); + + // Run the next `fn`, if any. + function next(err) { + var fn = fns[++index]; + var params = slice$1.call(arguments, 0); + var values = params.slice(1); + var length = input.length; + var pos = -1; + + if (err) { + done(err); + return + } + + // Copy non-nully input into values. + while (++pos < length) { + if (values[pos] === null || values[pos] === undefined) { + values[pos] = input[pos]; + } + } + + input = values; + + // Next or done. + if (fn) { + wrap_1(fn, next).apply(null, input); + } else { + done.apply(null, [null].concat(input)); + } + } + } + + // Add `fn` to the list. + function use(fn) { + if (typeof fn !== 'function') { + throw new Error('Expected `fn` to be a function, not ' + fn) + } + + fns.push(fn); + + return middleware + } +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +function getCjsExportFromNamespace (n) { + return n && n['default'] || n; +} + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +var isNothing_1 = isNothing; +var isObject_1 = isObject; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend; + +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; + +// YAML error class. http://stackoverflow.com/questions/8458984 + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +var exception = YAMLException; + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +var mark = Mark; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type; + +/*eslint-disable max-len*/ + + + + + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new exception('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type$1) { return type$1 instanceof type; })) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +var schema = Schema; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int_1 = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float_1 = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = new schema({ + include: [ + failsafe + ], + implicit: [ + _null, + bool, + int_1, + float_1 + ] +}); + +var core = new schema({ + include: [ + json + ] +}); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = commonjsRequire; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$1.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var default_safe = new schema({ + include: [ + core + ], + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +var _undefined = new type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +var regexp = new type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require$1 = commonjsRequire; + esprima = _require$1('esprima'); +} catch (_) { + /*global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + + + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +var _function = new type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +var default_full = schema.DEFAULT = new schema({ + include: [ + default_safe + ], + explicit: [ + _undefined, + regexp, + _function + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || default_full; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new exception( + message, + new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$2.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$2.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$2.call(overridableKeys, keyNode) && + _hasOwnProperty$2.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!state.anchorMap.hasOwnProperty(alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only assigned to plain scalars. So, it isn't + // needed to check for 'kind' conformity. + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + var documents = loadDocuments(input, options), index, length; + + if (typeof iterator !== 'function') { + return documents; + } + + for (index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, output, options) { + if (typeof output === 'function') { + loadAll(input, output, common.extend({ schema: default_safe }, options)); + } else { + return loadAll(input, common.extend({ schema: default_safe }, options)); + } +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: default_safe }, options)); +} + + +var loadAll_1 = loadAll; +var load_1 = load; +var safeLoadAll_1 = safeLoadAll; +var safeLoad_1 = safeLoad; + +var loader = { + loadAll: loadAll_1, + load: load_1, + safeLoadAll: safeLoadAll_1, + safeLoad: safeLoad_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + + +var _toString$2 = Object.prototype.toString; +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty$3.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State$1(options) { + this.schema = options['schema'] || default_full; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + && c !== CHAR_COLON + && c !== CHAR_SHARP; +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = state.condenseFlow ? '"' : ''; + + if (index !== 0) pairBuffer += ', '; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString$2.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty$3.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString$2.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State$1(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: default_safe }, options)); +} + +var dump_1 = dump; +var safeDump_1 = safeDump; + +var dumper = { + dump: dump_1, + safeDump: safeDump_1 +}; + +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; +} + + +var Type$1 = type; +var Schema$1 = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SAFE_SCHEMA = default_safe; +var DEFAULT_FULL_SCHEMA = default_full; +var load$1 = loader.load; +var loadAll$1 = loader.loadAll; +var safeLoad$1 = loader.safeLoad; +var safeLoadAll$1 = loader.safeLoadAll; +var dump$1 = dumper.dump; +var safeDump$1 = dumper.safeDump; +var YAMLException$1 = exception; + +// Deprecated schema names from JS-YAML 2.0.x +var MINIMAL_SCHEMA = failsafe; +var SAFE_SCHEMA = default_safe; +var DEFAULT_SCHEMA = default_full; + +// Deprecated functions from JS-YAML 1.x.x +var scan = deprecated('scan'); +var parse = deprecated('parse'); +var compose = deprecated('compose'); +var addConstructor = deprecated('addConstructor'); + +var jsYaml = { + Type: Type$1, + Schema: Schema$1, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA, + DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA, + load: load$1, + loadAll: loadAll$1, + safeLoad: safeLoad$1, + safeLoadAll: safeLoadAll$1, + dump: dump$1, + safeDump: safeDump$1, + YAMLException: YAMLException$1, + MINIMAL_SCHEMA: MINIMAL_SCHEMA, + SAFE_SCHEMA: SAFE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + scan: scan, + parse: parse, + compose: compose, + addConstructor: addConstructor +}; + +var jsYaml$1 = jsYaml; + +var isArrayish = function isArrayish(obj) { + if (!obj) { + return false; + } + + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; + +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } + + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } + + message = message instanceof Error + ? message.message + : (message || this.message); + + Error.call(this, message); + Error.captureStackTrace(this, errorExError); + + this.name = name; + + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); + + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } + + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); + + var overwrittenStack = null; + + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; + + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; + + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); + + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } + + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } + + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } + + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util$1.inherits(errorExError, Error); + } + + return errorExError; +}; + +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; + + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } + + return message; + } + }; +}; + +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; + + if (v) { + return str.replace('%s', v.toString()); + } + + return null; + } + }; +}; + +var errorEx_1 = errorEx; + +var jsonParseBetterErrors = parseJson; +function parseJson (txt, reviver, context) { + context = context || 20; + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0; + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)); + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i); + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null; + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context; + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context; + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'`; + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'`; + } + throw e + } +} + +const JSONError = errorEx_1('JSONError', { + fileName: errorEx_1.append('in %s') +}); + +var parseJson$1 = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } + + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + jsonParseBetterErrors(input, reviver); + + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); + + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } + + throw jsonErr; + } +}; + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse$1(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse$1(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * Active `debug` instances. + */ + createDebug.instances = []; + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; + // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + + // env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + + return debug; + } + + function destroy() { + const index = createDebug.instances.indexOf(this); + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + return false; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + const instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +var common$1 = setup; + +var browser = createCommonjsModule(function (module, exports) { +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ +function log(...args) { + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return typeof console === 'object' && + console.log && + console.log(...args); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = common$1(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; +}); +var browser_1 = browser.log; +var browser_2 = browser.formatArgs; +var browser_3 = browser.save; +var browser_4 = browser.load; +var browser_5 = browser.useColors; +var browser_6 = browser.storage; +var browser_7 = browser.colors; + +var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +var node = createCommonjsModule(function (module, exports) { +/** + * Module dependencies. + */ + + + + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = supportsColor_1; + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util$1.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = common$1(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util$1.inspect(v, this.inspectOpts) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util$1.inspect(v, this.inspectOpts); +}; +}); +var node_1 = node.init; +var node_2 = node.log; +var node_3 = node.formatArgs; +var node_4 = node.save; +var node_5 = node.load; +var node_6 = node.useColors; +var node_7 = node.colors; +var node_8 = node.inspectOpts; + +var src = createCommonjsModule(function (module) { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = browser; +} else { + module.exports = node; +} +}); + +const resolveFrom = (fromDirectory, moduleId, silent) => { + if (typeof fromDirectory !== 'string') { + throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); + } + + if (typeof moduleId !== 'string') { + throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); + } + + try { + fromDirectory = fs$1.realpathSync(fromDirectory); + } catch (error) { + if (error.code === 'ENOENT') { + fromDirectory = path$1.resolve(fromDirectory); + } else if (silent) { + return; + } else { + throw error; + } + } + + const fromFile = path$1.join(fromDirectory, 'noop.js'); + + const resolveFileName = () => module$1._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: module$1._nodeModulePaths(fromDirectory) + }); + + if (silent) { + try { + return resolveFileName(); + } catch (error) { + return; + } + } + + return resolveFileName(); +}; + +var resolveFrom_1 = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId); +var silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true); +resolveFrom_1.silent = silent; + +var ini = createCommonjsModule(function (module, exports) { +exports.parse = exports.decode = decode; + +exports.stringify = exports.encode = encode; + +exports.safe = safe; +exports.unsafe = unsafe; + +var eol = typeof process !== 'undefined' && + process.platform === 'win32' ? '\r\n' : '\n'; + +function encode (obj, opt) { + var children = []; + var out = ''; + + if (typeof opt === 'string') { + opt = { + section: opt, + whitespace: false + }; + } else { + opt = opt || {}; + opt.whitespace = opt.whitespace === true; + } + + var separator = opt.whitespace ? ' = ' : '='; + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k]; + if (val && Array.isArray(val)) { + val.forEach(function (item) { + out += safe(k + '[]') + separator + safe(item) + '\n'; + }); + } else if (val && typeof val === 'object') { + children.push(k); + } else { + out += safe(k) + separator + safe(val) + eol; + } + }); + + if (opt.section && out.length) { + out = '[' + safe(opt.section) + ']' + eol + out; + } + + children.forEach(function (k, _, __) { + var nk = dotSplit(k).join('\\.'); + var section = (opt.section ? opt.section + '.' : '') + nk; + var child = encode(obj[k], { + section: section, + whitespace: opt.whitespace + }); + if (out.length && child.length) { + out += eol; + } + out += child; + }); + + return out +} + +function dotSplit (str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') + }) +} + +function decode (str) { + var out = {}; + var p = out; + var section = null; + // section |key = value + var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; + var lines = str.split(/[\r\n]+/g); + + lines.forEach(function (line, _, __) { + if (!line || line.match(/^\s*[;#]/)) return + var match = line.match(re); + if (!match) return + if (match[1] !== undefined) { + section = unsafe(match[1]); + p = out[section] = out[section] || {}; + return + } + var key = unsafe(match[2]); + var value = match[3] ? unsafe(match[4]) : true; + switch (value) { + case 'true': + case 'false': + case 'null': value = JSON.parse(value); + } + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === '[]') { + key = key.substring(0, key.length - 2); + if (!p[key]) { + p[key] = []; + } else if (!Array.isArray(p[key])) { + p[key] = [p[key]]; + } + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) { + p[key].push(value); + } else { + p[key] = value; + } + }); + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || + typeof out[k] !== 'object' || + Array.isArray(out[k])) { + return false + } + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit(k); + var p = out; + var l = parts.pop(); + var nl = l.replace(/\\\./g, '.'); + parts.forEach(function (part, _, __) { + if (!p[part] || typeof p[part] !== 'object') p[part] = {}; + p = p[part]; + }); + if (p === out && nl === l) { + return false + } + p[nl] = out[k]; + return true + }).forEach(function (del, _, __) { + delete out[del]; + }); + + return out +} + +function isQuoted (val) { + return (val.charAt(0) === '"' && val.slice(-1) === '"') || + (val.charAt(0) === "'" && val.slice(-1) === "'") +} + +function safe (val) { + return (typeof val !== 'string' || + val.match(/[=\r\n]/) || + val.match(/^\[/) || + (val.length > 1 && + isQuoted(val)) || + val !== val.trim()) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, '\\#') +} + +function unsafe (val, doUnesc) { + val = (val || '').trim(); + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") { + val = val.substr(1, val.length - 2); + } + try { val = JSON.parse(val); } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + var esc = false; + var unesc = ''; + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i); + if (esc) { + if ('\\;#'.indexOf(c) !== -1) { + unesc += c; + } else { + unesc += '\\' + c; + } + esc = false; + } else if (';#'.indexOf(c) !== -1) { + break + } else if (c === '\\') { + esc = true; + } else { + unesc += c; + } + } + if (esc) { + unesc += '\\'; + } + return unesc.trim() + } + return val +} +}); +var ini_1 = ini.parse; +var ini_2 = ini.decode; +var ini_3 = ini.stringify; +var ini_4 = ini.encode; +var ini_5 = ini.safe; +var ini_6 = ini.unsafe; + +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +var stripJsonComments = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; + +var utils = createCommonjsModule(function (module, exports) { + + + + + +var parse = exports.parse = function (content) { + + //if it ends in .json or starts with { then it must be json. + //must be done this way, because ini accepts everything. + //can't just try and parse it and let it throw if it's not ini. + //everything is ini. even json with a syntax error. + + if(/^\s*{/.test(content)) + return JSON.parse(stripJsonComments(content)) + return ini.parse(content) + +}; + +var file = exports.file = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }); + + //path.join breaks if it's a not a string, so just skip this. + for(var i in args) + if('string' !== typeof args[i]) + return + + var file = path$1.join.apply(null, args); + try { + return fs$1.readFileSync(file,'utf-8') + } catch (err) { + return + } +}; + +var json = exports.json = function () { + var content = file.apply(null, arguments); + return content ? parse(content) : null +}; + +var env = exports.env = function (prefix, env) { + env = env || process.env; + var obj = {}; + var l = prefix.length; + for(var k in env) { + if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { + + var keypath = k.substring(l).split('__'); + + // Trim empty strings from keypath array + var _emptyStringIndex; + while ((_emptyStringIndex=keypath.indexOf('')) > -1) { + keypath.splice(_emptyStringIndex, 1); + } + + var cursor = obj; + keypath.forEach(function _buildSubObj(_subkey,i){ + + // (check for _subkey first so we ignore empty strings) + // (check for cursor to avoid assignment to primitive objects) + if (!_subkey || typeof cursor !== 'object') + return + + // If this is the last key, just stuff the value in there + // Assigns actual value from env variable to final key + // (unless it's just an empty string- in that case use the last valid key) + if (i === keypath.length-1) + cursor[_subkey] = env[k]; + + + // Build sub-object if nothing already exists at the keypath + if (cursor[_subkey] === undefined) + cursor[_subkey] = {}; + + // Increment cursor used to track the object at the current depth + cursor = cursor[_subkey]; + + }); + + } + + } + + return obj +}; + +var find = exports.find = function () { + var rel = path$1.join.apply(null, [].slice.call(arguments)); + + function find(start, rel) { + var file = path$1.join(start, rel); + try { + fs$1.statSync(file); + return file + } catch (err) { + if(path$1.dirname(start) !== start) // root + return find(path$1.dirname(start), rel) + } + } + return find(process.cwd(), rel) +}; +}); +var utils_1 = utils.parse; +var utils_2 = utils.file; +var utils_3 = utils.json; +var utils_4 = utils.env; +var utils_5 = utils.find; + +var deepExtend_1 = createCommonjsModule(function (module) { + +function isSpecificValue(val) { + return ( + val instanceof Buffer + || val instanceof Date + || val instanceof RegExp + ) ? true : false; +} + +function cloneSpecificValue(val) { + if (val instanceof Buffer) { + var x = Buffer.alloc + ? Buffer.alloc(val.length) + : new Buffer(val.length); + val.copy(x); + return x; + } else if (val instanceof Date) { + return new Date(val.getTime()); + } else if (val instanceof RegExp) { + return new RegExp(val); + } else { + throw new Error('Unexpected situation'); + } +} + +/** + * Recursive cloning array. + */ +function deepCloneArray(arr) { + var clone = []; + arr.forEach(function (item, index) { + if (typeof item === 'object' && item !== null) { + if (Array.isArray(item)) { + clone[index] = deepCloneArray(item); + } else if (isSpecificValue(item)) { + clone[index] = cloneSpecificValue(item); + } else { + clone[index] = deepExtend({}, item); + } + } else { + clone[index] = item; + } + }); + return clone; +} + +function safeGetProperty(object, property) { + return property === '__proto__' ? undefined : object[property]; +} + +/** + * Extening object that entered in first argument. + * + * Returns extended object or false if have no target object or incorrect type. + * + * If you wish to clone source object (without modify it), just use empty new + * object as first argument, like this: + * deepExtend({}, yourObj_1, [yourObj_N]); + */ +var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { + if (arguments.length < 1 || typeof arguments[0] !== 'object') { + return false; + } + + if (arguments.length < 2) { + return arguments[0]; + } + + var target = arguments[0]; + + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); + + var val, src; + + args.forEach(function (obj) { + // skip argument if isn't an object, is null, or is an array + if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { + return; + } + + Object.keys(obj).forEach(function (key) { + src = safeGetProperty(target, key); // source value + val = safeGetProperty(obj, key); // new value + + // recursion prevention + if (val === target) { + return; + + /** + * if new value isn't object then just overwrite by new value + * instead of extending. + */ + } else if (typeof val !== 'object' || val === null) { + target[key] = val; + return; + + // just clone arrays (and recursive clone objects inside) + } else if (Array.isArray(val)) { + target[key] = deepCloneArray(val); + return; + + // custom cloning and overwrite for specific objects + } else if (isSpecificValue(val)) { + target[key] = cloneSpecificValue(val); + return; + + // overwrite by new value if source isn't object or array + } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { + target[key] = deepExtend({}, val); + return; + + // source value and new value is objects both, extending... + } else { + target[key] = deepExtend(src, val); + return; + } + }); + }); + + return target; +}; +}); + +var minimist = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +var join = path$1.join; + +var etc = '/etc'; +var win = process.platform === "win32"; +var home = win + ? process.env.USERPROFILE + : process.env.HOME; + +var rc = function (name, defaults, argv, parse) { + if('string' !== typeof name) + throw new Error('rc(name): name *must* be string') + if(!argv) + argv = minimist(process.argv.slice(2)); + defaults = ( + 'string' === typeof defaults + ? utils.json(defaults) : defaults + ) || {}; + + parse = parse || utils.parse; + + var env = utils.env(name + '_'); + + var configs = [defaults]; + var configFiles = []; + function addConfigFile (file) { + if (configFiles.indexOf(file) >= 0) return + var fileConfig = utils.file(file); + if (fileConfig) { + configs.push(parse(fileConfig)); + configFiles.push(file); + } + } + + // which files do we look at? + if (!win) + [join(etc, name, 'config'), + join(etc, name + 'rc')].forEach(addConfigFile); + if (home) + [join(home, '.config', name, 'config'), + join(home, '.config', name), + join(home, '.' + name, 'config'), + join(home, '.' + name + 'rc')].forEach(addConfigFile); + addConfigFile(utils.find('.'+name+'rc')); + if (env.config) addConfigFile(env.config); + if (argv.config) addConfigFile(argv.config); + + return deepExtend_1.apply(null, configs.concat([ + env, + argv, + configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, + ])) +}; + +function homedir() { + var env = process.env; + var home = env.HOME; + var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME; + + if (process.platform === 'win32') { + return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null; + } + + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); + } + + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); + } + + return home || null; +} + +var osHomedir = typeof os.homedir === 'function' ? os.homedir : homedir; + +var home$1 = osHomedir(); + +var untildify = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return home$1 ? str.replace(/^~($|\/|\\)/, home$1 + '$1') : str; +}; + +var shellsubstitute = function (s, vars) { + return s.replace(/(\\*)(\$([_a-z0-9]+)|\${([_a-z0-9]+)})/ig, function (_, escape, varExpression, variable, bracedVariable) { + if (!(escape.length % 2)) { + return escape.substring(Math.ceil(escape.length / 2)) + (vars[variable || bracedVariable] || ''); + } else { + return escape.substring(1) + varExpression; + } + }); +}; + +var npmPrefix = function () { + var rcPrefix = rc('npm', null, []).prefix; + + if (rcPrefix) { + return untildify(shellsubstitute(rcPrefix, process.env)); + } + else if (process.platform == 'win32') { + return path$1.dirname(process.execPath); + } + else { + return path$1.resolve(process.execPath, '../..'); + } +}; + +var resolve = resolveFrom_1.silent; +var npmPrefix$1 = npmPrefix(); + +var loadPlugin_1 = loadPlugin; +loadPlugin.resolve = resolvePlugin; + +var electron = process.versions.electron !== undefined; +var argv = process.argv[1] || /* istanbul ignore next */ ''; +var nvm = process.env.NVM_BIN; +var globally = electron || argv.indexOf(npmPrefix$1) === 0; +var windows = process.platform === 'win32'; +var prefix = windows ? /* istanbul ignore next */ '' : 'lib'; +var globals = path$1.resolve(npmPrefix$1, prefix, 'node_modules'); + +// If we’re in Electron, we’re running in a modified Node that cannot really +// install global node modules. To find the actual modules, the user has to +// either set `prefix` in their `.npmrc` (which is picked up by `npm-prefix`). +// Most people don’t do that, and some use NVM instead to manage different +// versions of Node. Luckily NVM leaks some environment variables that we can +// pick up on to try and detect the actual modules. +/* istanbul ignore next */ +if (electron && nvm && !fs$1.existsSync(globals)) { + globals = path$1.resolve(nvm, '..', prefix, 'node_modules'); +} + +// Load the plug-in found using `resolvePlugin`. +function loadPlugin(name, options) { + return commonjsRequire(resolvePlugin(name, options) || name) +} + +// Find a plugin. +// +// See also: +// +// +// +// Uses the standard node module loading strategy to find $name in each given +// `cwd` (and optionally the global `node_modules` directory). +// +// If a prefix is given and $name is not a path, `$prefix-$name` is also +// searched (preferring these over non-prefixed modules). +function resolvePlugin(name, options) { + var settings = options || {}; + var prefix = settings.prefix; + var cwd = settings.cwd; + var global = settings.global; + var filePath; + var sources; + var length; + var index; + var plugin; + var slash; + var scope = ''; + + if (global === null || global === undefined) { + global = globally; + } + + if (cwd && typeof cwd === 'object') { + sources = cwd.concat(); + } else { + sources = [cwd || process.cwd()]; + } + + // Non-path. + if (name.charAt(0) !== '.') { + if (global) { + sources.push(globals); + } + + // Unprefix module. + if (prefix) { + prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-'; + + // Scope? + if (name.charAt(0) === '@') { + slash = name.indexOf('/'); + + // Let’s keep the algorithm simple. No need to care if this is a + // “valid” scope (I think?). But we do check for the slash. + if (slash !== -1) { + scope = name.slice(0, slash + 1); + name = name.slice(slash + 1); + } + } + + if (name.slice(0, prefix.length) !== prefix) { + plugin = scope + prefix + name; + } + + name = scope + name; + } + } + + length = sources.length; + index = -1; + + while (++index < length) { + cwd = sources[index]; + filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name); + + if (filePath) { + return filePath + } + } + + return null +} + +var format = createCommonjsModule(function (module) { +(function() { + + //// Export the API + var namespace; + + // CommonJS / Node module + { + namespace = module.exports = format; + } + + namespace.format = format; + namespace.vsprintf = vsprintf; + + if (typeof console !== 'undefined' && typeof console.log === 'function') { + namespace.printf = printf; + } + + function printf(/* ... */) { + console.log(format.apply(null, arguments)); + } + + function vsprintf(fmt, replacements) { + return format.apply(null, [fmt].concat(replacements)); + } + + function format(fmt) { + var argIndex = 1 // skip initial format argument + , args = [].slice.call(arguments) + , i = 0 + , n = fmt.length + , result = '' + , c + , escaped = false + , arg + , tmp + , leadingZero = false + , precision + , nextArg = function() { return args[argIndex++]; } + , slurpNumber = function() { + var digits = ''; + while (/\d/.test(fmt[i])) { + digits += fmt[i++]; + c = fmt[i]; + } + return digits.length > 0 ? parseInt(digits) : null; + } + ; + for (; i < n; ++i) { + c = fmt[i]; + if (escaped) { + escaped = false; + if (c == '.') { + leadingZero = false; + c = fmt[++i]; + } + else if (c == '0' && fmt[i + 1] == '.') { + leadingZero = true; + i += 2; + c = fmt[i]; + } + else { + leadingZero = true; + } + precision = slurpNumber(); + switch (c) { + case 'b': // number in binary + result += parseInt(nextArg(), 10).toString(2); + break; + case 'c': // character + arg = nextArg(); + if (typeof arg === 'string' || arg instanceof String) + result += arg; + else + result += String.fromCharCode(parseInt(arg, 10)); + break; + case 'd': // number in decimal + result += parseInt(nextArg(), 10); + break; + case 'f': // floating point number + tmp = String(parseFloat(nextArg()).toFixed(precision || 6)); + result += leadingZero ? tmp : tmp.replace(/^0/, ''); + break; + case 'j': // JSON + result += JSON.stringify(nextArg()); + break; + case 'o': // number in octal + result += '0' + parseInt(nextArg(), 10).toString(8); + break; + case 's': // string + result += nextArg(); + break; + case 'x': // lowercase hexadecimal + result += '0x' + parseInt(nextArg(), 10).toString(16); + break; + case 'X': // uppercase hexadecimal + result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase(); + break; + default: + result += c; + break; + } + } else if (c === '%') { + escaped = true; + } else { + result += c; + } + } + return result; + } + +}()); +}); + +var fault = create(Error); + +var fault_1 = fault; + +fault.eval = create(EvalError); +fault.range = create(RangeError); +fault.reference = create(ReferenceError); +fault.syntax = create(SyntaxError); +fault.type = create(TypeError); +fault.uri = create(URIError); + +fault.create = create; + +// Create a new `EConstructor`, with the formatted `format` as a first argument. +function create(EConstructor) { + FormattedError.displayName = EConstructor.displayName || EConstructor.name; + + return FormattedError + + function FormattedError(format$1) { + if (format$1) { + format$1 = format.apply(null, arguments); + } + + return new EConstructor(format$1) + } +} + +var immutable = extend$1; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend$1() { + var target = {}; + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target +} + +var isObject$1 = function isObject(x) { + return typeof x === "object" && x !== null; +}; + +var toString = Object.prototype.toString; + +var xIsString = isString; + +function isString(obj) { + return toString.call(obj) === "[object String]" +} + +var debug = src('unified-engine:find-up'); + + +var findUp = FindUp; + +var read = fs$1.readFile; +var resolve$1 = path$1.resolve; +var relative = path$1.relative; +var join$1 = path$1.join; +var dirname = path$1.dirname; + +FindUp.prototype.load = load$2; + +function FindUp(options) { + var self = this; + var fp = options.filePath; + + self.cache = {}; + self.cwd = options.cwd; + self.detect = options.detect; + self.names = options.names; + self.create = options.create; + + if (fp) { + self.givenFilePath = resolve$1(options.cwd, fp); + } +} + +function load$2(filePath, callback) { + var self = this; + var cache = self.cache; + var givenFilePath = self.givenFilePath; + var givenFile = self.givenFile; + var names = self.names; + var create = self.create; + var cwd = self.cwd; + var parent; + + if (givenFilePath) { + if (givenFile) { + apply(callback, givenFile); + } else { + givenFile = [callback]; + self.givenFile = givenFile; + debug('Checking given file `%s`', givenFilePath); + read(givenFilePath, loadGiven); + } + + return + } + + if (!self.detect) { + return callback() + } + + filePath = resolve$1(cwd, filePath); + parent = dirname(filePath); + + if (parent in cache) { + apply(callback, cache[parent]); + } else { + cache[parent] = [callback]; + find(parent); + } + + function loadGiven(error, buf) { + var cbs = self.givenFile; + var result; + + if (error) { + result = fault_1( + 'Cannot read given file `%s`\n%s', + relative(cwd, givenFilePath), + error.stack + ); + result.code = 'ENOENT'; + result.path = error.path; + result.syscall = error.syscall; + } else { + try { + result = create(buf, givenFilePath); + debug('Read given file `%s`', givenFilePath); + } catch (error2) { + result = fault_1( + 'Cannot parse given file `%s`\n%s', + relative(cwd, givenFilePath), + error2.stack + ); + debug(error2.message); + } + } + + givenFile = result; + self.givenFile = result; + applyAll(cbs, result); + } + + function find(directory) { + var index = -1; + var length = names.length; + + next(); + + function next() { + var parent; + + // Try to read the next file. + // We do not use `readdir` because on huge directories, that could be + // *very* slow. + if (++index < length) { + read(join$1(directory, names[index]), done); + } else { + parent = dirname(directory); + + if (directory === parent) { + debug('No files found for `%s`', filePath); + found(); + } else if (parent in cache) { + apply(found, cache[parent]); + } else { + cache[parent] = [found]; + find(parent); + } + } + } + + function done(error, buf) { + var name = names[index]; + var fp = join$1(directory, name); + var contents; + + /* istanbul ignore if - Hard to test. */ + if (error) { + if (error.code === 'ENOENT') { + return next() + } + + error = fault_1( + 'Cannot read file `%s`\n%s', + relative(cwd, fp), + error.message + ); + debug(error.message); + return found(error) + } + + try { + contents = create(buf, fp); + } catch (error2) { + return found( + fault_1('Cannot parse file `%s`\n%s', relative(cwd, fp), error2.message) + ) + } + + /* istanbul ignore else - maybe used in the future. */ + if (contents) { + debug('Read file `%s`', fp); + found(null, contents); + } else { + next(); + } + } + + function found(error, result) { + var cbs = cache[directory]; + cache[directory] = error || result; + applyAll(cbs, error || result); + } + } + + function applyAll(cbs, result) { + var index = cbs.length; + + while (index--) { + apply(cbs[index], result); + } + } + + function apply(cb, result) { + if (isObject$1(result) && typeof result[0] === 'function') { + result.push(cb); + } else if (result instanceof Error) { + cb(result); + } else { + cb(null, result); + } + } +} + +var configuration = createCommonjsModule(function (module) { + + + + + +var debug = src('unified-engine:configuration'); +var resolve = loadPlugin_1.resolve; + + + + + + +module.exports = Config; + +var own = {}.hasOwnProperty; +var extname = path$1.extname; +var basename = path$1.basename; +var dirname = path$1.dirname; +var relative = path$1.relative; + +var loaders = { + '.json': loadJSON, + '.js': loadScript, + '.yaml': loadYAML, + '.yml': loadYAML +}; + +var defaultLoader = loadJSON; + +Config.prototype.load = load; + +function Config(options) { + var rcName = options.rcName; + var packageField = options.packageField; + var names = []; + + this.cwd = options.cwd; + this.packageField = options.packageField; + this.pluginPrefix = options.pluginPrefix; + this.configTransform = options.configTransform; + this.defaultConfig = options.defaultConfig; + + if (rcName) { + names.push(rcName, rcName + '.js', rcName + '.yml', rcName + '.yaml'); + debug('Looking for `%s` configuration files', names); + } + + if (packageField) { + names.push('package.json'); + debug('Looking for `%s` fields in `package.json` files', packageField); + } + + this.given = {settings: options.settings, plugins: options.plugins}; + this.create = create.bind(this); + + this.findUp = new findUp({ + filePath: options.rcPath, + cwd: options.cwd, + detect: options.detectConfig, + names: names, + create: this.create + }); +} + +function load(filePath, callback) { + var searchPath = filePath || path$1.resolve(this.cwd, 'stdin.js'); + var self = this; + + self.findUp.load(searchPath, done); + + function done(error, res) { + if (error || res) { + return callback(error, res) + } + + callback(null, self.create()); + } +} + +function create(buf, filePath) { + var self = this; + var transform = self.configTransform; + var defaults = self.defaultConfig; + var fn = (filePath && loaders[extname(filePath)]) || defaultLoader; + var options = {prefix: self.pluginPrefix, cwd: self.cwd}; + var result = {settings: {}, plugins: []}; + var contents = buf ? fn.apply(self, arguments) : undefined; + + if (transform && contents !== undefined) { + contents = transform(contents, filePath); + } + + // Exit if we did find a `package.json`, but it does not have configuration. + if (buf && contents === undefined && basename(filePath) === 'package.json') { + return + } + + if (contents === undefined) { + if (defaults) { + merge(result, defaults, null, immutable(options, {root: self.cwd})); + } + } else { + merge(result, contents, null, immutable(options, {root: dirname(filePath)})); + } + + merge(result, self.given, null, immutable(options, {root: self.cwd})); + + return result +} + +// Basically `Module.prototype.load`, but for a buffer instead of a file path. +function loadScript(buf, filePath) { + var submodule = module$1._cache[filePath]; + + if (!submodule) { + submodule = new module$1(filePath, module); + submodule.filename = filePath; + submodule.paths = module$1._nodeModulePaths(dirname(filePath)); + submodule._compile(String(buf), filePath); + submodule.loaded = true; + module$1._cache[filePath] = submodule; + } + + return submodule.exports +} + +function loadYAML(buf, filePath) { + return jsYaml$1.safeLoad(buf, {filename: basename(filePath)}) +} + +function loadJSON(buf, filePath) { + var result = parseJson$1(buf, filePath); + + if (basename(filePath) === 'package.json') { + result = result[this.packageField]; + } + + return result +} + +function merge(target, raw, val, options) { + var root = options.root; + var cwd = options.cwd; + var prefix = options.prefix; + + if (isObject$1(raw)) { + addPreset(raw); + } else { + throw new Error('Expected preset, not `' + raw + '`') + } + + return target + + function addPreset(result) { + var plugins = result.plugins; + + if (plugins === null || plugins === undefined) ; else if (isObject$1(plugins)) { + if ('length' in plugins) { + addEach(plugins); + } else { + addIn(plugins); + } + } else { + throw new Error( + 'Expected a list or object of plugins, not `' + plugins + '`' + ) + } + + target.settings = immutable(target.settings, result.settings); + } + + function addEach(result) { + var length = result.length; + var index = -1; + var value; + + while (++index < length) { + value = result[index]; + + if (isObject$1(value) && 'length' in value) { + use.apply(null, value); + } else { + use(value); + } + } + } + + function addIn(result) { + var key; + + for (key in result) { + use(key, result[key]); + } + } + + function use(usable, value) { + if (xIsString(usable)) { + addModule(usable, value); + } else if (typeof usable === 'function') { + addPlugin(usable, value); + } else { + merge(target, usable, value, options); + } + } + + function addModule(id, value) { + var fp = resolve(id, {cwd: root, prefix: prefix}); + var res; + + if (fp) { + try { + res = commonjsRequire(fp); + } catch (error) { + throw fault_1( + 'Cannot parse script `%s`\n%s', + relative(root, fp), + error.stack + ) + } + + try { + if (typeof res === 'function') { + addPlugin(res, value); + } else { + merge(target, res, value, immutable(options, {root: dirname(fp)})); + } + } catch (error) { + throw fault_1( + 'Error: Expected preset or plugin, not %s, at `%s`', + res, + relative(root, fp) + ) + } + } else { + fp = relative(cwd, path$1.resolve(root, id)); + addPlugin( + failingModule(fp, new Error('Could not find module `' + id + '`')), + value + ); + } + } + + function addPlugin(result, value) { + var entry = find(target.plugins, result); + + if (entry) { + reconfigure(entry, value); + } else { + target.plugins.push([result, value]); + } + } +} + +function reconfigure(entry, value) { + if (value !== false && entry[1] !== false && isObject$1(value)) { + value = immutable(entry[1], value); + } + + entry[1] = value; +} + +function find(entries, plugin) { + var length = entries.length; + var index = -1; + var entry; + + while (++index < length) { + entry = entries[index]; + + if (entry[0] === plugin) { + return entry + } + } +} + +function failingModule(id, error) { + var cache = failingModule.cache || (failingModule.cache = {}); + var submodule = own.call(cache, id) ? cache[id] : (cache[id] = fail); + return submodule + function fail() { + throw error + } +} +}); + +var configure_1 = configure; + +function configure(context, settings) { + context.configuration = new configuration(settings); +} + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const REGEX_TEST_BLANK_LINE = /^\s+$/; +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +const REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; + +const SLASH = '/'; +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore'; + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}); + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : '' +); + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? ' ' + : '' + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => ' ' + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\^$.|*+(){]/g, + match => `\\${match}` + ], + + [ + // > [abc] matches any character inside the brackets + // > (in this case a, b, or c); + /\[([^\]/]*)($|\])/g, + (match, p1, p2) => p2 === ']' + ? `[${sanitizeRange(p1)}]` + : `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match '' + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + + return `${prefix}(?=$|\\/$)` + } + ], + + [ + // unescape + /\\\\\\/g, + () => '\\' + ] +]; + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null); + +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern]; + if (r) { + return r + } + + // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS + + const source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ); + + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +}; + +const isString$1 = subject => typeof subject === 'string'; + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString$1(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; + } +} + +const createRule = (pattern, ignorecase) => { + const origin = pattern; + let negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + + const regex = makeRegex(pattern, negative, ignorecase); + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +}; + +const throwError$1 = (message, Ctor) => { + throw new Ctor(message) +}; + +const checkPath = (path, originalPath, doThrow) => { + if (!isString$1(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore '', so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d'; + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +}; + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); + +checkPath.isNotRelative = isNotRelative; +checkPath.convert = p => p; + +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + define(this, KEY_IGNORE, true); + this._initCache(); + } + + _initCache () { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false; + + makeArray( + isString$1(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false; + let unignored = false; + + this._rules.forEach(rule => { + const {negative} = rule; + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path); + + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + + checkPath(path, originalPath, throwError$1); + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options); + +const returnFalse = () => false; + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse); + +factory.isPathValid = isPathValid; + +// Fixes typescript +factory.default = factory; + +var ignore = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/'); + + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path); +} + +var ignore$1 = Ignore$1; + +Ignore$1.prototype.check = check; + +var dirname$1 = path$1.dirname; +var relative$1 = path$1.relative; +var resolve$2 = path$1.resolve; + +function Ignore$1(options) { + this.cwd = options.cwd; + + this.findUp = new findUp({ + filePath: options.ignorePath, + cwd: options.cwd, + detect: options.detectIgnore, + names: options.ignoreName ? [options.ignoreName] : [], + create: create$1 + }); +} + +function check(filePath, callback) { + var self = this; + + self.findUp.load(filePath, done); + + function done(error, ignore) { + var normal; + + if (error) { + callback(error); + } else if (ignore) { + normal = relative$1(ignore.filePath, resolve$2(self.cwd, filePath)); + callback(null, normal ? ignore.ignores(normal) : false); + } else { + callback(null, false); + } + } +} + +function create$1(buf, filePath) { + var ignore$1 = ignore().add(String(buf)); + ignore$1.filePath = dirname$1(filePath); + return ignore$1 +} + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var isWindows = process.platform === 'win32'; + + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = path$1.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +var realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = path$1.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs$1.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs$1.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs$1.statSync(base); + linkTarget = fs$1.readlinkSync(base); + } + resolvedLink = path$1.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = path$1.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +var realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = path$1.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs$1.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs$1.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs$1.stat(base, function(err) { + if (err) return cb(err); + + fs$1.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = path$1.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = path$1.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + +var old = { + realpathSync: realpathSync, + realpath: realpath +}; + +var fs_realpath = realpath$1; +realpath$1.realpath = realpath$1; +realpath$1.sync = realpathSync$1; +realpath$1.realpathSync = realpathSync$1; +realpath$1.monkeypatch = monkeypatch; +realpath$1.unmonkeypatch = unmonkeypatch; + + +var origRealpath = fs$1.realpath; +var origRealpathSync = fs$1.realpathSync; + +var version = process.version; +var ok = /^v[0-5]\./.test(version); + + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath$1 (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache; + cache = null; + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb); + } else { + cb(er, result); + } + }); +} + +function realpathSync$1 (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs$1.realpath = realpath$1; + fs$1.realpathSync = realpathSync$1; +} + +function unmonkeypatch () { + fs$1.realpath = origRealpath; + fs$1.realpathSync = origRealpathSync; +} + +var concatMap = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var balancedMatch = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + +var braceExpansion = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balancedMatch('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balancedMatch('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + +var minimatch_1 = minimatch; +minimatch.Minimatch = Minimatch; + +var path = { sep: '/' }; +try { + path = path$1; +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; + + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +}; + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]'; + +// * => any number of characters +var star = qmark + '*?'; + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!'); + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true; + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/; + +minimatch.filter = filter; +function filter (pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {}; + b = b || {}; + var t = {}; + Object.keys(b).forEach(function (k) { + t[k] = b[k]; + }); + Object.keys(a).forEach(function (k) { + t[k] = a[k]; + }); + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch; + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + }; + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + }; + + return m +}; + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +}; + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {}; + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {}; + pattern = pattern.trim(); + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/'); + } + + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + + // make the set of regexps etc. + this.make(); +} + +Minimatch.prototype.debug = function () {}; + +Minimatch.prototype.make = make; +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern; + var options = this.options; + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return + } + if (!pattern) { + this.empty = true; + return + } + + // step 1: figure out negation, etc. + this.parseNegate(); + + // step 2: expand braces + var set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = console.error; + + this.debug(this.pattern, set); + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }); + + this.debug(this.pattern, set); + + this.set = set; +} + +Minimatch.prototype.parseNegate = parseNegate; +function parseNegate () { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +}; + +Minimatch.prototype.braceExpand = braceExpand; + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options; + } else { + options = {}; + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern; + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return braceExpansion(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse$2; +var SUBPARSE = {}; +function parse$2 (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options; + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = ''; + var hasMagic = !!options.nocase; + var escaping = false; + // ? => one single character + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)'; + var self = this; + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break + case '?': + re += qmark; + hasMagic = true; + break + default: + re += '\\' + stateChar; + break + } + self.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c; + escaping = false; + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar(); + escaping = true; + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) c = '^'; + re += c; + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar(); + continue + + case '(': + if (inClass) { + re += '('; + continue + } + + if (!stateChar) { + re += '\\('; + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)'; + continue + } + + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(pl); + } + pl.reEnd = re.length; + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|'; + escaping = false; + continue + } + + clearStateChar(); + re += '|'; + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += '\\' + c; + continue + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + escaping = false; + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + cs + ']'); + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue + } + } + + // finish up the class. + hasMagic = true; + inClass = false; + re += c; + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length); + this.debug('setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }); + + this.debug('tail=%j\n %s', tail, tail, pl, re); + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type; + + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false; + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true; + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + + var nlBefore = re.slice(0, nl.reStart); + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re.slice(nl.reEnd); + + nlLast += nlAfter; + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1; + var cleanAfter = nlAfter; + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + var dollar = ''; + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$'; + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re = newRe; + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + + if (addPatternStart) { + re = patternStart + re; + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : ''; + try { + var regExp = new RegExp('^' + re + '$', flags); + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern; + regExp._src = re; + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +}; + +Minimatch.prototype.makeRe = makeRe; +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set; + + if (!set.length) { + this.regexp = false; + return this.regexp + } + var options = this.options; + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot; + var flags = options.nocase ? 'i' : ''; + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|'); + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$'; + + try { + this.regexp = new RegExp(re, flags); + } catch (ex) { + this.regexp = false; + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {}; + var mm = new Minimatch(pattern, options); + list = list.filter(function (f) { + return mm.match(f) + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list +}; + +Minimatch.prototype.match = match; +function match (f, partial) { + this.debug('match', f, this.pattern); + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options; + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/'); + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit); + this.debug(this.pattern, 'split', f); + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set; + this.debug(this.pattern, 'set', set); + + // Find the basename of the path by looking for the last non-empty segment + var filename; + var i; + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i]; + var file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + var hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options; + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }); + + this.debug('matchOne', file.length, pattern.length); + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + + this.debug(pattern, p, f); + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]); + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit; + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase(); + } else { + hit = f === p; + } + this.debug('string match', p, f, hit); + } else { + hit = f.match(p); + this.debug('pattern match', p, f, hit); + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === ''); + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +}; + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +var inherits_browser = createCommonjsModule(function (module) { +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; +} +}); + +var inherits = createCommonjsModule(function (module) { +try { + var util = util$1; + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = inherits_browser; +} +}); + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +var pathIsAbsolute = process.platform === 'win32' ? win32 : posix; +var posix_1 = posix; +var win32_1 = win32; +pathIsAbsolute.posix = posix_1; +pathIsAbsolute.win32 = win32_1; + +var alphasort_1 = alphasort; +var alphasorti_1 = alphasorti; +var setopts_1 = setopts; +var ownProp_1 = ownProp; +var makeAbs_1 = makeAbs; +var finish_1 = finish; +var mark_1 = mark$1; +var isIgnored_1 = isIgnored; +var childrenIgnored_1 = childrenIgnored; + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + + + + +var Minimatch$1 = minimatch_1.Minimatch; + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || []; + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore]; + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap); + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null; + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, ''); + gmatcher = new Minimatch$1(gpattern, { dot: true }); + } + + return { + matcher: new Minimatch$1(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {}; + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern; + } + + self.silent = !!options.silent; + self.pattern = pattern; + self.strict = options.strict !== false; + self.realpath = !!options.realpath; + self.realpathCache = options.realpathCache || Object.create(null); + self.follow = !!options.follow; + self.dot = !!options.dot; + self.mark = !!options.mark; + self.nodir = !!options.nodir; + if (self.nodir) + self.mark = true; + self.sync = !!options.sync; + self.nounique = !!options.nounique; + self.nonull = !!options.nonull; + self.nosort = !!options.nosort; + self.nocase = !!options.nocase; + self.stat = !!options.stat; + self.noprocess = !!options.noprocess; + self.absolute = !!options.absolute; + + self.maxLength = options.maxLength || Infinity; + self.cache = options.cache || Object.create(null); + self.statCache = options.statCache || Object.create(null); + self.symlinks = options.symlinks || Object.create(null); + + setupIgnores(self, options); + + self.changedCwd = false; + var cwd = process.cwd(); + if (!ownProp(options, "cwd")) + self.cwd = cwd; + else { + self.cwd = path$1.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path$1.resolve(self.cwd, "/"); + self.root = path$1.resolve(self.root); + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/"); + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + self.nomount = !!options.nomount; + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + + self.minimatch = new Minimatch$1(pattern, options); + self.options = self.minimatch.options; +} + +function finish (self) { + var nou = self.nounique; + var all = nou ? [] : Object.create(null); + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i]; + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i]; + if (nou) + all.push(literal); + else + all[literal] = true; + } + } else { + // had matches + var m = Object.keys(matches); + if (nou) + all.push.apply(all, m); + else + m.forEach(function (m) { + all[m] = true; + }); + } + } + + if (!nou) + all = Object.keys(all); + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort); + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]); + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)); + var c = self.cache[e] || self.cache[makeAbs(self, e)]; + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c); + return notDir + }); + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }); + + self.found = all; +} + +function mark$1 (self, p) { + var abs = makeAbs(self, p); + var c = self.cache[abs]; + var m = p; + if (c) { + var isDir = c === 'DIR' || Array.isArray(c); + var slash = p.slice(-1) === '/'; + + if (isDir && !slash) + m += '/'; + else if (!isDir && slash) + m = m.slice(0, -1); + + if (m !== p) { + var mabs = makeAbs(self, m); + self.statCache[mabs] = self.statCache[abs]; + self.cache[mabs] = self.cache[abs]; + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f; + if (f.charAt(0) === '/') { + abs = path$1.join(self.root, f); + } else if (pathIsAbsolute(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path$1.resolve(self.cwd, f); + } else { + abs = path$1.resolve(f); + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/'); + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +var common$2 = { + alphasort: alphasort_1, + alphasorti: alphasorti_1, + setopts: setopts_1, + ownProp: ownProp_1, + makeAbs: makeAbs_1, + finish: finish_1, + mark: mark_1, + isIgnored: isIgnored_1, + childrenIgnored: childrenIgnored_1 +}; + +var sync = globSync; +globSync.GlobSync = GlobSync; +var setopts$1 = common$2.setopts; +var ownProp$1 = common$2.ownProp; +var childrenIgnored$1 = common$2.childrenIgnored; +var isIgnored$1 = common$2.isIgnored; + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts$1(this, pattern, options); + + if (this.noprocess) + return this + + var n = this.minimatch.set.length; + this.matches = new Array(n); + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false); + } + this._finish(); +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync); + if (this.realpath) { + var self = this; + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null); + for (var p in matchset) { + try { + p = self._makeAbs(p); + var real = fs_realpath.realpathSync(p, self.realpathCache); + set[real] = true; + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true; + else + throw er + } + } + }); + } + common$2.finish(this); +}; + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync); + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { + if (!prefix || !pathIsAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip processing + if (childrenIgnored$1(this, read)) + return + + var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar); +}; + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar); + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$1.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + var newPattern; + if (prefix) + newPattern = [prefix, e]; + else + newPattern = [e]; + this._process(newPattern.concat(remain), index, inGlobStar); + } +}; + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored$1(this, e)) + return + + var abs = this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) { + e = abs; + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + if (this.stat) + this._stat(e); +}; + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries; + var lstat; + try { + lstat = fs$1.lstatSync(abs); + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink(); + this.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE'; + else + entries = this._readdir(abs, false); + + return entries +}; + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + + if (inGlobStar && !ownProp$1(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs$1.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er); + return null + } +}; + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + + // mark and cache dir-ness + return entries +}; + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er); + break + } +}; + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar); + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false); + + var len = entries.length; + var isSym = this.symlinks[abs]; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true); + } +}; + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix); + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && pathIsAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$1.join(this.root, prefix); + } else { + prefix = path$1.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); +}; + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (!stat) { + var lstat; + try { + lstat = fs$1.lstatSync(abs); + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs$1.statSync(abs); + } catch (er) { + stat = lstat; + } + } else { + stat = lstat; + } + } + + this.statCache[abs] = stat; + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return false + + return c +}; + +GlobSync.prototype._mark = function (p) { + return common$2.mark(this, p) +}; + +GlobSync.prototype._makeAbs = function (f) { + return common$2.makeAbs(this, f) +}; + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +var wrappy_1 = wrappy; +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } +} + +var once_1 = wrappy_1(once); +var strict = wrappy_1(onceStrict); + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); +}); + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f +} +once_1.strict = strict; + +var reqs = Object.create(null); + + +var inflight_1 = wrappy_1(inflight); + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb); + return null + } else { + reqs[key] = [cb]; + return makeres(key) + } +} + +function makeres (key) { + return once_1(function RES () { + var cbs = reqs[key]; + var len = cbs.length; + var args = slice$2(arguments); + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args); + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len); + process.nextTick(function () { + RES.apply(null, args); + }); + } else { + delete reqs[key]; + } + } + }) +} + +function slice$2 (args) { + var length = args.length; + var array = []; + + for (var i = 0; i < length; i++) array[i] = args[i]; + return array +} + +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +var glob_1 = glob; + +var EE = events.EventEmitter; +var setopts$2 = common$2.setopts; +var ownProp$2 = common$2.ownProp; + + +var childrenIgnored$2 = common$2.childrenIgnored; +var isIgnored$2 = common$2.isIgnored; + + + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {}; + if (!options) options = {}; + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return sync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = sync; +var GlobSync$1 = glob.GlobSync = sync.GlobSync; + +// old api surface +glob.glob = glob; + +function extend$2 (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend$2({}, options_); + options.noprocess = true; + + var g = new Glob(pattern, options); + var set = g.minimatch.set; + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +}; + +glob.Glob = Glob; +inherits(Glob, EE); +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync$1(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts$2(this, pattern, options); + this._didRealPath = false; + + // process each pattern in the minimatch set + var n = this.minimatch.set.length; + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n); + + if (typeof cb === 'function') { + cb = once_1(cb); + this.on('error', cb); + this.on('end', function (matches) { + cb(null, matches); + }); + } + + var self = this; + this._processing = 0; + + this._emitQueue = []; + this._processQueue = []; + this.paused = false; + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true; + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done); + } + sync = false; + + function done () { + --self._processing; + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish(); + }); + } else { + self._finish(); + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob); + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common$2.finish(this); + this.emit('end', this.found); +}; + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true; + + var n = this.matches.length; + if (n === 0) + return this._finish() + + var self = this; + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next); + + function next () { + if (--n === 0) + self._finish(); + } +}; + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index]; + if (!matchset) + return cb() + + var found = Object.keys(matchset); + var self = this; + var n = found.length; + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null); + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p); + fs_realpath.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true; + else if (er.syscall === 'stat') + set[p] = true; + else + self.emit('error', er); // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set; + cb(); + } + }); + }); +}; + +Glob.prototype._mark = function (p) { + return common$2.mark(this, p) +}; + +Glob.prototype._makeAbs = function (f) { + return common$2.makeAbs(this, f) +}; + +Glob.prototype.abort = function () { + this.aborted = true; + this.emit('abort'); +}; + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true; + this.emit('pause'); + } +}; + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume'); + this.paused = false; + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0); + this._emitQueue.length = 0; + for (var i = 0; i < eq.length; i ++) { + var e = eq[i]; + this._emitMatch(e[0], e[1]); + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0); + this._processQueue.length = 0; + for (var i = 0; i < pq.length; i ++) { + var p = pq[i]; + this._processing--; + this._process(p[0], p[1], p[2], p[3]); + } + } + } +}; + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob); + assert(typeof cb === 'function'); + + if (this.aborted) + return + + this._processing++; + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]); + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { + if (!prefix || !pathIsAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip _processing + if (childrenIgnored$2(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); +}; + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }); +}; + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$1.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + this._process([e].concat(remain), index, inGlobStar, cb); + } + cb(); +}; + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored$2(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]); + return + } + + var abs = pathIsAbsolute(e) ? e : this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) + e = abs; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + var st = this.statCache[abs]; + if (st) + this.emit('stat', e, st); + + this.emit('match', e); +}; + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs; + var self = this; + var lstatcb = inflight_1(lstatkey, lstatcb_); + + if (lstatcb) + fs$1.lstat(abs, lstatcb); + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink(); + self.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE'; + cb(); + } else + self._readdir(abs, false, cb); + } +}; + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb); + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp$2(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp$2(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + fs$1.readdir(abs, readdirCb(this, abs, cb)); +}; + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb); + else + self._readdirEntries(abs, entries, cb); + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + return cb(null, entries) +}; + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + this.emit('error', error); + this.abort(); + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) { + this.emit('error', er); + // If the error is handled, then we abort + // if not, we threw out of here + this.abort(); + } + if (!this.silent) + console.error('glob error', er); + break + } + + return cb() +}; + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); + }); +}; + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb); + + var isSym = this.symlinks[abs]; + var len = entries.length; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true, cb); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true, cb); + } + + cb(); +}; + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this; + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb); + }); +}; +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && pathIsAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$1.join(this.root, prefix); + } else { + prefix = path$1.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + cb(); +}; + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp$2(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE'; + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this; + var statcb = inflight_1('stat\0' + abs, lstatcb_); + if (statcb) + fs$1.lstat(abs, statcb); + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs$1.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb); + else + self._stat2(f, abs, er, stat, cb); + }) + } else { + self._stat2(f, abs, er, lstat, cb); + } + } +}; + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return cb() + } + + var needDir = f.slice(-1) === '/'; + this.statCache[abs] = stat; + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +}; + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var isBuffer = function isBuffer (obj) { + return obj != null && obj.constructor != null && + typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +}; + +var own = {}.hasOwnProperty; + +var unistUtilStringifyPosition = stringify; + +function stringify(value) { + // Nothing. + if (!value || typeof value !== 'object') { + return '' + } + + // Node. + if (own.call(value, 'position') || own.call(value, 'type')) { + return position(value.position) + } + + // Position. + if (own.call(value, 'start') || own.call(value, 'end')) { + return position(value) + } + + // Point. + if (own.call(value, 'line') || own.call(value, 'column')) { + return point(value) + } + + // ? + return '' +} + +function point(point) { + if (!point || typeof point !== 'object') { + point = {}; + } + + return index(point.line) + ':' + index(point.column) +} + +function position(pos) { + if (!pos || typeof pos !== 'object') { + pos = {}; + } + + return point(pos.start) + '-' + point(pos.end) +} + +function index(value) { + return value && typeof value === 'number' ? value : 1 +} + +var vfileMessage = VMessage; + +// Inherit from `Error#`. +function VMessagePrototype() {} +VMessagePrototype.prototype = Error.prototype; +VMessage.prototype = new VMessagePrototype(); + +// Message properties. +var proto = VMessage.prototype; + +proto.file = ''; +proto.name = ''; +proto.reason = ''; +proto.message = ''; +proto.stack = ''; +proto.fatal = null; +proto.column = null; +proto.line = null; + +// Construct a new VMessage. +// +// Note: We cannot invoke `Error` on the created context, as that adds readonly +// `line` and `column` attributes on Safari 9, thus throwing and failing the +// data. +function VMessage(reason, position, origin) { + var parts; + var range; + var location; + + if (typeof position === 'string') { + origin = position; + position = null; + } + + parts = parseOrigin(origin); + range = unistUtilStringifyPosition(position) || '1:1'; + + location = { + start: {line: null, column: null}, + end: {line: null, column: null} + }; + + // Node. + if (position && position.position) { + position = position.position; + } + + if (position) { + // Position. + if (position.start) { + location = position; + position = position.start; + } else { + // Point. + location.start = position; + } + } + + if (reason.stack) { + this.stack = reason.stack; + reason = reason.message; + } + + this.message = reason; + this.name = range; + this.reason = reason; + this.line = position ? position.line : null; + this.column = position ? position.column : null; + this.location = location; + this.source = parts[0]; + this.ruleId = parts[1]; +} + +function parseOrigin(origin) { + var result = [null, null]; + var index; + + if (typeof origin === 'string') { + index = origin.indexOf(':'); + + if (index === -1) { + result[1] = origin; + } else { + result[0] = origin.slice(0, index); + result[1] = origin.slice(index + 1); + } + } + + return result +} + +function replaceExt(npath, ext) { + if (typeof npath !== 'string') { + return npath; + } + + if (npath.length === 0) { + return npath; + } + + var nFileName = path$1.basename(npath, path$1.extname(npath)) + ext; + return path$1.join(path$1.dirname(npath), nFileName); +} + +var replaceExt_1 = replaceExt; + +var core$1 = VFile; + +var own$1 = {}.hasOwnProperty; +var proto$1 = VFile.prototype; + +// Order of setting (least specific to most), we need this because otherwise +// `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a +// stem can be set. +var order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname']; + +proto$1.toString = toString$1; + +// Access full path (`~/index.min.js`). +Object.defineProperty(proto$1, 'path', {get: getPath, set: setPath}); + +// Access parent path (`~`). +Object.defineProperty(proto$1, 'dirname', {get: getDirname, set: setDirname}); + +// Access basename (`index.min.js`). +Object.defineProperty(proto$1, 'basename', {get: getBasename, set: setBasename}); + +// Access extname (`.js`). +Object.defineProperty(proto$1, 'extname', {get: getExtname, set: setExtname}); + +// Access stem (`index.min`). +Object.defineProperty(proto$1, 'stem', {get: getStem, set: setStem}); + +// Construct a new file. +function VFile(options) { + var prop; + var index; + var length; + + if (!options) { + options = {}; + } else if (typeof options === 'string' || isBuffer(options)) { + options = {contents: options}; + } else if ('message' in options && 'messages' in options) { + return options + } + + if (!(this instanceof VFile)) { + return new VFile(options) + } + + this.data = {}; + this.messages = []; + this.history = []; + this.cwd = process.cwd(); + + // Set path related properties in the correct order. + index = -1; + length = order.length; + + while (++index < length) { + prop = order[index]; + + if (own$1.call(options, prop)) { + this[prop] = options[prop]; + } + } + + // Set non-path related properties. + for (prop in options) { + if (order.indexOf(prop) === -1) { + this[prop] = options[prop]; + } + } +} + +function getPath() { + return this.history[this.history.length - 1] +} + +function setPath(path) { + assertNonEmpty(path, 'path'); + + if (path !== this.path) { + this.history.push(path); + } +} + +function getDirname() { + return typeof this.path === 'string' ? path$1.dirname(this.path) : undefined +} + +function setDirname(dirname) { + assertPath(this.path, 'dirname'); + this.path = path$1.join(dirname || '', this.basename); +} + +function getBasename() { + return typeof this.path === 'string' ? path$1.basename(this.path) : undefined +} + +function setBasename(basename) { + assertNonEmpty(basename, 'basename'); + assertPart(basename, 'basename'); + this.path = path$1.join(this.dirname || '', basename); +} + +function getExtname() { + return typeof this.path === 'string' ? path$1.extname(this.path) : undefined +} + +function setExtname(extname) { + var ext = extname || ''; + + assertPart(ext, 'extname'); + assertPath(this.path, 'extname'); + + if (ext) { + if (ext.charAt(0) !== '.') { + throw new Error('`extname` must start with `.`') + } + + if (ext.indexOf('.', 1) !== -1) { + throw new Error('`extname` cannot contain multiple dots') + } + } + + this.path = replaceExt_1(this.path, ext); +} + +function getStem() { + return typeof this.path === 'string' + ? path$1.basename(this.path, this.extname) + : undefined +} + +function setStem(stem) { + assertNonEmpty(stem, 'stem'); + assertPart(stem, 'stem'); + this.path = path$1.join(this.dirname || '', stem + (this.extname || '')); +} + +// Get the value of the file. +function toString$1(encoding) { + var value = this.contents || ''; + return isBuffer(value) ? value.toString(encoding) : String(value) +} + +// Assert that `part` is not a path (i.e., does not contain `path.sep`). +function assertPart(part, name) { + if (part.indexOf(path$1.sep) !== -1) { + throw new Error( + '`' + name + '` cannot be a path: did not expect `' + path$1.sep + '`' + ) + } +} + +// Assert that `part` is not empty. +function assertNonEmpty(part, name) { + if (!part) { + throw new Error('`' + name + '` cannot be empty') + } +} + +// Assert `path` exists. +function assertPath(path, name) { + if (!path) { + throw new Error('Setting `' + name + '` requires `path` to be set too') + } +} + +var vfile = core$1; + +var proto$2 = core$1.prototype; + +proto$2.message = message; +proto$2.info = info; +proto$2.fail = fail; + +// Create a message with `reason` at `position`. +// When an error is passed in as `reason`, copies the stack. +function message(reason, position, origin) { + var filePath = this.path; + var message = new vfileMessage(reason, position, origin); + + if (filePath) { + message.name = filePath + ':' + message.name; + message.file = filePath; + } + + message.fatal = false; + + this.messages.push(message); + + return message +} + +// Fail: creates a vmessage, associates it with the file, and throws it. +function fail() { + var message = this.message.apply(this, arguments); + + message.fatal = true; + + throw message +} + +// Info: creates a vmessage, associates it with the file, and marks the fatality +// as null. +function info() { + var message = this.message.apply(this, arguments); + + message.fatal = null; + + return message +} + +var core$2 = toVFile; + +// Create a virtual file from a description. If `options` is a string or a +// buffer, it’s used as the path. In all other cases, the options are passed +// through to `vfile()`. +function toVFile(options) { + if (typeof options === 'string' || isBuffer(options)) { + options = {path: String(options)}; + } + + return vfile(options) +} + +var read$1 = readSync; +var write = writeSync; + +// Create a virtual file and read it in, synchronously. +function readSync(description, options) { + var file = core$2(description); + file.contents = fs$1.readFileSync(path$1.resolve(file.cwd, file.path), options); + return file +} + +// Create a virtual file and write it out, synchronously. +function writeSync(description, options) { + var file = core$2(description); + fs$1.writeFileSync( + path$1.resolve(file.cwd, file.path), + file.contents || '', + options + ); +} + +var sync$1 = { + read: read$1, + write: write +}; + +var read_1 = read$2; +var write_1 = write$1; + +// Create a virtual file and read it in, asynchronously. +function read$2(description, options, callback) { + var file = core$2(description); + + if (!callback && typeof options === 'function') { + callback = options; + options = null; + } + + if (!callback) { + return new Promise(executor) + } + + executor(resolve, callback); + + function resolve(result) { + callback(null, result); + } + + function executor(resolve, reject) { + var fp; + + try { + fp = path$1.resolve(file.cwd, file.path); + } catch (error) { + return reject(error) + } + + fs$1.readFile(fp, options, done); + + function done(error, res) { + if (error) { + reject(error); + } else { + file.contents = res; + resolve(file); + } + } + } +} + +// Create a virtual file and write it out, asynchronously. +function write$1(description, options, callback) { + var file = core$2(description); + + // Weird, right? Otherwise `fs` doesn’t accept it. + if (!callback && typeof options === 'function') { + callback = options; + options = undefined; + } + + if (!callback) { + return new Promise(executor) + } + + executor(resolve, callback); + + function resolve(result) { + callback(null, result); + } + + function executor(resolve, reject) { + var fp; + + try { + fp = path$1.resolve(file.cwd, file.path); + } catch (error) { + return reject(error) + } + + fs$1.writeFile(fp, file.contents || '', options, done); + + function done(error) { + if (error) { + reject(error); + } else { + resolve(); + } + } + } +} + +var async = { + read: read_1, + write: write_1 +}; + +var fs = core$2; + +core$2.read = async.read; +core$2.readSync = sync$1.read; +core$2.write = async.write; +core$2.writeSync = sync$1.write; + +var toVfile = fs; + +var isHidden = hidden; + +function hidden(filename) { + if (typeof filename !== 'string') { + throw new Error('Expected string') + } + + return filename.charAt(0) === '.' +} + +var readdir = fs$1.readdir; +var stat = fs$1.stat; +var join$2 = path$1.join; +var relative$2 = path$1.relative; +var resolve$3 = path$1.resolve; +var basename = path$1.basename; +var extname = path$1.extname; +var magic = glob_1.hasMagic; + +var finder = find; + +// Search `patterns`, a mix of globs, paths, and files. +function find(input, options, callback) { + expand$1(input, options, done); + + function done(error, result) { + /* istanbul ignore if - glob errors are unusual. + * other errors are on the vfile results. */ + if (error) { + callback(error); + } else { + callback(null, {oneFileMode: oneFileMode(result), files: result.output}); + } + } +} + +// Expand the given glob patterns, search given and found directories, and map +// to vfiles. +function expand$1(input, options, next) { + var cwd = options.cwd; + var paths = []; + var actual = 0; + var expected = 0; + var failed; + + input.forEach(each); + + if (!expected) { + search(paths, options, done); + } + + function each(file) { + if (xIsString(file)) { + if (magic(file)) { + expected++; + glob_1(file, {cwd: cwd}, one); + } else { + // `relative` to make the paths canonical. + file = relative$2(cwd, resolve$3(cwd, file)) || '.'; + paths.push(file); + } + } else { + file.cwd = cwd; + file.path = relative$2(cwd, file.path); + file.history = [file.path]; + paths.push(file); + } + } + + function one(error, files) { + /* istanbul ignore if - Glob errors are unusual. */ + if (failed) { + return + } + + /* istanbul ignore if - Glob errors are unusual. */ + if (error) { + failed = true; + done(error); + } else { + actual++; + paths = paths.concat(files); + + if (actual === expected) { + search(paths, options, done); + } + } + } + + function done(error, files) { + /* istanbul ignore if - `search` currently does not give errors. */ + if (error) { + next(error); + } else { + next(null, {input: paths, output: files}); + } + } +} + +// Search `paths`. +function search(input, options, next) { + var cwd = options.cwd; + var silent = options.silentlyIgnore; + var nested = options.nested; + var extensions = options.extensions; + var extraIgnore = ignore().add(options.ignorePatterns); + var files = []; + var expected = 0; + var actual = 0; + + input.forEach(each); + + if (!expected) { + next(null, files); + } + + return each + + function each(file) { + var ext = xIsString(file) ? extname(file) : file.extname; + var part; + + // Normalise globs. + if (xIsString(file)) { + file = file.split('/').join(path$1.sep); + } + + part = base(file); + + if (nested && (isHidden(part) || part === 'node_modules')) { + return + } + + expected++; + + statAndIgnore(file, immutable(options, {extraIgnore: extraIgnore}), handle); + + function handle(error, result) { + var ignored = result && result.ignored; + var dir = result && result.stats && result.stats.isDirectory(); + + if (ignored && (nested || silent)) { + return one(null, []) + } + + if (!ignored && dir) { + return readdir(resolve$3(cwd, filePath(file)), directory) + } + + if ( + nested && + !dir && + extensions.length !== 0 && + extensions.indexOf(ext) === -1 + ) { + return one(null, []) + } + + file = toVfile(file); + file.cwd = cwd; + + if (ignored) { + try { + file.fail('Cannot process specified file: it’s ignored'); + } catch (error2) {} + } + + if (error && error.code === 'ENOENT') { + try { + file.fail( + error.syscall === 'stat' ? 'No such file or directory' : error + ); + } catch (error2) {} + } + + one(null, [file]); + } + + function directory(error, basenames) { + var file; + + /* istanbul ignore if - Should not happen often: the directory is `stat`ed + * first, which was ok, but reading it is not. */ + if (error) { + file = toVfile(filePath(file)); + file.cwd = cwd; + + try { + file.fail('Cannot read directory'); + } catch (error2) {} + + one(null, [file]); + } else { + search(basenames.map(concat), immutable(options, {nested: true}), one); + } + } + + // Error is never given. Always given `results`. + function one(_, results) { + /* istanbul ignore else - Always given. */ + if (results) { + files = files.concat(results); + } + + actual++; + + if (actual === expected) { + next(null, files); + } + } + + function concat(value) { + return join$2(filePath(file), value) + } + } +} + +function statAndIgnore(file, options, callback) { + var ignore = options.ignore; + var extraIgnore = options.extraIgnore; + var fp = resolve$3(options.cwd, filePath(file)); + var normal = relative$2(options.cwd, fp); + var expected = 1; + var actual = 0; + var stats; + var ignored; + + if (!file.contents) { + expected++; + stat(fp, handleStat); + } + + ignore.check(fp, handleIgnore); + + function handleStat(error, value) { + stats = value; + one(error); + } + + function handleIgnore(error, value) { + ignored = value; + one(error); + } + + function one(error) { + actual++; + + if (error) { + callback(error); + actual = -1; + } else if (actual === expected) { + callback(null, { + stats: stats, + ignored: ignored || (normal ? extraIgnore.ignores(normal) : false) + }); + } + } +} + +function base(file) { + return xIsString(file) ? basename(file) : file.basename +} + +function filePath(file) { + return xIsString(file) ? file : file.path +} + +function oneFileMode(result) { + return ( + result.output.length === 1 && + result.input.length === 1 && + result.output[0].path === result.input[0] + ) +} + +var fileSystem_1 = fileSystem; + +// Find files from the file-system. +function fileSystem(context, settings, next) { + var input = context.files; + + if (input.length === 0) { + next(); + } else { + finder( + input, + { + cwd: settings.cwd, + extensions: settings.extensions, + silentlyIgnore: settings.silentlyIgnore, + ignorePatterns: settings.ignorePatterns, + ignore: new ignore$1({ + cwd: settings.cwd, + detectIgnore: settings.detectIgnore, + ignoreName: settings.ignoreName, + ignorePath: settings.ignorePath + }) + }, + onfound + ); + } + + function onfound(error, result) { + var output = result.files; + + // Sort alphabetically. + // Everything is unique so we do not care about cases where left and right + // are equal. + output.sort(sortAlphabetically); + + // Mark as given. + // This allows outputting files, which can be pretty dangerous, so it’s + // “hidden”. + output.forEach(markAsGiven); + + context.files = output; + + // If `out` was not set, detect it based on whether one file was given. + if (settings.out === null || settings.out === undefined) { + settings.out = result.oneFileMode; + } + + next(error); + } + + function markAsGiven(file) { + file.data.unifiedEngineGiven = true; + } + + function sortAlphabetically(left, right) { + return left.path < right.path ? -1 : 1 + } +} + +var toString$2 = Object.prototype.toString; + +var isModern = ( + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +); + +function isArrayBuffer (input) { + return toString$2.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0; + + var maxLength = obj.byteLength - byteOffset; + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength; + } else { + length >>>= 0; + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +var bufferFrom_1 = bufferFrom; + +var typedarray = createCommonjsModule(function (module, exports) { +var undefined$1 = (void 0); // Paranoia + +// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to +// create, and consume so much memory, that the browser appears frozen. +var MAX_ARRAY_LENGTH = 1e5; + +// Approximations of internal ECMAScript conversion functions +var ECMAScript = (function() { + // Stash a copy in case other scripts modify these + var opts = Object.prototype.toString, + ophop = Object.prototype.hasOwnProperty; + + return { + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: + Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, + HasProperty: function(o, p) { return p in o; }, + HasOwnProperty: function(o, p) { return ophop.call(o, p); }, + IsCallable: function(o) { return typeof o === 'function'; }, + ToInt32: function(v) { return v >> 0; }, + ToUint32: function(v) { return v >>> 0; } + }; +}()); + +// Snapshot intrinsics +var LN2 = Math.LN2, + abs = Math.abs, + floor = Math.floor, + log = Math.log, + min = Math.min, + pow = Math.pow, + round = Math.round; + +// ES5: lock down object properties +function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i; + for (i = 0; i < props.length; i += 1) { + defineProp(obj, props[i], { + value: obj[props[i]], + writable: false, + enumerable: false, + configurable: false + }); + } + } +} + +// emulate ES5 getter/setter API using legacy APIs +// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx +// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but +// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) +var defineProp; +if (Object.defineProperty && (function() { + try { + Object.defineProperty({}, 'x', {}); + return true; + } catch (e) { + return false; + } + })()) { + defineProp = Object.defineProperty; +} else { + defineProp = function(o, p, desc) { + if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } + if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } + return o; + }; +} + +var getOwnPropNames = Object.getOwnPropertyNames || function (o) { + if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); + var props = [], p; + for (p in o) { + if (ECMAScript.HasOwnProperty(o, p)) { + props.push(p); + } + } + return props; +}; + +// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) +// for index in 0 ... obj.length +function makeArrayAccessors(obj) { + if (!defineProp) { return; } + + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); + + function makeArrayAccessor(index) { + defineProp(obj, index, { + 'get': function() { return obj._getter(index); }, + 'set': function(v) { obj._setter(index, v); }, + enumerable: true, + configurable: false + }); + } + + var i; + for (i = 0; i < obj.length; i += 1) { + makeArrayAccessor(i); + } +} + +// Internal conversion functions: +// pack() - take a number (interpreted as Type), output a byte array +// unpack() - take a byte array, output a Type-like number + +function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } +function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } + +function packI8(n) { return [n & 0xff]; } +function unpackI8(bytes) { return as_signed(bytes[0], 8); } + +function packU8(n) { return [n & 0xff]; } +function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } + +function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } + +function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } + +function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } + +function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packIEEE754(v, ebits, fbits) { + + var bias = (1 << (ebits - 1)) - 1, + s, e, f, i, bits, str, bytes; + + function roundToEven(n) { + var w = floor(n), f = n - w; + if (f < 0.5) + return w; + if (f > 0.5) + return w + 1; + return w % 2 ? w + 1 : w; + } + + // Compute sign, exponent, fraction + if (v !== v) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normalized + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Denormalized + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; +} + +function unpackIEEE754(bytes, ebits, fbits) { + + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; + + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } else if (e > 0) { + // Normalized + return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + } else if (f !== 0) { + // Denormalized + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + } else { + return s < 0 ? -0 : 0; + } +} + +function unpackF64(b) { return unpackIEEE754(b, 11, 52); } +function packF64(v) { return packIEEE754(v, 11, 52); } +function unpackF32(b) { return unpackIEEE754(b, 8, 23); } +function packF32(v) { return packIEEE754(v, 8, 23); } + + +// +// 3 The ArrayBuffer Type +// + +(function() { + + /** @constructor */ + var ArrayBuffer = function ArrayBuffer(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); + + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; + + var i; + for (i = 0; i < this.byteLength; i += 1) { + this._bytes[i] = 0; + } + + configureProperties(this); + }; + + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; + + // + // 4 The ArrayBufferView Type + // + + // NOTE: this constructor is not exported + /** @constructor */ + var ArrayBufferView = function ArrayBufferView() { + //this.buffer = null; + //this.byteOffset = 0; + //this.byteLength = 0; + }; + + // + // 5 The Typed Array View Types + // + + function makeConstructor(bytesPerElement, pack, unpack) { + // Each TypedArray type requires a distinct constructor instance with + // identical logic, which this produces. + + var ctor; + ctor = function(buffer, byteOffset, length) { + var array, sequence, i, s; + + if (!arguments.length || typeof arguments[0] === 'number') { + // Constructor(unsigned long length) + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); + + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { + // Constructor(TypedArray array) + array = arguments[0]; + + this.length = array.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + this._setter(i, array._getter(i)); + } + } else if (typeof arguments[0] === 'object' && + !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(sequence array) + sequence = arguments[0]; + + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + s = sequence[i]; + this._setter(i, Number(s)); + } + } else if (typeof arguments[0] === 'object' && + (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, optional unsigned long length) + this.buffer = buffer; + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + // The given byteOffset must be a multiple of the element + // size of the specific type, otherwise an exception is raised. + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + + this.constructor = ctor; + + configureProperties(this); + makeArrayAccessors(this); + }; + + ctor.prototype = new ArrayBufferView(); + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._pack = pack; + ctor.prototype._unpack = unpack; + ctor.BYTES_PER_ELEMENT = bytesPerElement; + + // getter type (unsigned long index); + ctor.prototype._getter = function(index) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined$1; + } + + var bytes = [], i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + bytes.push(this.buffer._bytes[o]); + } + return this._unpack(bytes); + }; + + // NONSTANDARD: convenience alias for getter: type get(unsigned long index); + ctor.prototype.get = ctor.prototype._getter; + + // setter void (unsigned long index, type value); + ctor.prototype._setter = function(index, value) { + if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined$1; + } + + var bytes = this._pack(value), i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + this.buffer._bytes[o] = bytes[i]; + } + }; + + // void set(TypedArray array, optional unsigned long offset); + // void set(sequence array, optional unsigned long offset); + ctor.prototype.set = function(index, value) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + var array, sequence, offset, len, + i, s, d, + byteOffset, byteLength, tmp; + + if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { + // void set(TypedArray array, optional unsigned long offset); + array = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + array.length > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array.length * this.BYTES_PER_ELEMENT; + + if (array.buffer === this.buffer) { + tmp = []; + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { + tmp[i] = array.buffer._bytes[s]; + } + for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { + this.buffer._bytes[d] = tmp[i]; + } + } else { + for (i = 0, s = array.byteOffset, d = byteOffset; + i < byteLength; i += 1, s += 1, d += 1) { + this.buffer._bytes[d] = array.buffer._bytes[s]; + } + } + } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { + // void set(sequence array, optional unsigned long offset); + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + len > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + for (i = 0; i < len; i += 1) { + s = sequence[i]; + this._setter(offset + i, Number(s)); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + }; + + // TypedArray subarray(long begin, optional long end); + ctor.prototype.subarray = function(start, end) { + function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } + + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); + + if (arguments.length < 1) { start = 0; } + if (arguments.length < 2) { end = this.length; } + + if (start < 0) { start = this.length + start; } + if (end < 0) { end = this.length + end; } + + start = clamp(start, 0, this.length); + end = clamp(end, 0, this.length); + + var len = end - start; + if (len < 0) { + len = 0; + } + + return new this.constructor( + this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); + }; + + return ctor; + } + + var Int8Array = makeConstructor(1, packI8, unpackI8); + var Uint8Array = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array = makeConstructor(2, packI16, unpackI16); + var Uint16Array = makeConstructor(2, packU16, unpackU16); + var Int32Array = makeConstructor(4, packI32, unpackI32); + var Uint32Array = makeConstructor(4, packU32, unpackU32); + var Float32Array = makeConstructor(4, packF32, unpackF32); + var Float64Array = makeConstructor(8, packF64, unpackF64); + + exports.Int8Array = exports.Int8Array || Int8Array; + exports.Uint8Array = exports.Uint8Array || Uint8Array; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; + exports.Int16Array = exports.Int16Array || Int16Array; + exports.Uint16Array = exports.Uint16Array || Uint16Array; + exports.Int32Array = exports.Int32Array || Int32Array; + exports.Uint32Array = exports.Uint32Array || Uint32Array; + exports.Float32Array = exports.Float32Array || Float32Array; + exports.Float64Array = exports.Float64Array || Float64Array; +}()); + +// +// 6 The DataView View Type +// + +(function() { + function r(array, index) { + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; + } + + var IS_BIG_ENDIAN = (function() { + var u16array = new(exports.Uint16Array)([0x1234]), + u8array = new(exports.Uint8Array)(u16array.buffer); + return r(u8array, 0) === 0x12; + }()); + + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, + // optional unsigned long byteLength) + /** @constructor */ + var DataView = function DataView(buffer, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer = new exports.ArrayBuffer(0); + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { + throw new TypeError("TypeError"); + } + + this.buffer = buffer || new exports.ArrayBuffer(0); + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + } else { + this.byteLength = ECMAScript.ToUint32(byteLength); + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + + configureProperties(this); + }; + + function makeGetter(arrayType) { + return function(byteOffset, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + byteOffset += this.byteOffset; + + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), + bytes = [], i; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(uint8Array, i)); + } + + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); + }; + } + + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); + + function makeSetter(arrayType) { + return function(byteOffset, value, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + + // Get bytes + var typeArray = new arrayType([value]), + byteArray = new exports.Uint8Array(typeArray.buffer), + bytes = [], i, byteView; + + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(byteArray, i)); + } + + // Flip if necessary + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + // Write them + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); + + exports.DataView = exports.DataView || DataView; + +}()); +}); +var typedarray_1 = typedarray.ArrayBuffer; +var typedarray_2 = typedarray.Int8Array; +var typedarray_3 = typedarray.Uint8Array; +var typedarray_4 = typedarray.Uint8ClampedArray; +var typedarray_5 = typedarray.Int16Array; +var typedarray_6 = typedarray.Uint16Array; +var typedarray_7 = typedarray.Int32Array; +var typedarray_8 = typedarray.Uint32Array; +var typedarray_9 = typedarray.Float32Array; +var typedarray_10 = typedarray.Float64Array; +var typedarray_11 = typedarray.DataView; + +var Writable = stream.Writable; + + + +if (typeof Uint8Array === 'undefined') { + var U8 = typedarray.Uint8Array; +} else { + var U8 = Uint8Array; +} + +function ConcatStream(opts, cb) { + if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) + + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (!opts) opts = {}; + + var encoding = opts.encoding; + var shouldInferEncoding = false; + + if (!encoding) { + shouldInferEncoding = true; + } else { + encoding = String(encoding).toLowerCase(); + if (encoding === 'u8' || encoding === 'uint8') { + encoding = 'uint8array'; + } + } + + Writable.call(this, { objectMode: true }); + + this.encoding = encoding; + this.shouldInferEncoding = shouldInferEncoding; + + if (cb) this.on('finish', function () { cb(this.getBody()); }); + this.body = []; +} + +var concatStream = ConcatStream; +inherits(ConcatStream, Writable); + +ConcatStream.prototype._write = function(chunk, enc, next) { + this.body.push(chunk); + next(); +}; + +ConcatStream.prototype.inferEncoding = function (buff) { + var firstBuffer = buff === undefined ? this.body[0] : buff; + if (Buffer.isBuffer(firstBuffer)) return 'buffer' + if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' + if (Array.isArray(firstBuffer)) return 'array' + if (typeof firstBuffer === 'string') return 'string' + if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' + return 'buffer' +}; + +ConcatStream.prototype.getBody = function () { + if (!this.encoding && this.body.length === 0) return [] + if (this.shouldInferEncoding) this.encoding = this.inferEncoding(); + if (this.encoding === 'array') return arrayConcat(this.body) + if (this.encoding === 'string') return stringConcat(this.body) + if (this.encoding === 'buffer') return bufferConcat(this.body) + if (this.encoding === 'uint8array') return u8Concat(this.body) + return this.body +}; + +function isArrayish$1 (arr) { + return /Array\]$/.test(Object.prototype.toString.call(arr)) +} + +function isBufferish (p) { + return typeof p === 'string' || isArrayish$1(p) || (p && typeof p.subarray === 'function') +} + +function stringConcat (parts) { + var strings = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (typeof p === 'string') { + strings.push(p); + } else if (Buffer.isBuffer(p)) { + strings.push(p); + } else if (isBufferish(p)) { + strings.push(bufferFrom_1(p)); + } else { + strings.push(bufferFrom_1(String(p))); + } + } + if (Buffer.isBuffer(parts[0])) { + strings = Buffer.concat(strings); + strings = strings.toString('utf8'); + } else { + strings = strings.join(''); + } + return strings +} + +function bufferConcat (parts) { + var bufs = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (Buffer.isBuffer(p)) { + bufs.push(p); + } else if (isBufferish(p)) { + bufs.push(bufferFrom_1(p)); + } else { + bufs.push(bufferFrom_1(String(p))); + } + } + return Buffer.concat(bufs) +} + +function arrayConcat (parts) { + var res = []; + for (var i = 0; i < parts.length; i++) { + res.push.apply(res, parts[i]); + } + return res +} + +function u8Concat (parts) { + var len = 0; + for (var i = 0; i < parts.length; i++) { + if (typeof parts[i] === 'string') { + parts[i] = bufferFrom_1(parts[i]); + } + len += parts[i].length; + } + var u8 = new U8(len); + for (var i = 0, offset = 0; i < parts.length; i++) { + var part = parts[i]; + for (var j = 0; j < part.length; j++) { + u8[offset++] = part[j]; + } + } + return u8 +} + +var debug$1 = src('unified-engine:file-set-pipeline:stdin'); + + + +var stdin_1 = stdin; + +function stdin(context, settings, next) { + var streamIn = settings.streamIn; + var error; + + if (settings.files && settings.files.length !== 0) { + debug$1('Ignoring `streamIn`'); + + if (settings.filePath) { + error = new Error( + 'Do not pass both `--file-path` and real files.\nDid you mean to pass stdin instead of files?' + ); + } + + next(error); + + return + } + + if (streamIn.isTTY) { + debug$1('Cannot read from `tty` stream'); + next(new Error('No input')); + + return + } + + debug$1('Reading from `streamIn`'); + + streamIn.pipe(concatStream({encoding: 'string'}, read)); + + function read(value) { + var file = toVfile(settings.filePath || undefined); + + debug$1('Read from `streamIn`'); + + file.cwd = settings.cwd; + file.contents = value; + file.data.unifiedEngineGiven = true; + file.data.unifiedEngineStreamIn = true; + + context.files = [file]; + + // If `out` was not set, set `out`. + settings.out = + settings.out === null || settings.out === undefined ? true : settings.out; + + next(); + } +} + +var inherits$1 = util$1.inherits; + + + + +var fileSet = FileSet; + +// FileSet constructor. +function FileSet() { + var self = this; + + self.files = []; + self.origins = []; + + self.expected = 0; + self.actual = 0; + + self.pipeline = trough_1(); + self.plugins = []; + + events.init.call(self); + + self.on('one', one.bind(self)); +} + +// Events. +inherits$1(FileSet, events.EventEmitter); + +// Expose methods. +FileSet.prototype.valueOf = valueOf; +FileSet.prototype.use = use; +FileSet.prototype.add = add; + +// Create an array representation of `fileSet`. +function valueOf() { + return this.files +} + +// Attach middleware to the pipeline on `fileSet`. +function use(plugin) { + var self = this; + var pipeline = self.pipeline; + var duplicate = false; + + if (plugin && plugin.pluginId) { + duplicate = self.plugins.some(matches); + } + + if (!duplicate && self.plugins.indexOf(plugin) !== -1) { + duplicate = true; + } + + if (!duplicate) { + self.plugins.push(plugin); + pipeline.use(plugin); + } + + return self + + function matches(fn) { + return fn.pluginId === plugin.pluginId + } +} + +// Add a file to be processed. +// Ignores duplicate files (based on the `filePath` at time of addition). +// Only runs `file-pipeline` on files which have not `failed` before addition. +function add(file) { + var self = this; + var origin; + + if (xIsString(file)) { + file = toVfile(file); + } + + // Prevent files from being added multiple times. + origin = file.history[0]; + + if (self.origins.indexOf(origin) !== -1) { + return self + } + + self.origins.push(origin); + + // Add. + self.valueOf().push(file); + self.expected++; + + // Force an asynchronous operation. + // This ensures that files which fall through the file pipeline immediately + // (such as, when already fatally failed) still queue up correctly. + setImmediate(add); + + return self + + function add() { + self.emit('add', file); + } +} + +// Utility invoked when a single file has completed it's pipeline, triggering +// `done` when all files are complete. +function one() { + var self = this; + + self.actual++; + + if (self.actual >= self.expected) { + self.emit('done'); + } +} + +var debug$2 = src('unified-engine:file-pipeline:read'); + + +var read_1$1 = read$3; + +var resolve$4 = path$1.resolve; +var readFile = fs$1.readFile; + +// Fill a file with its contents when not already filled. +function read$3(context, file, fileSet, next) { + var filePath = file.path; + + if (file.contents || file.data.unifiedEngineStreamIn) { + debug$2('Not reading file `%s` with contents', filePath); + next(); + } else if (vfileStatistics(file).fatal) { + debug$2('Not reading failed file `%s`', filePath); + next(); + } else { + filePath = resolve$4(context.cwd, filePath); + + debug$2('Reading `%s` in `%s`', filePath, 'utf8'); + readFile(filePath, 'utf8', onread); + } + + function onread(error, contents) { + debug$2('Read `%s` (error: %s)', filePath, error); + + file.contents = contents || ''; + + next(error); + } +} + +var fnName = function (fn) { + if (typeof fn !== 'function') { + throw new TypeError('Expected a function'); + } + + return fn.displayName || fn.name || (/function ([^\(]+)?\(/.exec(fn.toString()) || [])[1] || null; +}; + +/** + * Has own property. + * + * @type {Function} + */ + +var has = Object.prototype.hasOwnProperty; + +/** + * To string. + * + * @type {Function} + */ + +var toString$3 = Object.prototype.toString; + +/** + * Test whether a value is "empty". + * + * @param {Mixed} val + * @return {Boolean} + */ + +function isEmpty(val) { + // Null and Undefined... + if (val == null) return true + + // Booleans... + if ('boolean' == typeof val) return false + + // Numbers... + if ('number' == typeof val) return val === 0 + + // Strings... + if ('string' == typeof val) return val.length === 0 + + // Functions... + if ('function' == typeof val) return val.length === 0 + + // Arrays... + if (Array.isArray(val)) return val.length === 0 + + // Errors... + if (val instanceof Error) return val.message === '' + + // Objects... + if (val.toString == toString$3) { + switch (val.toString()) { + + // Maps, Sets, Files and Errors... + case '[object File]': + case '[object Map]': + case '[object Set]': { + return val.size === 0 + } + + // Plain objects... + case '[object Object]': { + for (var key in val) { + if (has.call(val, key)) return false + } + + return true + } + } + } + + // Anything else... + return false +} + +/** + * Export `isEmpty`. + * + * @type {Function} + */ + +var lib = isEmpty; + +var debug$3 = src('unified-engine:file-pipeline:configure'); + + + + + +var configure_1$1 = configure$1; + +// Collect configuration for a file based on the context. +function configure$1(context, file, fileSet, next) { + var config = context.configuration; + var processor = context.processor; + + if (vfileStatistics(file).fatal) { + return next() + } + + config.load(file.path, handleConfiguration); + + function handleConfiguration(error, configuration) { + var plugins; + var options; + var plugin; + var length; + var index; + var name; + + if (error) { + return next(error) + } + + // Store configuration on the context object. + debug$3('Using settings `%j`', configuration.settings); + processor.data('settings', configuration.settings); + + plugins = configuration.plugins; + length = plugins.length; + index = -1; + + debug$3('Using `%d` plugins', length); + + while (++index < length) { + plugin = plugins[index][0]; + options = plugins[index][1]; + + if (options === false) { + continue + } + + // Allow for default arguments in es2020. + if (options === null || (isObject$1(options) && lib(options))) { + options = undefined; + } + + name = fnName(plugin) || 'function'; + debug$3('Using plugin `%s`, with options `%j`', name, options); + + try { + processor.use(plugin, options, fileSet); + } catch (error2) { + /* istanbul ignore next - Should not happen anymore! */ + return next(error2) + } + } + + next(); + } +} + +var debug$4 = src('unified-engine:file-pipeline:parse'); + + + +var parse_1 = parse$3; + +// Fill a file with a tree. +function parse$3(context, file) { + var message; + + if (vfileStatistics(file).fatal) { + return + } + + if (context.treeIn) { + debug$4('Not parsing already parsed document'); + + try { + context.tree = parseJson$1(file.toString()); + } catch (error) { + message = file.message( + new Error('Cannot read file as JSON\n' + error.message) + ); + message.fatal = true; + } + + // Add the preferred extension to ensure the file, when compiled, is correctly + // recognised. + // Only add it if there is a path — not if the file is for example stdin. + if (file.path) { + file.extname = context.extensions[0]; + } + + file.contents = ''; + + return + } + + debug$4('Parsing `%s`', file.path); + + context.tree = context.processor.parse(file); + + debug$4('Parsed document'); +} + +var debug$5 = src('unified-engine:file-pipeline:transform'); + + +var transform_1 = transform; + +// Transform the tree associated with a file with configured plugins. +function transform(context, file, fileSet, next) { + if (vfileStatistics(file).fatal) { + next(); + } else { + debug$5('Transforming document `%s`', file.path); + context.processor.run(context.tree, file, onrun); + } + + function onrun(error, node) { + debug$5('Transformed document (error: %s)', error); + context.tree = node; + next(error); + } +} + +var debug$6 = src('unified-engine:file-pipeline:queue'); + + +var queue_1 = queue; + +// Queue all files which came this far. +// When the last file gets here, run the file-set pipeline and flush the queue. +function queue(context, file, fileSet, next) { + var origin = file.history[0]; + var map = fileSet.complete; + var complete = true; + + if (!map) { + map = {}; + fileSet.complete = map; + } + + debug$6('Queueing `%s`', origin); + + map[origin] = next; + + fileSet.valueOf().forEach(each); + + if (!complete) { + debug$6('Not flushing: some files cannot be flushed'); + return + } + + fileSet.complete = {}; + + fileSet.pipeline.run(fileSet, done); + + function each(file) { + var key = file.history[0]; + + if (vfileStatistics(file).fatal) { + return + } + + if (typeof map[key] === 'function') { + debug$6('`%s` can be flushed', key); + } else { + debug$6('Interupting flush: `%s` is not finished', key); + complete = false; + } + } + + function done(error) { + debug$6('Flushing: all files can be flushed'); + + // Flush. + for (origin in map) { + map[origin](error); + } + } +} + +// Detect color support. +var color = true; + +try { + color = 'inspect' in util$1; +} catch (error) { + /* istanbul ignore next - browser */ + color = false; +} + +var unistUtilInspect = color ? inspect : /* istanbul ignore next */ noColor; + +inspect.color = inspect; +noColor.color = inspect; +inspect.noColor = noColor; +noColor.noColor = noColor; + +var dim = ansiColor(2, 22); +var yellow = ansiColor(33, 39); +var green = ansiColor(32, 39); + +// Define ANSII color removal functionality. +var colorExpression = new RegExp( + '(?:' + + '(?:\\u001b\\[)|' + + '\\u009b' + + ')' + + '(?:' + + '(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m]' + + ')|' + + '\\u001b[A-M]', + 'g' +); + +// Standard keys defined by unist: https://github.com/syntax-tree/unist. +// We don’t ignore `data` though. +var ignore$2 = ['type', 'value', 'children', 'position']; + +// Inspects a node, without using color. +function noColor(node, pad) { + return stripColor(inspect(node, pad)) +} + +// Inspects a node. +function inspect(node, pad) { + var result; + var children; + var index; + var length; + + if (node && Boolean(node.length) && typeof node !== 'string') { + length = node.length; + index = -1; + result = []; + + while (++index < length) { + result[index] = inspect(node[index]); + } + + return result.join('\n') + } + + if (!node || !node.type) { + return String(node) + } + + result = [formatNode(node)]; + children = node.children; + length = children && children.length; + index = -1; + + if (!length) { + return result[0] + } + + if (!pad || typeof pad === 'number') { + pad = ''; + } + + while (++index < length) { + node = children[index]; + + if (index === length - 1) { + result.push(formatNesting(pad + '└─ ') + inspect(node, pad + ' ')); + } else { + result.push(formatNesting(pad + '├─ ') + inspect(node, pad + '│ ')); + } + } + + return result.join('\n') +} + +// Colored nesting formatter. +function formatNesting(value) { + return dim(value) +} + +// Compile a single position. +function compile(pos) { + var values = []; + + if (!pos) { + return null + } + + values = [[pos.line || 1, pos.column || 1].join(':')]; + + if ('offset' in pos) { + values.push(String(pos.offset || 0)); + } + + return values +} + +// Compile a location. +function stringify$1(start, end) { + var values = []; + var positions = []; + var offsets = []; + + add(start); + add(end); + + if (positions.length !== 0) { + values.push(positions.join('-')); + } + + if (offsets.length !== 0) { + values.push(offsets.join('-')); + } + + return values.join(', ') + + // Add a position. + function add(position) { + var tuple = compile(position); + + if (tuple) { + positions.push(tuple[0]); + + if (tuple[1]) { + offsets.push(tuple[1]); + } + } + } +} + +// Colored node formatter. +function formatNode(node) { + var log = node.type; + var location = node.position || {}; + var position = stringify$1(location.start, location.end); + var key; + var values = []; + var value; + + if (node.children) { + log += dim('[') + yellow(node.children.length) + dim(']'); + } else if (typeof node.value === 'string') { + log += dim(': ') + green(JSON.stringify(node.value)); + } + + if (position) { + log += ' (' + position + ')'; + } + + for (key in node) { + value = node[key]; + + if ( + ignore$2.indexOf(key) !== -1 || + value === null || + value === undefined || + (typeof value === 'object' && lib(value)) + ) { + continue + } + + values.push('[' + key + '=' + JSON.stringify(value) + ']'); + } + + if (values.length !== 0) { + log += ' ' + values.join(''); + } + + return log +} + +// Remove ANSI colour from `value`. +function stripColor(value) { + return value.replace(colorExpression, '') +} + +// Factory to wrap values in ANSI colours. +function ansiColor(open, close) { + return color + + function color(value) { + return '\u001B[' + open + 'm' + value + '\u001B[' + close + 'm' + } +} + +var debug$7 = src('unified-engine:file-pipeline:stringify'); + + + +var stringify_1 = stringify$2; + +// Stringify a tree. +function stringify$2(context, file) { + var processor = context.processor; + var tree = context.tree; + var value; + + if (vfileStatistics(file).fatal) { + debug$7('Not compiling failed document'); + return + } + + if (!context.output && !context.out && !context.alwaysStringify) { + debug$7('Not compiling document without output settings'); + return + } + + debug$7('Compiling `%s`', file.path); + + if (context.inspect) { + // Add a `txt` extension if there is a path. + if (file.path) { + file.extname = '.txt'; + } + + value = unistUtilInspect[context.color ? 'color' : 'noColor'](tree) + '\n'; + } else if (context.treeOut) { + // Add a `json` extension to ensure the file is correctly seen as JSON. + // Only add it if there is a path — not if the file is for example stdin. + if (file.path) { + file.extname = '.json'; + } + + // Add the line feed to create a valid UNIX file. + value = JSON.stringify(tree, null, 2) + '\n'; + } else { + value = processor.stringify(tree, file); + } + + file.contents = value; + + debug$7('Compiled document'); +} + +var debug$8 = src('unified-engine:file-pipeline:copy'); + + +var copy_1 = copy; + +var stat$1 = fs$1.stat; +var dirname$2 = path$1.dirname; +var resolve$5 = path$1.resolve; +var relative$3 = path$1.relative; + +// Move a file. +function copy(context, file, fileSet, next) { + var output = context.output; + var multi = fileSet.expected > 1; + var outpath = output; + var currentPath = file.path; + + if (!xIsString(outpath)) { + debug$8('Not copying'); + return next() + } + + outpath = resolve$5(context.cwd, outpath); + + debug$8('Copying `%s`', currentPath); + + stat$1(outpath, onstatfile); + + function onstatfile(error, stats) { + if (error) { + if ( + error.code !== 'ENOENT' || + output.charAt(output.length - 1) === path$1.sep + ) { + return next( + new Error('Cannot read output directory. Error:\n' + error.message) + ) + } + + stat$1(dirname$2(outpath), onstatparent); + } else { + done(stats.isDirectory()); + } + } + + // This is either given an error, or the parent exists which is a directory, + // but we should keep the basename of the given file. + function onstatparent(error) { + if (error) { + next(new Error('Cannot read parent directory. Error:\n' + error.message)); + } else { + done(false); + } + } + + function done(directory) { + if (!directory && multi) { + return next( + new Error('Cannot write multiple files to single output: ' + outpath) + ) + } + + file[directory ? 'dirname' : 'path'] = relative$3(file.cwd, outpath); + + debug$8('Copying document from %s to %s', currentPath, file.path); + + next(); + } +} + +var debug$9 = src('unified-engine:file-pipeline:stdout'); + + +var stdout_1 = stdout; + +// Write a virtual file to `streamOut`. +// Ignored when `output` is given, more than one file was processed, or `out` +// is false. +function stdout(context, file, fileSet, next) { + if (!file.data.unifiedEngineGiven) { + debug$9('Ignoring programmatically added file'); + next(); + } else if (vfileStatistics(file).fatal || context.output || !context.out) { + debug$9('Ignoring writing to `streamOut`'); + next(); + } else { + debug$9('Writing document to `streamOut`'); + context.streamOut.write(file.toString(), next); + } +} + +var debug$a = src('unified-engine:file-pipeline:file-system'); + + +var fileSystem_1$1 = fileSystem$1; + +var writeFile = fs$1.writeFile; +var resolve$6 = path$1.resolve; + +// Write a virtual file to the file-system. +// Ignored when `output` is not given. +function fileSystem$1(context, file, fileSet, next) { + var destinationPath; + + if (!context.output) { + debug$a('Ignoring writing to file-system'); + return next() + } + + if (!file.data.unifiedEngineGiven) { + debug$a('Ignoring programmatically added file'); + return next() + } + + destinationPath = file.path; + + if (!destinationPath) { + debug$a('Cannot write file without a `destinationPath`'); + return next(new Error('Cannot write file without an output path')) + } + + if (vfileStatistics(file).fatal) { + debug$a('Cannot write file with a fatal error'); + return next() + } + + destinationPath = resolve$6(context.cwd, destinationPath); + debug$a('Writing document to `%s`', destinationPath); + + file.stored = true; + + writeFile(destinationPath, file.toString(), next); +} + +// This pipeline ensures each of the pipes always runs: even if the read pipe +// fails, queue and write run. +var filePipeline = trough_1() + .use( + chunk( + trough_1() + .use(read_1$1) + .use(configure_1$1) + .use(parse_1) + .use(transform_1) + ) + ) + .use(chunk(trough_1().use(queue_1))) + .use( + chunk( + trough_1() + .use(stringify_1) + .use(copy_1) + .use(stdout_1) + .use(fileSystem_1$1) + ) + ); + +// Factory to run a pipe. +// Wraps a pipe to trigger an error on the `file` in `context`, but still call +// `next`. +function chunk(pipe) { + return run + + // Run the bound bound pipe and handles any errors. + function run(context, file, fileSet, next) { + pipe.run(context, file, fileSet, one); + + function one(error) { + var messages = file.messages; + var index; + + if (error) { + index = messages.indexOf(error); + + if (index === -1) { + error = file.message(error); + index = messages.length - 1; + } + + messages[index].fatal = true; + } + + next(); + } + } +} + +var transform_1$1 = transform$1; + +// Transform all files. +function transform$1(context, settings, next) { + var fileSet$1 = new fileSet(); + + context.fileSet = fileSet$1; + + fileSet$1.on('add', add).on('done', next); + + if (context.files.length === 0) { + next(); + } else { + context.files.forEach(fileSet$1.add, fileSet$1); + } + + function add(file) { + filePipeline.run( + { + configuration: context.configuration, + processor: settings.processor(), + cwd: settings.cwd, + extensions: settings.extensions, + pluginPrefix: settings.pluginPrefix, + treeIn: settings.treeIn, + treeOut: settings.treeOut, + inspect: settings.inspect, + color: settings.color, + out: settings.out, + output: settings.output, + streamOut: settings.streamOut, + alwaysStringify: settings.alwaysStringify + }, + file, + fileSet$1, + done + ); + + function done(error) { + /* istanbul ignore next - Does not occur as all failures in `filePipeLine` + * are failed on each file. + * Still, just to ensure things work in the future, we add an extra + * check. */ + if (error) { + error = file.message(error); + error.fatal = true; + } + + fileSet$1.emit('one', file); + } + } +} + +const {env: env$1} = process; + +let forceColor$1; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor$1 = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor$1 = 1; +} +if ('FORCE_COLOR' in env$1) { + if (env$1.FORCE_COLOR === true || env$1.FORCE_COLOR === 'true') { + forceColor$1 = 1; + } else if (env$1.FORCE_COLOR === false || env$1.FORCE_COLOR === 'false') { + forceColor$1 = 0; + } else { + forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); + } +} + +function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$1(stream) { + if (forceColor$1 === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor$1 === undefined) { + return 0; + } + + const min = forceColor$1 || 0; + + if (env$1.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + return min; +} + +function getSupportLevel$1(stream) { + const level = supportsColor$1(stream); + return translateLevel$1(level); +} + +var supportsColor_1$1 = { + supportsColor: getSupportLevel$1, + stdout: getSupportLevel$1(process.stdout), + stderr: getSupportLevel$1(process.stderr) +}; + +var ansiRegex = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; + +var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +/* eslint-disable yoda */ + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +var isFullwidthCodePoint_1 = isFullwidthCodePoint; +var default_1 = isFullwidthCodePoint; +isFullwidthCodePoint_1.default = default_1; + +var emojiRegex = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +const stringWidth = string => { + string = string.replace(emojiRegex(), ' '); + + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint_1(code) ? 2 : 1; + } + + return width; +}; + +var stringWidth_1 = stringWidth; +// TODO: remove this in the next major version +var default_1$1 = stringWidth; +stringWidth_1.default = default_1$1; + +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +/** + * Results cache + */ + +var res = ''; +var cache; + +/** + * Expose `repeat` + */ + +var repeatString = repeat$1; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat$1(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } + + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } + + num >>= 1; + str += str; + } + + res += str; + res = res.substr(0, max); + return res; +} + +var vfileSort = sort; + +var severities = { + true: 2, + false: 1, + null: 0, + undefined: 0 +}; + +function sort(file) { + file.messages.sort(comparator); + return file +} + +function comparator(a, b) { + return ( + check$1(a, b, 'line') || + check$1(a, b, 'column') || + severities[b.fatal] - severities[a.fatal] || + compare(a, b, 'source') || + compare(a, b, 'ruleId') || + compare(a, b, 'reason') || + 0 + ) +} + +function check$1(a, b, property) { + return (a[property] || 0) - (b[property] || 0) +} + +function compare(a, b, property) { + return (a[property] || '').localeCompare(b[property] || '') +} + +var supported = supportsColor_1$1.stderr.hasBasic; + + + + + + +var vfileReporter = reporter; + +// Check which characters should be used. +var windows$1 = process.platform === 'win32'; +// `log-symbols` without chalk: +/* istanbul ignore next - Windows. */ +var chars = windows$1 ? {error: '×', warning: '‼'} : {error: '✖', warning: '⚠'}; + +// Match trailing white-space. +var trailing = /\s*$/; + +// Default filename. +var DEFAULT = ''; + +var noop = {open: '', close: ''}; + +var colors = { + underline: {open: '\u001B[4m', close: '\u001B[24m'}, + red: {open: '\u001B[31m', close: '\u001B[39m'}, + yellow: {open: '\u001B[33m', close: '\u001B[39m'}, + green: {open: '\u001B[32m', close: '\u001B[39m'} +}; + +var noops = { + underline: noop, + red: noop, + yellow: noop, + green: noop +}; + +var labels = { + true: 'error', + false: 'warning', + null: 'info', + undefined: 'info' +}; + +// Report a file’s messages. +function reporter(files, options) { + var settings = options || {}; + var one; + + if (!files) { + return '' + } + + // Error. + if ('name' in files && 'message' in files) { + return String(files.stack || files) + } + + // One file. + if (!('length' in files)) { + one = true; + files = [files]; + } + + return compile$1(parse$4(filter$1(files, settings), settings), one, settings) +} + +function filter$1(files, options) { + var result = []; + var length = files.length; + var index = -1; + var file; + + if (!options.quiet && !options.silent) { + return files.concat() + } + + while (++index < length) { + file = files[index]; + + if (applicable(file, options).length !== 0) { + result.push(file); + } + } + + return result +} + +function parse$4(files, options) { + var length = files.length; + var index = -1; + var rows = []; + var all = []; + var locationSize = 0; + var labelSize = 0; + var reasonSize = 0; + var ruleIdSize = 0; + var file; + var destination; + var origin; + var messages; + var offset; + var count; + var message; + var loc; + var reason; + var label; + var id; + + while (++index < length) { + file = files[index]; + destination = file.path; + origin = file.history[0] || destination; + messages = vfileSort({messages: applicable(file, options)}).messages; + + if (rows.length !== 0 && rows[rows.length - 1].type !== 'header') { + rows.push({type: 'separator'}); + } + + rows.push({ + type: 'header', + origin: origin, + destination: destination, + name: origin || options.defaultName || DEFAULT, + stored: Boolean(file.stored), + moved: Boolean(file.stored && destination !== origin), + stats: vfileStatistics(messages) + }); + + offset = -1; + count = messages.length; + + while (++offset < count) { + message = messages[offset]; + id = message.ruleId || ''; + reason = message.stack || message.message; + loc = message.location; + loc = unistUtilStringifyPosition(loc.end.line && loc.end.column ? loc : loc.start); + + if (options.verbose && message.note) { + reason += '\n' + message.note; + } + + label = labels[message.fatal]; + + rows.push({ + location: loc, + label: label, + reason: reason, + ruleId: id, + source: message.source + }); + + locationSize = Math.max(realLength(loc), locationSize); + labelSize = Math.max(realLength(label), labelSize); + reasonSize = Math.max(realLength(reason), reasonSize); + ruleIdSize = Math.max(realLength(id), ruleIdSize); + } + + all = all.concat(messages); + } + + return { + rows: rows, + statistics: vfileStatistics(all), + location: locationSize, + label: labelSize, + reason: reasonSize, + ruleId: ruleIdSize + } +} + +// eslint-disable-next-line complexity +function compile$1(map, one, options) { + var enabled = options.color; + var all = map.statistics; + var rows = map.rows; + var length = rows.length; + var index = -1; + var lines = []; + var row; + var line; + var style; + var color; + var reason; + var rest; + var position; + + if (enabled === null || enabled === undefined) { + enabled = supported; + } + + style = enabled ? colors : noops; + + while (++index < length) { + row = rows[index]; + + if (row.type === 'separator') { + lines.push(''); + } else if (row.type === 'header') { + if (one && !options.defaultName && !row.origin) { + line = ''; + } else { + color = + style[row.stats.fatal ? 'red' : row.stats.total ? 'yellow' : 'green']; + line = + style.underline.open + + color.open + + row.name + + color.close + + style.underline.close; + line += row.moved ? ' > ' + row.destination : ''; + } + + if (!row.stats.total) { + line += line ? ': ' : ''; + + if (row.stored) { + line += style.yellow.open + 'written' + style.yellow.close; + } else { + line += 'no issues found'; + } + } + + if (line) { + lines.push(line); + } + } else { + color = style[row.label === 'error' ? 'red' : 'yellow']; + + reason = row.reason; + rest = ''; + position = reason.indexOf('\n'); + + if (position !== -1) { + rest = reason.slice(position); + reason = reason.slice(0, position); + } + + lines.push( + [ + '', + padLeft(row.location, map.location), + padRight(color.open + row.label + color.close, map.label), + padRight(reason, map.reason), + padRight(row.ruleId, map.ruleId), + row.source || '' + ] + .join(' ') + .replace(trailing, '') + rest + ); + } + } + + if (all.fatal || all.warn) { + line = []; + + if (all.fatal) { + line.push( + [ + style.red.open + chars.error + style.red.close, + all.fatal, + plural$1(labels.true, all.fatal) + ].join(' ') + ); + } + + if (all.warn) { + line.push( + [ + style.yellow.open + chars.warning + style.yellow.close, + all.warn, + plural$1(labels.false, all.warn) + ].join(' ') + ); + } + + line = line.join(', '); + + if (all.total !== all.fatal && all.total !== all.warn) { + line = all.total + ' messages (' + line + ')'; + } + + lines.push('', line); + } + + return lines.join('\n') +} + +function applicable(file, options) { + var messages = file.messages; + var length = messages.length; + var index = -1; + var result = []; + + if (options.silent) { + while (++index < length) { + if (messages[index].fatal) { + result.push(messages[index]); + } + } + } else { + result = messages.concat(); + } + + return result +} + +// Get the length of `value`, ignoring ANSI sequences. +function realLength(value) { + var length = value.indexOf('\n'); + return stringWidth_1(length === -1 ? value : value.slice(0, length)) +} + +// Pad `value` on the left. +function padLeft(value, minimum) { + return repeatString(' ', minimum - realLength(value)) + value +} + +// Pad `value` on the right. +function padRight(value, minimum) { + return value + repeatString(' ', minimum - realLength(value)) +} + +function plural$1(value, count) { + return count === 1 ? value : value + 's' +} + +var log_1 = log; + +var prefix$1 = 'vfile-reporter'; + +function log(context, settings, next) { + var reporter = settings.reporter || vfileReporter; + var diagnostics; + + if (xIsString(reporter)) { + try { + reporter = loadPlugin_1(reporter, {cwd: settings.cwd, prefix: prefix$1}); + } catch (error) { + next(new Error('Could not find reporter `' + reporter + '`')); + return + } + } + + diagnostics = reporter( + context.files.filter(given), + immutable(settings.reporterOptions, { + quiet: settings.quiet, + silent: settings.silent, + color: settings.color + }) + ); + + if (diagnostics) { + if (diagnostics.charAt(diagnostics.length - 1) !== '\n') { + diagnostics += '\n'; + } + + settings.streamError.write(diagnostics, next); + } else { + next(); + } +} + +function given(file) { + return file.data.unifiedEngineGiven +} + +var fileSetPipeline = trough_1() + .use(configure_1) + .use(fileSystem_1) + .use(stdin_1) + .use(transform_1$1) + .use(log_1); + +var PassThrough = stream.PassThrough; + + + +var lib$1 = run; + +// Run the file set pipeline once. +// `callback` is invoked with a fatal error, or with a status code (`0` on +// success, `1` on failure). +function run(options, callback) { + var settings = {}; + var stdin = new PassThrough(); + var tree; + var detectConfig; + var hasConfig; + var detectIgnore; + var hasIgnore; + + try { + stdin = process.stdin; + } catch (error) { + // Obscure bug in Node (seen on Windows). + // See: , + // . + } + + if (!callback) { + throw new Error('Missing `callback`') + } + + if (!options || !options.processor) { + return next(new Error('Missing `processor`')) + } + + // Processor. + settings.processor = options.processor; + + // Path to run as. + settings.cwd = options.cwd || process.cwd(); + + // Input. + settings.files = options.files || []; + settings.extensions = (options.extensions || []).map(extension); + + settings.filePath = options.filePath || null; + settings.streamIn = options.streamIn || stdin; + + // Output. + settings.streamOut = options.streamOut || process.stdout; + settings.streamError = options.streamError || process.stderr; + settings.alwaysStringify = options.alwaysStringify; + settings.output = options.output; + settings.out = options.out; + + // Null overwrites config settings, `undefined` does not. + if (settings.output === null || settings.output === undefined) { + settings.output = undefined; + } + + if (settings.output && settings.out) { + return next(new Error('Cannot accept both `output` and `out`')) + } + + // Process phase management. + tree = options.tree || false; + + settings.treeIn = options.treeIn; + settings.treeOut = options.treeOut; + settings.inspect = options.inspect; + + if (settings.treeIn === null || settings.treeIn === undefined) { + settings.treeIn = tree; + } + + if (settings.treeOut === null || settings.treeOut === undefined) { + settings.treeOut = tree; + } + + // Configuration. + detectConfig = options.detectConfig; + hasConfig = Boolean(options.rcName || options.packageField); + + if (detectConfig && !hasConfig) { + return next( + new Error('Missing `rcName` or `packageField` with `detectConfig`') + ) + } + + settings.detectConfig = + detectConfig === null || detectConfig === undefined + ? hasConfig + : detectConfig; + settings.rcName = options.rcName || null; + settings.rcPath = options.rcPath || null; + settings.packageField = options.packageField || null; + settings.settings = options.settings || {}; + settings.configTransform = options.configTransform; + settings.defaultConfig = options.defaultConfig; + + // Ignore. + detectIgnore = options.detectIgnore; + hasIgnore = Boolean(options.ignoreName); + + settings.detectIgnore = + detectIgnore === null || detectIgnore === undefined + ? hasIgnore + : detectIgnore; + settings.ignoreName = options.ignoreName || null; + settings.ignorePath = options.ignorePath || null; + settings.ignorePatterns = options.ignorePatterns || []; + settings.silentlyIgnore = Boolean(options.silentlyIgnore); + + if (detectIgnore && !hasIgnore) { + return next(new Error('Missing `ignoreName` with `detectIgnore`')) + } + + // Plugins. + settings.pluginPrefix = options.pluginPrefix || null; + settings.plugins = options.plugins || {}; + + // Reporting. + settings.reporter = options.reporter || null; + settings.reporterOptions = options.reporterOptions || null; + settings.color = options.color || false; + settings.silent = options.silent || false; + settings.quiet = options.quiet || false; + settings.frail = options.frail || false; + + // Process. + fileSetPipeline.run({files: options.files || []}, settings, next); + + function next(error, context) { + var stats = vfileStatistics((context || {}).files); + var failed = Boolean( + settings.frail ? stats.fatal || stats.warn : stats.fatal + ); + + if (error) { + callback(error); + } else { + callback(null, failed ? 1 : 0, context); + } + } +} + +function extension(ext) { + return ext.charAt(0) === '.' ? ext : '.' + ext +} + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +var conversions = createCommonjsModule(function (module) { +/* MIT license */ + + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in colorName) { + if (colorName.hasOwnProperty(key)) { + reverseKeywords[colorName[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName) { + if (colorName.hasOwnProperty(keyword)) { + var value = colorName[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return colorName[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; +}); +var conversions_1 = conversions.rgb; +var conversions_2 = conversions.hsl; +var conversions_3 = conversions.hsv; +var conversions_4 = conversions.hwb; +var conversions_5 = conversions.cmyk; +var conversions_6 = conversions.xyz; +var conversions_7 = conversions.lab; +var conversions_8 = conversions.lch; +var conversions_9 = conversions.hex; +var conversions_10 = conversions.keyword; +var conversions_11 = conversions.ansi16; +var conversions_12 = conversions.ansi256; +var conversions_13 = conversions.hcg; +var conversions_14 = conversions.apple; +var conversions_15 = conversions.gray; + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +var colorConvert = convert; + +var ansiStyles = createCommonjsModule(function (module) { + + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +}); + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +var templates = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + +var chalk = createCommonjsModule(function (module) { + + +const stdoutColor = supportsColor_1.stdout; + + + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript +}); +var chalk_1 = chalk.supportsColor; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$1.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +var utils$1 = createCommonjsModule(function (module, exports) { + + +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = constants; + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; + +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path$1.sep === '\\'; +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; +}); +var utils_1$1 = utils$1.isObject; +var utils_2$1 = utils$1.hasRegexChars; +var utils_3$1 = utils$1.isRegexChar; +var utils_4$1 = utils$1.escapeRegex; +var utils_5$1 = utils$1.toPosixSlashes; +var utils_6 = utils$1.removeBackslashes; +var utils_7 = utils$1.supportsLookbehinds; +var utils_8 = utils$1.isWindows; +var utils_9 = utils$1.escapeLast; +var utils_10 = utils$1.removePrefix; +var utils_11 = utils$1.wrapOutput; + +const { + CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ +} = constants; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), and `negated` (true if the path starts with `!`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$1 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK$1 + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK$1) { + if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + } + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + } + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$1.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$1.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$1; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils$1.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$5 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = (opts) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$1.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index]; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + + + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.prev.type === 'bos' && eos()) { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$1.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance() || ''; + } else { + value += advance() || ''; + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE$1[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$1.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$1.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = `\\}`; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$1.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$1.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$1.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$1.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$5.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = (opts) => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$1.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$5; + +const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject$2(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$1.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$1.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path$1.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse_1$1(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan_1(input, options); + +/** + * Create a regular expression from a glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.makeRe(input[, options]); + * + * console.log(picomatch.makeRe('*.js')); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `input` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return parsed.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${parsed.output})${append}`; + if (parsed && parsed.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = parsed; + } + + return regex; +}; + +picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + const opts = options || {}; + let parsed = { negated: false, fastpaths: true }; + let prefix = ''; + let output; + + if (input.startsWith('./')) { + input = input.slice(2); + prefix = parsed.prefix = './'; + } + + if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + output = parse_1$1.fastpaths(input, options); + } + + if (output === undefined) { + parsed = parse_1$1(input, options); + parsed.prefix = prefix + (parsed.prefix || ''); + } else { + parsed.output = output; + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch; + +var picomatch$1 = picomatch_1; + +const { Readable } = stream; + +const { promisify } = util$1; + + +const readdir$1 = promisify(fs$1.readdir); +const stat$2 = promisify(fs$1.stat); +const lstat = promisify(fs$1.lstat); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG = '!'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']); +const FILE_TYPE = 'files'; +const DIR_TYPE = 'directories'; +const FILE_DIR_TYPE = 'files_directories'; +const EVERYTHING_TYPE = 'all'; +const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + +const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); + +const normalizeFilter = filter => { + if (filter === undefined) return; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch$1(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch$1(trimmed.slice(1))); + } else { + positive.push(picomatch$1(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat : stat$2; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (process.platform === 'win32' && stat$2.length === 3) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = path$1.resolve(root); + this._isDirent = ('Dirent' in fs$1) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + try { + this.parents = [this._exploreDir(root, 1)]; + } catch (error) { + this.destroy(error); + } + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this._isDirAndMatchesFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if (this._isFileAndMatchesFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir$1(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return {files, depth, path}; + } + + async _formatEntry(dirent, path) { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = path$1.resolve(path$1.join(path, basename)); + const entry = {path: path$1.relative(this._root, fullPath), fullPath, basename}; + try { + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + throw err; + } + } + + _isDirAndMatchesFilter(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + return stats && stats.isDirectory() && this._directoryFilter(entry); + } + + _isFileAndMatchesFilter(entry) { + const stats = entry && entry[this._statsProp]; + const isFileType = stats && ( + (this._wantsEverything && !stats.isDirectory()) || + (stats.isFile() || stats.isSymbolicLink()) + ); + return isFileType && this._fileFilter(entry); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp.promise = readdirpPromise; +readdirp.ReaddirpStream = ReaddirpStream; +readdirp.default = readdirp; + +var readdirp_1 = readdirp; + +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +var normalizePath = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + + var len = path.length; + if (len <= 1) return path; + + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; + +var anymatch_1 = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, "__esModule", { value: true }); + + + + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch$1(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch$1(item, opts)); + const patterns = mtchers.map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; +}); + +unwrapExports(anymatch_1); + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + +var chars$1 = { '{': '}', '(': ')', '[': ']'}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +var isGlob = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; + + // optionally relax regex + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while ((match = regex.exec(str))) { + if (match[2]) return true; + var idx = match.index + match[0].length; + + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + var open = match[1]; + var close = open ? chars$1[open] : null; + if (open && close) { + var n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + return false; +}; + +var pathPosixDirname = path$1.posix.dirname; +var isWin32 = os.platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +var globParent = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$2 = createCommonjsModule(function (module, exports) { + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; +}; +}); +var utils_1$2 = utils$2.isInteger; +var utils_2$2 = utils$2.find; +var utils_3$2 = utils$2.exceedsLimit; +var utils_4$2 = utils$2.escapeNode; +var utils_5$2 = utils$2.encloseBrace; +var utils_6$1 = utils$2.isInvalidBrace; +var utils_7$1 = utils$2.isOpenOrClose; +var utils_8$1 = utils$2.reduce; +var utils_9$1 = utils$2.flatten; + +var stringify$3 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$1 = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; + +const toRegexRange = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare$1); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare$1(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange; + +const isObject$3 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform$2 = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber$2 = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify$4 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange_1(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange_1(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util$1.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$4(start, end, options) === false; + let format = options.transform || transform$2(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber$2(start) && start.length > 1) || (!isNumber$2(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } + + if (isObject$3(step)) { + return fill(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber$2(step)) { + if (step != null && !isObject$3(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber$2(start) && isNumber$2(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill; + +const compile$2 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$2.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$2.reduce(node.nodes); + let range = fillRange(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$2; + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$2.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + } + } + } + return utils$2.flatten(result); +}; + +const expand$2 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify$3(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$2.reduce(node.nodes); + + if (utils$2.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fillRange(...args, options); + if (range.length === 0) { + range = stringify$3(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$2.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$2.flatten(walk(ast)); +}; + +var expand_1 = expand$2; + +var constants$1 = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA: CHAR_COMMA$2, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2, /* ] */ + CHAR_DOUBLE_QUOTE: CHAR_DOUBLE_QUOTE$1, /* " */ + CHAR_SINGLE_QUOTE: CHAR_SINGLE_QUOTE$1, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$1; + +/** + * parse + */ + +const parse$6 = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET$2) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET$2) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET$2) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$2) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES$1) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES$1) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE$1 || value === CHAR_SINGLE_QUOTE$1 || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE$1) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE$1) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA$2 && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$3(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +var parse_1$2 = parse$6; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse_1$2(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$3(braces.parse(input, options), options); + } + return stringify$3(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile_1(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand_1(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces; + +var binaryExtensions = [ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "oga", + "ogg", + "ogv", + "otf", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +]; + +var binaryExtensions$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': binaryExtensions +}); + +var require$$0 = getCjsExportFromNamespace(binaryExtensions$1); + +var binaryExtensions$2 = require$$0; + +const extensions = new Set(binaryExtensions$2); + +var isBinaryPath = filePath => extensions.has(path$1.extname(filePath).slice(1).toLowerCase()); + +var constants$2 = createCommonjsModule(function (module, exports) { + +const {sep} = path$1; +const {platform} = process; + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +}); +var constants_1 = constants$2.EV_ALL; +var constants_2 = constants$2.EV_READY; +var constants_3 = constants$2.EV_ADD; +var constants_4 = constants$2.EV_CHANGE; +var constants_5 = constants$2.EV_ADD_DIR; +var constants_6 = constants$2.EV_UNLINK; +var constants_7 = constants$2.EV_UNLINK_DIR; +var constants_8 = constants$2.EV_RAW; +var constants_9 = constants$2.EV_ERROR; +var constants_10 = constants$2.STR_DATA; +var constants_11 = constants$2.STR_END; +var constants_12 = constants$2.STR_CLOSE; +var constants_13 = constants$2.FSEVENT_CREATED; +var constants_14 = constants$2.FSEVENT_MODIFIED; +var constants_15 = constants$2.FSEVENT_DELETED; +var constants_16 = constants$2.FSEVENT_MOVED; +var constants_17 = constants$2.FSEVENT_CLONED; +var constants_18 = constants$2.FSEVENT_UNKNOWN; +var constants_19 = constants$2.FSEVENT_TYPE_DIRECTORY; +var constants_20 = constants$2.FSEVENT_TYPE_SYMLINK; +var constants_21 = constants$2.KEY_LISTENERS; +var constants_22 = constants$2.KEY_ERR; +var constants_23 = constants$2.KEY_RAW; +var constants_24 = constants$2.HANDLER_KEYS; +var constants_25 = constants$2.DOT_SLASH; +var constants_26 = constants$2.BACK_SLASH_RE; +var constants_27 = constants$2.DOUBLE_SLASH_RE; +var constants_28 = constants$2.SLASH_OR_BACK_SLASH_RE; +var constants_29 = constants$2.DOT_RE; +var constants_30 = constants$2.REPLACER_RE; +var constants_31 = constants$2.SLASH; +var constants_32 = constants$2.BRACE_START; +var constants_33 = constants$2.BANG; +var constants_34 = constants$2.ONE_DOT; +var constants_35 = constants$2.TWO_DOTS; +var constants_36 = constants$2.STAR; +var constants_37 = constants$2.GLOBSTAR; +var constants_38 = constants$2.ROOT_GLOBSTAR; +var constants_39 = constants$2.SLASH_GLOBSTAR; +var constants_40 = constants$2.DIR_SUFFIX; +var constants_41 = constants$2.ANYMATCH_OPTS; +var constants_42 = constants$2.STRING_TYPE; +var constants_43 = constants$2.FUNCTION_TYPE; +var constants_44 = constants$2.EMPTY_STR; +var constants_45 = constants$2.EMPTY_FN; +var constants_46 = constants$2.IDENTITY_FN; +var constants_47 = constants$2.isWindows; +var constants_48 = constants$2.isMacos; + +const { promisify: promisify$1 } = util$1; + +const { + isWindows: isWindows$1, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR: STAR$1 +} = constants$2; + +const THROTTLE_MODE_WATCH = 'watch'; + +const open = promisify$1(fs$1.open); +const stat$3 = promisify$1(fs$1.stat); +const lstat$1 = promisify$1(fs$1.lstat); +const close = promisify$1(fs$1.close); +const fsrealpath = promisify$1(fs$1.realpath); + +const statMethods = { lstat: lstat$1, stat: stat$3 }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + path$1.resolve(path, evPath), KEY_LISTENERS, path$1.join(path, evPath) + ); + } + }; + try { + return fs$1.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows$1 && error.code === 'EPERM') { + try { + const fd = await open(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + /* eslint-disable no-unused-vars, prefer-destructuring */ + let listeners = new Set(); + let rawEmitters = new Set(); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + // "Upgrade" the watcher to persistence or a quicker interval. + // This creates some unlikely edge case issues if the user mixes + // settings in a very weird way, but solving for those cases + // doesn't seem worthwhile for the added complexity. + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs$1.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs$1.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs$1.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = path$1.dirname(path); + const basename = path$1.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = path$1.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = path$1.dirname(file); + const basename = path$1.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + // kick off the watcher + const closer = this._watchWithNodeFs(file, async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat$3(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + }); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) return; + this.fsw._emit(EV_ADD, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + const linkPath = await fsrealpath(path); + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = path$1.join(directory, EMPTY_STR); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = path$1.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = path$1.join(dir, path$1.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: path$1.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(path$1.dirname(dir)); + const tracked = parentDir.has(path$1.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(path$1.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR$1) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (path !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(targetPath, true); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = path$1.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(path$1.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +var nodefsHandler = NodeFsHandler; + +const { promisify: promisify$2 } = util$1; + +let fsevents; +try { + fsevents = undefined; +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD: EV_ADD$1, + EV_CHANGE: EV_CHANGE$1, + EV_ADD_DIR: EV_ADD_DIR$1, + EV_UNLINK, + EV_ERROR: EV_ERROR$1, + STR_DATA: STR_DATA$1, + STR_END: STR_END$1, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN: EMPTY_FN$1, + IDENTITY_FN +} = constants$2; +const FS_MODE_READ = 'r'; + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat$4 = promisify$2(fs$1.stat); +const open$1 = promisify$2(fs$1.open); +const close$1 = promisify$2(fs$1.close); +const lstat$2 = promisify$2(fs$1.lstat); +const realpath$2 = promisify$2(fs$1.realpath); + +const statMethods$1 = { stat: stat$4, lstat: lstat$2 }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter, fsw) { + let watchPath = path$1.extname(path) ? path$1.dirname(path) : path; + const parentPath = path$1.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = path$1.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + path$1.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(path$1.resolve(watchedPath) + path$1.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (fsw.closed) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = path$1.dirname(path)) !== root) i++; + return i; +}; + +/** + * @mixin + */ +class FsEventsHandler { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const fd = await open$1(path, FS_MODE_READ); + if (this.fsw.closed) return; + await close$1(fd); + if (this.fsw.closed) return; + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK) { + // suppress unlink events on never before seen files + if (info.type === FSEVENT_TYPE_DIRECTORY || watchedDir.has(item)) { + this.fsw._remove(parent, item); + } + } else { + if (event === EV_ADD$1) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed) return; + if (this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(path$1.join( + watchPath, path$1.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = path$1.dirname(path); + const item = path$1.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat$4(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (stats) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw, + this.fsw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath$2(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = path$1.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(path$1.dirname(pp)); + const base = path$1.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + path$1.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods$1[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA$1, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = path$1.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, path$1.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath$2(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +var fseventsHandler = FsEventsHandler; +var canUse_1 = canUse; +fseventsHandler.canUse = canUse_1; + +const { EventEmitter } = events; + + +const { promisify: promisify$3 } = util$1; + +const anymatch = anymatch_1.default; + + + + + + + +const { + EV_ALL, + EV_READY, + EV_ADD: EV_ADD$2, + EV_CHANGE: EV_CHANGE$2, + EV_UNLINK: EV_UNLINK$1, + EV_ADD_DIR: EV_ADD_DIR$2, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR: EV_ERROR$2, + + STR_CLOSE, + STR_END: STR_END$2, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH: SLASH$1, + BRACE_START: BRACE_START$1, + BANG: BANG$1, + ONE_DOT, + TWO_DOTS, + GLOBSTAR: GLOBSTAR$1, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE: FUNCTION_TYPE$1, + EMPTY_STR: EMPTY_STR$1, + EMPTY_FN: EMPTY_FN$2, + + isWindows: isWindows$2, + isMacos +} = constants$2; + +const stat$5 = promisify$3(fs$1.stat); +const readdir$2 = promisify$3(fs$1.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH$1); + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH$1); + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(path$1.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR$1) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(path$1.isAbsolute(path) ? path : path$1.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (path$1.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG$1)) { + return BANG$1 + path$1.join(cwd, path.slice(1)); + } + return path$1.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + + if (!items.size) { + const dir = this.path; + try { + await readdir$2(dir); + } catch (err) { + this._removeWatcher(path$1.dirname(dir), path$1.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR$1); + this.watchPath = watchPath; + this.fullWatchPath = path$1.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR$1) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return path$1.join(this.watchPath, + path$1.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE$1 ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START$1) ? braces_1.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(path$1.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR$1) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = fseventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + + // Global override (useful for end-developers that need to force polling for all + // instances of chokidar, regardless of usage/dependency depth) + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN$2; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new fseventsHandler(this); + } else { + this._nodeFsHandler = new nodefsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG$1)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount *= 2; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(path$1.dirname(item), path$1.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!path$1.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = path$1.join(cwd, path); + path = path$1.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + return closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? path$1.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR$2) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows$2) path = path$1.normalize(path); + if (opts.cwd) path = path$1.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK$1) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD$2 && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE$2; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD$2 || event === EV_CHANGE$2) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR$2; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE$2) { + const isThrottled = !this._throttle(EV_CHANGE$2, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD$2 || event === EV_ADD_DIR$2 || event === EV_CHANGE$2) + ) { + const fullPath = opts.cwd ? path$1.join(opts.cwd, path) : path; + try { + const stats = await stat$5(fullPath); + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats) return; + args.push(stats); + this.emitWithAll(event, args); + } catch (err) {} + } else { + this.emitWithAll(event, args); + } + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR$2, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !path$1.isAbsolute(path)) { + fullPath = path$1.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs$1.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = path$1.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = path$1.join(directory, item); + const fullPath = path$1.resolve(path); + const isDirectory = this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = path$1.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD$2) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK$1; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * + * @param {Path} path + */ +_closePath(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); + const dir = path$1.dirname(path); + this._getWatchedDir(dir).remove(path$1.basename(path)); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp_1(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END$2, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +var FSWatcher_1 = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +var watch_1 = watch; + +var chokidar = { + FSWatcher: FSWatcher_1, + watch: watch_1 +}; + +var textTable = function (rows_, opts) { + if (!opts) opts = {}; + var hsep = opts.hsep === undefined ? ' ' : opts.hsep; + var align = opts.align || []; + var stringLength = opts.stringLength + || function (s) { return String(s).length; } + ; + + var dotsizes = reduce(rows_, function (acc, row) { + forEach(row, function (c, ix) { + var n = dotindex(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + var rows = map$1(rows_, function (row) { + return map$1(row, function (c_, ix) { + var c = String(c_); + if (align[ix] === '.') { + var index = dotindex(c); + var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) + - (stringLength(c) - index) + ; + return c + Array(size).join(' '); + } + else return c; + }); + }); + + var sizes = reduce(rows, function (acc, row) { + forEach(row, function (c, ix) { + var n = stringLength(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + return map$1(rows, function (row) { + return map$1(row, function (c, ix) { + var n = (sizes[ix] - stringLength(c)) || 0; + var s = Array(Math.max(n + 1, 1)).join(' '); + if (align[ix] === 'r' || align[ix] === '.') { + return s + c; + } + if (align[ix] === 'c') { + return Array(Math.ceil(n / 2 + 1)).join(' ') + + c + Array(Math.floor(n / 2 + 1)).join(' ') + ; + } + + return c + s; + }).join(hsep).replace(/\s+$/, ''); + }).join('\n'); +}; + +function dotindex (c) { + var m = /\.[^.]*$/.exec(c); + return m ? m.index + 1 : c.length; +} + +function reduce (xs, f, init) { + if (xs.reduce) return xs.reduce(f, init); + var i = 0; + var acc = arguments.length >= 3 ? init : xs[i++]; + for (; i < xs.length; i++) { + f(acc, xs[i], i); + } + return acc; +} + +function forEach (xs, f) { + if (xs.forEach) return xs.forEach(f); + for (var i = 0; i < xs.length; i++) { + f.call(xs, xs[i], i); + } +} + +function map$1 (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f.call(xs, xs[i], i)); + } + return res; +} + +const preserveCamelCase = string => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + + return string; +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = Object.assign({ + pascalCase: false + }, options); + + const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + + const hasUpperCase = input !== input.toLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) + .replace(/\d+(\w|$)/g, m => m.toUpperCase()); + + return postProcess(input); +}; + +var camelcase = camelCase; +// TODO: Remove this for the next major release +var default_1$2 = camelCase; +camelcase.default = default_1$2; + +// This is a generated file. Do not edit. +var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; +var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; +var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; + +var unicode = { + Space_Separator: Space_Separator, + ID_Start: ID_Start, + ID_Continue: ID_Continue +}; + +var util = { + isSpaceSeparator (c) { + return unicode.Space_Separator.test(c) + }, + + isIdStartChar (c) { + return ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar (c) { + return ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit (c) { + return /[0-9]/.test(c) + }, + + isHexDigit (c) { + return /[0-9A-Fa-f]/.test(c) + }, +}; + +let source; +let parseState; +let stack; +let pos; +let line; +let column; +let token; +let key; +let root; + +var parse$7 = function parse (text, reviver) { + source = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line = 1; + column = 0; + token = undefined; + key = undefined; + root = undefined; + + do { + token = lex(); + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root}, '', reviver) + } + + return root +}; + +function internalize (holder, name, reviver) { + const value = holder[name]; + if (value != null && typeof value === 'object') { + for (const key in value) { + const replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + value[key] = replacement; + } + } + } + + return reviver.call(holder, name, value) +} + +let lexState; +let buffer; +let doubleQuote; +let sign; +let c; + +function lex () { + lexState = 'default'; + buffer = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState](); + if (token) { + return token + } + } +} + +function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } +} + +function read$4 () { + const c = peek(); + + if (c === '\n') { + line++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c +} + +const lexStates = { + default () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$4(); + return + + case '/': + read$4(); + lexState = 'comment'; + return + + case undefined: + read$4(); + return newToken('eof') + } + + if (util.isSpaceSeparator(c)) { + read$4(); + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment () { + switch (c) { + case '*': + read$4(); + lexState = 'multiLineComment'; + return + + case '/': + read$4(); + lexState = 'singleLineComment'; + return + } + + throw invalidChar(read$4()) + }, + + multiLineComment () { + switch (c) { + case '*': + read$4(); + lexState = 'multiLineCommentAsterisk'; + return + + case undefined: + throw invalidChar(read$4()) + } + + read$4(); + }, + + multiLineCommentAsterisk () { + switch (c) { + case '*': + read$4(); + return + + case '/': + read$4(); + lexState = 'default'; + return + + case undefined: + throw invalidChar(read$4()) + } + + read$4(); + lexState = 'multiLineComment'; + }, + + singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$4(); + lexState = 'default'; + return + + case undefined: + read$4(); + return newToken('eof') + } + + read$4(); + }, + + value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$4()) + + case 'n': + read$4(); + literal('ull'); + return newToken('null', null) + + case 't': + read$4(); + literal('rue'); + return newToken('boolean', true) + + case 'f': + read$4(); + literal('alse'); + return newToken('boolean', false) + + case '-': + case '+': + if (read$4() === '-') { + sign = -1; + } + + lexState = 'sign'; + return + + case '.': + buffer = read$4(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read$4(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read$4(); + lexState = 'decimalInteger'; + return + + case 'I': + read$4(); + literal('nfinity'); + return newToken('numeric', Infinity) + + case 'N': + read$4(); + literal('aN'); + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read$4() === '"'); + buffer = ''; + lexState = 'string'; + return + } + + throw invalidChar(read$4()) + }, + + identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read$4()) + } + + read$4(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + break + + default: + if (!util.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read$4(); + return + + case '\\': + read$4(); + lexState = 'identifierNameEscape'; + return + } + + if (util.isIdContinueChar(c)) { + buffer += read$4(); + return + } + + return newToken('identifier', buffer) + }, + + identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read$4()) + } + + read$4(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + sign () { + switch (c) { + case '.': + buffer = read$4(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read$4(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read$4(); + lexState = 'decimalInteger'; + return + + case 'I': + read$4(); + literal('nfinity'); + return newToken('numeric', sign * Infinity) + + case 'N': + read$4(); + literal('aN'); + return newToken('numeric', NaN) + } + + throw invalidChar(read$4()) + }, + + zero () { + switch (c) { + case '.': + buffer += read$4(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + + case 'x': + case 'X': + buffer += read$4(); + lexState = 'hexadecimal'; + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger () { + switch (c) { + case '.': + buffer += read$4(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalPointLeading () { + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalFraction'; + return + } + + throw invalidChar(read$4()) + }, + + decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalFraction'; + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalExponent () { + switch (c) { + case '+': + case '-': + buffer += read$4(); + lexState = 'decimalExponentSign'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$4()) + }, + + decimalExponentSign () { + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$4()) + }, + + decimalExponentInteger () { + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + hexadecimal () { + if (util.isHexDigit(c)) { + buffer += read$4(); + lexState = 'hexadecimalInteger'; + return + } + + throw invalidChar(read$4()) + }, + + hexadecimalInteger () { + if (util.isHexDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + string () { + switch (c) { + case '\\': + read$4(); + buffer += escape(); + return + + case '"': + if (doubleQuote) { + read$4(); + return newToken('string', buffer) + } + + buffer += read$4(); + return + + case "'": + if (!doubleQuote) { + read$4(); + return newToken('string', buffer) + } + + buffer += read$4(); + return + + case '\n': + case '\r': + throw invalidChar(read$4()) + + case '\u2028': + case '\u2029': + separatorChar(c); + break + + case undefined: + throw invalidChar(read$4()) + } + + buffer += read$4(); + }, + + start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$4()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer = read$4(); + lexState = 'identifierName'; + return + + case '\\': + read$4(); + lexState = 'identifierNameStartEscape'; + return + + case '}': + return newToken('punctuator', read$4()) + + case '"': + case "'": + doubleQuote = (read$4() === '"'); + lexState = 'string'; + return + } + + if (util.isIdStartChar(c)) { + buffer += read$4(); + lexState = 'identifierName'; + return + } + + throw invalidChar(read$4()) + }, + + afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + beforePropertyValue () { + lexState = 'value'; + }, + + afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read$4()) + } + + lexState = 'value'; + }, + + afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read$4()) + }, +}; + +function newToken (type, value) { + return { + type, + value, + line, + column, + } +} + +function literal (s) { + for (const c of s) { + const p = peek(); + + if (p !== c) { + throw invalidChar(read$4()) + } + + read$4(); + } +} + +function escape () { + const c = peek(); + switch (c) { + case 'b': + read$4(); + return '\b' + + case 'f': + read$4(); + return '\f' + + case 'n': + read$4(); + return '\n' + + case 'r': + read$4(); + return '\r' + + case 't': + read$4(); + return '\t' + + case 'v': + read$4(); + return '\v' + + case '0': + read$4(); + if (util.isDigit(peek())) { + throw invalidChar(read$4()) + } + + return '\0' + + case 'x': + read$4(); + return hexEscape() + + case 'u': + read$4(); + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read$4(); + return '' + + case '\r': + read$4(); + if (peek() === '\n') { + read$4(); + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read$4()) + + case undefined: + throw invalidChar(read$4()) + } + + return read$4() +} + +function hexEscape () { + let buffer = ''; + let c = peek(); + + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + + c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +function unicodeEscape () { + let buffer = ''; + let count = 4; + + while (count-- > 0) { + const c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + } + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +const parseStates = { + start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop(); + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return + } + + push(); + }, + + afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return + + case '}': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return + + case ']': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, +}; + +function push () { + let value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break + + case '[': + value = []; + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root === undefined) { + root = value; + } else { + const parent = stack[stack.length - 1]; + if (Array.isArray(parent)) { + parent.push(value); + } else { + parent[key] = value; + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } +} + +function pop () { + stack.pop(); + + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } +} + +// This code is unreachable. +// function invalidParseState () { +// return new Error(`JSON5: invalid parse state '${parseState}'`) +// } + +// This code is unreachable. +// function invalidLexState (state) { +// return new Error(`JSON5: invalid lex state '${state}'`) +// } + +function invalidChar (c) { + if (c === undefined) { + return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) + } + + return syntaxError$1(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +} + +function invalidEOF () { + return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) +} + +// This code is unreachable. +// function invalidToken () { +// if (token.type === 'eof') { +// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +// } + +// const c = String.fromCodePoint(token.value.codePointAt(0)) +// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +// } + +function invalidIdentifier () { + column -= 5; + return syntaxError$1(`JSON5: invalid identifier character at ${line}:${column}`) +} + +function separatorChar (c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); +} + +function formatChar (c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c +} + +function syntaxError$1 (message) { + const err = new SyntaxError(message); + err.lineNumber = line; + err.columnNumber = column; + return err +} + +var stringify$5 = function stringify (value, replacer, space) { + const stack = []; + let indent = ''; + let propertyList; + let replacerFunc; + let gap = ''; + let quote; + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + for (const v of replacer) { + let item; + + if (typeof v === 'string') { + item = v; + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + let value = holder[key]; + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + const quotes = { + "'": 0.1, + '"': 0.2, + }; + + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + let product = ''; + + for (let i = 0; i < value.length; i++) { + const c = value[i]; + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue + + case '\0': + if (util.isDigit(value[i + 1])) { + product += '\\x00'; + continue + } + } + + if (replacements[c]) { + product += replacements[c]; + continue + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue + } + + product += c; + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let keys = propertyList || Object.keys(value); + let partial = []; + for (const key of keys) { + const propertyString = serializeProperty(key, value); + if (propertyString !== undefined) { + let member = serializeKey(key) + ':'; + if (gap !== '') { + member += ' '; + } + member += propertyString; + partial.push(member); + } + } + + let final; + if (partial.length === 0) { + final = '{}'; + } else { + let properties; + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + let separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key) + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)); + if (!util.isIdStartChar(firstChar)) { + return quoteString(key) + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let partial = []; + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value); + partial.push((propertyString !== undefined) ? propertyString : 'null'); + } + + let final; + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + let properties = partial.join(','); + final = '[' + properties + ']'; + } else { + let separator = ',\n' + indent; + let properties = partial.join(separator); + final = '[\n' + indent + properties + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final + } +}; + +const JSON5 = { + parse: parse$7, + stringify: stringify$5, +}; + +var lib$2 = JSON5; + +var dist = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': lib$2 +}); + +var schema$1 = [ + { + long: "help", + description: "output usage information", + short: "h", + type: "boolean", + "default": false + }, + { + long: "version", + description: "output version number", + short: "v", + type: "boolean", + "default": false + }, + { + long: "output", + description: "specify output location", + short: "o", + value: "[path]" + }, + { + long: "rc-path", + description: "specify configuration file", + short: "r", + type: "string", + value: "" + }, + { + long: "ignore-path", + description: "specify ignore file", + short: "i", + type: "string", + value: "" + }, + { + long: "setting", + description: "specify settings", + short: "s", + type: "string", + value: "" + }, + { + long: "ext", + description: "specify extensions", + short: "e", + type: "string", + value: "" + }, + { + long: "use", + description: "use plugins", + short: "u", + type: "string", + value: "" + }, + { + long: "watch", + description: "watch for changes and reprocess", + short: "w", + type: "boolean", + "default": false + }, + { + long: "quiet", + description: "output only warnings and errors", + short: "q", + type: "boolean", + "default": false + }, + { + long: "silent", + description: "output only errors", + short: "S", + type: "boolean", + "default": false + }, + { + long: "frail", + description: "exit with 1 on warnings", + short: "f", + type: "boolean", + "default": false + }, + { + long: "tree", + description: "specify input and output as syntax tree", + short: "t", + type: "boolean", + "default": false + }, + { + long: "report", + description: "specify reporter", + type: "string", + value: "" + }, + { + long: "file-path", + description: "specify path to process as", + type: "string", + value: "" + }, + { + long: "ignore-pattern", + description: "specify ignore patterns", + type: "string", + value: "" + }, + { + long: "tree-in", + description: "specify input as syntax tree", + type: "boolean" + }, + { + long: "tree-out", + description: "output syntax tree", + type: "boolean" + }, + { + long: "inspect", + description: "output formatted syntax tree", + type: "boolean" + }, + { + long: "stdout", + description: "specify writing to stdout", + type: "boolean", + truelike: true + }, + { + long: "color", + description: "specify color in report", + type: "boolean", + "default": true + }, + { + long: "config", + description: "search for configuration files", + type: "boolean", + "default": true + }, + { + long: "ignore", + description: "search for ignore files", + type: "boolean", + "default": true + } +]; + +var schema$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': schema$1 +}); + +var json5 = getCjsExportFromNamespace(dist); + +var schema$3 = getCjsExportFromNamespace(schema$2); + +var options_1 = options; + +// Schema for `minimist`. +var minischema = { + unknown: handleUnknownArgument, + default: {}, + alias: {}, + string: [], + boolean: [] +}; + +schema$3.forEach(addEach); + +// Parse CLI options. +function options(flags, configuration) { + var extension = configuration.extensions[0]; + var name = configuration.name; + var config = toCamelCase(minimist(flags, minischema)); + var help; + var ext; + var report; + + schema$3.forEach(function(option) { + if (option.type === 'string' && config[option.long] === '') { + throw fault_1('Missing value:%s', inspect$1(option).join(' ')) + } + }); + + ext = commaSeparated(config.ext); + report = reporter$1(config.report); + + help = [ + inspectAll(schema$3), + '', + 'Examples:', + '', + ' # Process `input.' + extension + '`', + ' $ ' + name + ' input.' + extension + ' -o output.' + extension, + '', + ' # Pipe', + ' $ ' + name + ' < input.' + extension + ' > output.' + extension, + '', + ' # Rewrite all applicable files', + ' $ ' + name + ' . -o' + ].join('\n'); + + return { + helpMessage: help, + // “hidden” feature, makes testing easier. + cwd: configuration.cwd, + processor: configuration.processor, + help: config.help, + version: config.version, + files: config._, + filePath: config.filePath, + watch: config.watch, + extensions: ext.length === 0 ? configuration.extensions : ext, + output: config.output, + out: config.stdout, + tree: config.tree, + treeIn: config.treeIn, + treeOut: config.treeOut, + inspect: config.inspect, + rcName: configuration.rcName, + packageField: configuration.packageField, + rcPath: config.rcPath, + detectConfig: config.config, + settings: settings(config.setting), + ignoreName: configuration.ignoreName, + ignorePath: config.ignorePath, + ignorePatterns: commaSeparated(config.ignorePattern), + detectIgnore: config.ignore, + pluginPrefix: configuration.pluginPrefix, + plugins: plugins(config.use), + reporter: report[0], + reporterOptions: report[1], + color: config.color, + silent: config.silent, + quiet: config.quiet, + frail: config.frail + } +} + +function addEach(option) { + var value = option.default; + + minischema.default[option.long] = value === undefined ? null : value; + + if (option.type in minischema) { + minischema[option.type].push(option.long); + } + + if (option.short) { + minischema.alias[option.short] = option.long; + } +} + +// Parse `extensions`. +function commaSeparated(value) { + return flatten$1(normalize$1(value).map(splitList)) +} + +// Parse `plugins`. +function plugins(value) { + var result = {}; + + normalize$1(value) + .map(splitOptions) + .forEach(function(value) { + result[value[0]] = value[1] ? parseConfig(value[1], {}) : null; + }); + + return result +} + +// Parse `reporter`: only one is accepted. +function reporter$1(value) { + var all = normalize$1(value) + .map(splitOptions) + .map(function(value) { + return [value[0], value[1] ? parseConfig(value[1], {}) : null] + }); + + return all[all.length - 1] || [] +} + +// Parse `settings`. +function settings(value) { + var cache = {}; + + normalize$1(value).forEach(function(value) { + parseConfig(value, cache); + }); + + return cache +} + +// Parse configuration. +function parseConfig(flags, cache) { + var flag; + var message; + + try { + flags = toCamelCase(parseJSON(flags)); + } catch (error) { + // Fix position + message = error.message.replace(/at(?= position)/, 'around'); + + throw fault_1('Cannot parse `%s` as JSON: %s', flags, message) + } + + for (flag in flags) { + cache[flag] = flags[flag]; + } + + return cache +} + +// Handle an unknown flag. +function handleUnknownArgument(flag) { + // Glob. + if (flag.charAt(0) !== '-') { + return + } + + // Long options, always unknown. + if (flag.charAt(1) === '-') { + throw fault_1('Unknown option `%s`, expected:\n%s', flag, inspectAll(schema$3)) + } + + // Short options, can be grouped. + flag + .slice(1) + .split('') + .forEach(each); + + function each(key) { + var length = schema$3.length; + var index = -1; + var option; + + while (++index < length) { + option = schema$3[index]; + + if (option.short === key) { + return + } + } + + throw fault_1( + 'Unknown short option `-%s`, expected:\n%s', + key, + inspectAll(schema$3.filter(short)) + ) + } + + function short(option) { + return option.short + } +} + +// Inspect all `options`. +function inspectAll(options) { + return textTable(options.map(inspect$1)) +} + +// Inspect one `option`. +function inspect$1(option) { + var description = option.description; + var long = option.long; + + if (option.default === true || option.truelike) { + description += ' (on by default)'; + long = '[no-]' + long; + } + + return [ + '', + option.short ? '-' + option.short : '', + '--' + long + (option.value ? ' ' + option.value : ''), + description + ] +} + +// Normalize `value`. +function normalize$1(value) { + if (!value) { + return [] + } + + if (typeof value === 'string') { + return [value] + } + + return flatten$1(value.map(normalize$1)) +} + +// Flatten `values`. +function flatten$1(values) { + return [].concat.apply([], values) +} + +function splitOptions(value) { + return value.split('=') +} + +function splitList(value) { + return value.split(',') +} + +// Transform the keys on an object to camel-case, recursivly. +function toCamelCase(object) { + var result = {}; + var value; + var key; + + for (key in object) { + value = object[key]; + + if (value && typeof value === 'object' && !('length' in value)) { + value = toCamelCase(value); + } + + result[camelcase(key)] = value; + } + + return result +} + +// Parse a (lazy?) JSON config. +function parseJSON(value) { + return json5.parse('{' + value + '}') +} + +var lib$3 = start; + +var noop$1 = Function.prototype; + +// Fake TTY stream. +var ttyStream = new stream.Readable(); +ttyStream.isTTY = true; + +// Exit, lazily, with the correct exit status code. +var exitStatus = 0; + +process.on('exit', onexit); + +// Handle uncaught errors, such as from unexpected async behaviour. +process.on('uncaughtException', fail$1); + +// Start the CLI. +function start(cliConfig) { + var config; + var output; + var watcher; + + try { + config = options_1(process.argv.slice(2), cliConfig); + } catch (error) { + return fail$1(error, true) + } + + if (config.help) { + process.stdout.write( + [ + 'Usage: ' + cliConfig.name + ' [options] [path | glob ...]', + '', + ' ' + cliConfig.description, + '', + 'Options:', + '', + config.helpMessage, + '' + ].join('\n'), + noop$1 + ); + + return + } + + if (config.version) { + process.stdout.write(cliConfig.version + '\n', noop$1); + + return + } + + // Modify `config` for watching. + if (config.watch) { + output = config.output; + + // Do not read from stdin(4). + config.streamIn = ttyStream; + + // Do not write to stdout(4). + config.out = false; + + process.stderr.write( + chalk.bold('Watching...') + ' (press CTRL+C to exit)\n', + noop$1 + ); + + // Prevent infinite loop if set to regeneration. + if (output === true) { + config.output = false; + + process.stderr.write( + chalk.yellow('Note') + ': Ignoring `--output` until exit.\n', + noop$1 + ); + } + } + + // Initial run. + lib$1(config, done); + + // Handle complete run. + function done(err, code, context) { + if (err) { + clean(); + fail$1(err); + } else { + exitStatus = code; + + if (config.watch && !watcher) { + subscribe(context); + } + } + } + + // Clean the watcher. + function clean() { + if (watcher) { + watcher.close(); + watcher = null; + } + } + + // Subscribe a chokidar watcher to all processed files. + function subscribe(context) { + watcher = chokidar + .watch(context.fileSet.origins, {cwd: config.cwd, ignoreInitial: true}) + .on('error', done) + .on('change', onchange); + + process.on('SIGINT', onsigint); + + function onchange(filePath) { + config.files = [filePath]; + + lib$1(config, done); + } + + function onsigint() { + // Hide the `^C` in terminal. + process.stderr.write('\n', noop$1); + + clean(); + + // Do another process if `output` specified regeneration. + if (output === true) { + config.output = output; + config.watch = false; + lib$1(config, done); + } + } + } +} + +// Print an error, optionally with stack. +function fail$1(err, pretty) { + var message = + (pretty ? String(err).trim() : err.stack) || + /* istanbul ignore next - Old versions of Node */ err; + + exitStatus = 1; + + process.stderr.write(message.trim() + '\n', noop$1); +} + +function onexit() { + /* eslint-disable unicorn/no-process-exit */ + process.exit(exitStatus); + /* eslint-enable unicorn/no-process-exit */ +} + +var unifiedArgs = lib$3; + +var markdownExtensions = [ + "md", + "markdown", + "mdown", + "mkdn", + "mkd", + "mdwn", + "mkdown", + "ron" +]; + +var markdownExtensions$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': markdownExtensions +}); + +var require$$0$1 = getCjsExportFromNamespace(markdownExtensions$1); + +var markdownExtensions$2 = require$$0$1; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray$1 = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +var extend$3 = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray$1(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray$1(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; + +var bail_1 = bail; + +function bail(err) { + if (err) { + throw err + } +} + +var isPlainObj = value => { + if (Object.prototype.toString.call(value) !== '[object Object]') { + return false; + } + + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; + +// Expose a frozen processor. +var unified_1 = unified().freeze(); + +var slice$3 = [].slice; +var own$2 = {}.hasOwnProperty; + +// Process pipeline. +var pipeline = trough_1() + .use(pipelineParse) + .use(pipelineRun) + .use(pipelineStringify); + +function pipelineParse(p, ctx) { + ctx.tree = p.parse(ctx.file); +} + +function pipelineRun(p, ctx, next) { + p.run(ctx.tree, ctx.file, done); + + function done(err, tree, file) { + if (err) { + next(err); + } else { + ctx.tree = tree; + ctx.file = file; + next(); + } + } +} + +function pipelineStringify(p, ctx) { + ctx.file.contents = p.stringify(ctx.tree, ctx.file); +} + +// Function to create the first processor. +function unified() { + var attachers = []; + var transformers = trough_1(); + var namespace = {}; + var frozen = false; + var freezeIndex = -1; + + // Data management. + processor.data = data; + + // Lock. + processor.freeze = freeze; + + // Plugins. + processor.attachers = attachers; + processor.use = use; + + // API. + processor.parse = parse; + processor.stringify = stringify; + processor.run = run; + processor.runSync = runSync; + processor.process = process; + processor.processSync = processSync; + + // Expose. + return processor + + // Create a new processor based on the processor in the current scope. + function processor() { + var destination = unified(); + var length = attachers.length; + var index = -1; + + while (++index < length) { + destination.use.apply(null, attachers[index]); + } + + destination.data(extend$3(true, {}, namespace)); + + return destination + } + + // Freeze: used to signal a processor that has finished configuration. + // + // For example, take unified itself: it’s frozen. + // Plugins should not be added to it. + // Rather, it should be extended, by invoking it, before modifying it. + // + // In essence, always invoke this when exporting a processor. + function freeze() { + var values; + var plugin; + var options; + var transformer; + + if (frozen) { + return processor + } + + while (++freezeIndex < attachers.length) { + values = attachers[freezeIndex]; + plugin = values[0]; + options = values[1]; + transformer = null; + + if (options === false) { + continue + } + + if (options === true) { + values[1] = undefined; + } + + transformer = plugin.apply(processor, values.slice(1)); + + if (typeof transformer === 'function') { + transformers.use(transformer); + } + } + + frozen = true; + freezeIndex = Infinity; + + return processor + } + + // Data management. + // Getter / setter for processor-specific informtion. + function data(key, value) { + if (typeof key === 'string') { + // Set `key`. + if (arguments.length === 2) { + assertUnfrozen('data', frozen); + + namespace[key] = value; + + return processor + } + + // Get `key`. + return (own$2.call(namespace, key) && namespace[key]) || null + } + + // Set space. + if (key) { + assertUnfrozen('data', frozen); + namespace = key; + return processor + } + + // Get space. + return namespace + } + + // Plugin management. + // + // Pass it: + // * an attacher and options, + // * a preset, + // * a list of presets, attachers, and arguments (list of attachers and + // options). + function use(value) { + var settings; + + assertUnfrozen('use', frozen); + + if (value === null || value === undefined) ; else if (typeof value === 'function') { + addPlugin.apply(null, arguments); + } else if (typeof value === 'object') { + if ('length' in value) { + addList(value); + } else { + addPreset(value); + } + } else { + throw new Error('Expected usable value, not `' + value + '`') + } + + if (settings) { + namespace.settings = extend$3(namespace.settings || {}, settings); + } + + return processor + + function addPreset(result) { + addList(result.plugins); + + if (result.settings) { + settings = extend$3(settings || {}, result.settings); + } + } + + function add(value) { + if (typeof value === 'function') { + addPlugin(value); + } else if (typeof value === 'object') { + if ('length' in value) { + addPlugin.apply(null, value); + } else { + addPreset(value); + } + } else { + throw new Error('Expected usable value, not `' + value + '`') + } + } + + function addList(plugins) { + var length; + var index; + + if (plugins === null || plugins === undefined) ; else if (typeof plugins === 'object' && 'length' in plugins) { + length = plugins.length; + index = -1; + + while (++index < length) { + add(plugins[index]); + } + } else { + throw new Error('Expected a list of plugins, not `' + plugins + '`') + } + } + + function addPlugin(plugin, value) { + var entry = find(plugin); + + if (entry) { + if (isPlainObj(entry[1]) && isPlainObj(value)) { + value = extend$3(entry[1], value); + } + + entry[1] = value; + } else { + attachers.push(slice$3.call(arguments)); + } + } + } + + function find(plugin) { + var length = attachers.length; + var index = -1; + var entry; + + while (++index < length) { + entry = attachers[index]; + + if (entry[0] === plugin) { + return entry + } + } + } + + // Parse a file (in string or vfile representation) into a unist node using + // the `Parser` on the processor. + function parse(doc) { + var file = vfile(doc); + var Parser; + + freeze(); + Parser = processor.Parser; + assertParser('parse', Parser); + + if (newable(Parser, 'parse')) { + return new Parser(String(file), file).parse() + } + + return Parser(String(file), file) // eslint-disable-line new-cap + } + + // Run transforms on a unist node representation of a file (in string or + // vfile representation), async. + function run(node, file, cb) { + assertNode(node); + freeze(); + + if (!cb && typeof file === 'function') { + cb = file; + file = null; + } + + if (!cb) { + return new Promise(executor) + } + + executor(null, cb); + + function executor(resolve, reject) { + transformers.run(node, vfile(file), done); + + function done(err, tree, file) { + tree = tree || node; + if (err) { + reject(err); + } else if (resolve) { + resolve(tree); + } else { + cb(null, tree, file); + } + } + } + } + + // Run transforms on a unist node representation of a file (in string or + // vfile representation), sync. + function runSync(node, file) { + var complete = false; + var result; + + run(node, file, done); + + assertDone('runSync', 'run', complete); + + return result + + function done(err, tree) { + complete = true; + bail_1(err); + result = tree; + } + } + + // Stringify a unist node representation of a file (in string or vfile + // representation) into a string using the `Compiler` on the processor. + function stringify(node, doc) { + var file = vfile(doc); + var Compiler; + + freeze(); + Compiler = processor.Compiler; + assertCompiler('stringify', Compiler); + assertNode(node); + + if (newable(Compiler, 'compile')) { + return new Compiler(node, file).compile() + } + + return Compiler(node, file) // eslint-disable-line new-cap + } + + // Parse a file (in string or vfile representation) into a unist node using + // the `Parser` on the processor, then run transforms on that node, and + // compile the resulting node using the `Compiler` on the processor, and + // store that result on the vfile. + function process(doc, cb) { + freeze(); + assertParser('process', processor.Parser); + assertCompiler('process', processor.Compiler); + + if (!cb) { + return new Promise(executor) + } + + executor(null, cb); + + function executor(resolve, reject) { + var file = vfile(doc); + + pipeline.run(processor, {file: file}, done); + + function done(err) { + if (err) { + reject(err); + } else if (resolve) { + resolve(file); + } else { + cb(null, file); + } + } + } + } + + // Process the given document (in string or vfile representation), sync. + function processSync(doc) { + var complete = false; + var file; + + freeze(); + assertParser('processSync', processor.Parser); + assertCompiler('processSync', processor.Compiler); + file = vfile(doc); + + process(file, done); + + assertDone('processSync', 'process', complete); + + return file + + function done(err) { + complete = true; + bail_1(err); + } + } +} + +// Check if `value` is a constructor. +function newable(value, name) { + return ( + typeof value === 'function' && + value.prototype && + // A function with keys in its prototype is probably a constructor. + // Classes’ prototype methods are not enumerable, so we check if some value + // exists in the prototype. + (keys(value.prototype) || name in value.prototype) + ) +} + +// Check if `value` is an object with keys. +function keys(value) { + var key; + for (key in value) { + return true + } + + return false +} + +// Assert a parser is available. +function assertParser(name, Parser) { + if (typeof Parser !== 'function') { + throw new Error('Cannot `' + name + '` without `Parser`') + } +} + +// Assert a compiler is available. +function assertCompiler(name, Compiler) { + if (typeof Compiler !== 'function') { + throw new Error('Cannot `' + name + '` without `Compiler`') + } +} + +// Assert the processor is not frozen. +function assertUnfrozen(name, frozen) { + if (frozen) { + throw new Error( + 'Cannot invoke `' + + name + + '` on a frozen processor.\nCreate a new processor first, by invoking it: use `processor()` instead of `processor`.' + ) + } +} + +// Assert `node` is a unist node. +function assertNode(node) { + if (!node || typeof node.type !== 'string') { + throw new Error('Expected node, got `' + node + '`') + } +} + +// Assert that `complete` is `true`. +function assertDone(name, asyncName, complete) { + if (!complete) { + throw new Error( + '`' + name + '` finished async. Use `' + asyncName + '` instead' + ) + } +} + +var unherit_1 = unherit; + +// Create a custom constructor which can be modified without affecting the +// original class. +function unherit(Super) { + var result; + var key; + var value; + + inherits(Of, Super); + inherits(From, Of); + + // Clone values. + result = Of.prototype; + + for (key in result) { + value = result[key]; + + if (value && typeof value === 'object') { + result[key] = 'concat' in value ? value.concat() : immutable(value); + } + } + + return Of + + // Constructor accepting a single argument, which itself is an `arguments` + // object. + function From(parameters) { + return Super.apply(this, parameters) + } + + // Constructor accepting variadic arguments. + function Of() { + if (!(this instanceof Of)) { + return new From(arguments) + } + + return Super.apply(this, arguments) + } +} + +var stateToggle = factory$1; + +// Construct a state `toggler`: a function which inverses `property` in context +// based on its current value. +// The by `toggler` returned function restores that value. +function factory$1(key, state, ctx) { + return enter + + function enter() { + var context = ctx || this; + var current = context[key]; + + context[key] = !state; + + return exit + + function exit() { + context[key] = current; + } + } +} + +var vfileLocation = factory$2; + +function factory$2(file) { + var contents = indices(String(file)); + + return { + toPosition: offsetToPositionFactory(contents), + toOffset: positionToOffsetFactory(contents) + } +} + +// Factory to get the line and column-based `position` for `offset` in the bound +// indices. +function offsetToPositionFactory(indices) { + return offsetToPosition + + // Get the line and column-based `position` for `offset` in the bound indices. + function offsetToPosition(offset) { + var index = -1; + var length = indices.length; + + if (offset < 0) { + return {} + } + + while (++index < length) { + if (indices[index] > offset) { + return { + line: index + 1, + column: offset - (indices[index - 1] || 0) + 1, + offset: offset + } + } + } + + return {} + } +} + +// Factory to get the `offset` for a line and column-based `position` in the +// bound indices. +function positionToOffsetFactory(indices) { + return positionToOffset + + // Get the `offset` for a line and column-based `position` in the bound + // indices. + function positionToOffset(position) { + var line = position && position.line; + var column = position && position.column; + + if (!isNaN(line) && !isNaN(column) && line - 1 in indices) { + return (indices[line - 2] || 0) + column - 1 || 0 + } + + return -1 + } +} + +// Get indices of line-breaks in `value`. +function indices(value) { + var result = []; + var index = value.indexOf('\n'); + + while (index !== -1) { + result.push(index + 1); + index = value.indexOf('\n', index + 1); + } + + result.push(value.length + 1); + + return result +} + +var _unescape = factory$3; + +var backslash$1 = '\\'; + +// Factory to de-escape a value, based on a list at `key` in `ctx`. +function factory$3(ctx, key) { + return unescape + + // De-escape a string using the expression at `key` in `ctx`. + function unescape(value) { + var prev = 0; + var index = value.indexOf(backslash$1); + var escape = ctx[key]; + var queue = []; + var character; + + while (index !== -1) { + queue.push(value.slice(prev, index)); + prev = index + 1; + character = value.charAt(prev); + + // If the following character is not a valid escape, add the slash. + if (!character || escape.indexOf(character) === -1) { + queue.push(backslash$1); + } + + index = value.indexOf(backslash$1, prev + 1); + } + + queue.push(value.slice(prev)); + + return queue.join('') + } +} + +const AElig = "Æ"; +const AMP = "&"; +const Aacute = "Á"; +const Acirc = "Â"; +const Agrave = "À"; +const Aring = "Å"; +const Atilde = "Ã"; +const Auml = "Ä"; +const COPY = "©"; +const Ccedil = "Ç"; +const ETH = "Ð"; +const Eacute = "É"; +const Ecirc = "Ê"; +const Egrave = "È"; +const Euml = "Ë"; +const GT = ">"; +const Iacute = "Í"; +const Icirc = "Î"; +const Igrave = "Ì"; +const Iuml = "Ï"; +const LT = "<"; +const Ntilde = "Ñ"; +const Oacute = "Ó"; +const Ocirc = "Ô"; +const Ograve = "Ò"; +const Oslash = "Ø"; +const Otilde = "Õ"; +const Ouml = "Ö"; +const QUOT = "\""; +const REG = "®"; +const THORN = "Þ"; +const Uacute = "Ú"; +const Ucirc = "Û"; +const Ugrave = "Ù"; +const Uuml = "Ü"; +const Yacute = "Ý"; +const aacute = "á"; +const acirc = "â"; +const acute = "´"; +const aelig = "æ"; +const agrave = "à"; +const amp = "&"; +const aring = "å"; +const atilde = "ã"; +const auml = "ä"; +const brvbar = "¦"; +const ccedil = "ç"; +const cedil = "¸"; +const cent = "¢"; +const copy$1 = "©"; +const curren = "¤"; +const deg = "°"; +const divide = "÷"; +const eacute = "é"; +const ecirc = "ê"; +const egrave = "è"; +const eth = "ð"; +const euml = "ë"; +const frac12 = "½"; +const frac14 = "¼"; +const frac34 = "¾"; +const gt = ">"; +const iacute = "í"; +const icirc = "î"; +const iexcl = "¡"; +const igrave = "ì"; +const iquest = "¿"; +const iuml = "ï"; +const laquo = "«"; +const lt = "<"; +const macr = "¯"; +const micro = "µ"; +const middot = "·"; +const nbsp = " "; +const not = "¬"; +const ntilde = "ñ"; +const oacute = "ó"; +const ocirc = "ô"; +const ograve = "ò"; +const ordf = "ª"; +const ordm = "º"; +const oslash = "ø"; +const otilde = "õ"; +const ouml = "ö"; +const para = "¶"; +const plusmn = "±"; +const pound = "£"; +const quot = "\""; +const raquo = "»"; +const reg = "®"; +const sect = "§"; +const shy = "­"; +const sup1 = "¹"; +const sup2 = "²"; +const sup3 = "³"; +const szlig = "ß"; +const thorn = "þ"; +const times = "×"; +const uacute = "ú"; +const ucirc = "û"; +const ugrave = "ù"; +const uml = "¨"; +const uuml = "ü"; +const yacute = "ý"; +const yen = "¥"; +const yuml = "ÿ"; +var index$1 = { + AElig: AElig, + AMP: AMP, + Aacute: Aacute, + Acirc: Acirc, + Agrave: Agrave, + Aring: Aring, + Atilde: Atilde, + Auml: Auml, + COPY: COPY, + Ccedil: Ccedil, + ETH: ETH, + Eacute: Eacute, + Ecirc: Ecirc, + Egrave: Egrave, + Euml: Euml, + GT: GT, + Iacute: Iacute, + Icirc: Icirc, + Igrave: Igrave, + Iuml: Iuml, + LT: LT, + Ntilde: Ntilde, + Oacute: Oacute, + Ocirc: Ocirc, + Ograve: Ograve, + Oslash: Oslash, + Otilde: Otilde, + Ouml: Ouml, + QUOT: QUOT, + REG: REG, + THORN: THORN, + Uacute: Uacute, + Ucirc: Ucirc, + Ugrave: Ugrave, + Uuml: Uuml, + Yacute: Yacute, + aacute: aacute, + acirc: acirc, + acute: acute, + aelig: aelig, + agrave: agrave, + amp: amp, + aring: aring, + atilde: atilde, + auml: auml, + brvbar: brvbar, + ccedil: ccedil, + cedil: cedil, + cent: cent, + copy: copy$1, + curren: curren, + deg: deg, + divide: divide, + eacute: eacute, + ecirc: ecirc, + egrave: egrave, + eth: eth, + euml: euml, + frac12: frac12, + frac14: frac14, + frac34: frac34, + gt: gt, + iacute: iacute, + icirc: icirc, + iexcl: iexcl, + igrave: igrave, + iquest: iquest, + iuml: iuml, + laquo: laquo, + lt: lt, + macr: macr, + micro: micro, + middot: middot, + nbsp: nbsp, + not: not, + ntilde: ntilde, + oacute: oacute, + ocirc: ocirc, + ograve: ograve, + ordf: ordf, + ordm: ordm, + oslash: oslash, + otilde: otilde, + ouml: ouml, + para: para, + plusmn: plusmn, + pound: pound, + quot: quot, + raquo: raquo, + reg: reg, + sect: sect, + shy: shy, + sup1: sup1, + sup2: sup2, + sup3: sup3, + szlig: szlig, + thorn: thorn, + times: times, + uacute: uacute, + ucirc: ucirc, + ugrave: ugrave, + uml: uml, + uuml: uuml, + yacute: yacute, + yen: yen, + yuml: yuml +}; + +var characterEntitiesLegacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + AElig: AElig, + AMP: AMP, + Aacute: Aacute, + Acirc: Acirc, + Agrave: Agrave, + Aring: Aring, + Atilde: Atilde, + Auml: Auml, + COPY: COPY, + Ccedil: Ccedil, + ETH: ETH, + Eacute: Eacute, + Ecirc: Ecirc, + Egrave: Egrave, + Euml: Euml, + GT: GT, + Iacute: Iacute, + Icirc: Icirc, + Igrave: Igrave, + Iuml: Iuml, + LT: LT, + Ntilde: Ntilde, + Oacute: Oacute, + Ocirc: Ocirc, + Ograve: Ograve, + Oslash: Oslash, + Otilde: Otilde, + Ouml: Ouml, + QUOT: QUOT, + REG: REG, + THORN: THORN, + Uacute: Uacute, + Ucirc: Ucirc, + Ugrave: Ugrave, + Uuml: Uuml, + Yacute: Yacute, + aacute: aacute, + acirc: acirc, + acute: acute, + aelig: aelig, + agrave: agrave, + amp: amp, + aring: aring, + atilde: atilde, + auml: auml, + brvbar: brvbar, + ccedil: ccedil, + cedil: cedil, + cent: cent, + copy: copy$1, + curren: curren, + deg: deg, + divide: divide, + eacute: eacute, + ecirc: ecirc, + egrave: egrave, + eth: eth, + euml: euml, + frac12: frac12, + frac14: frac14, + frac34: frac34, + gt: gt, + iacute: iacute, + icirc: icirc, + iexcl: iexcl, + igrave: igrave, + iquest: iquest, + iuml: iuml, + laquo: laquo, + lt: lt, + macr: macr, + micro: micro, + middot: middot, + nbsp: nbsp, + not: not, + ntilde: ntilde, + oacute: oacute, + ocirc: ocirc, + ograve: ograve, + ordf: ordf, + ordm: ordm, + oslash: oslash, + otilde: otilde, + ouml: ouml, + para: para, + plusmn: plusmn, + pound: pound, + quot: quot, + raquo: raquo, + reg: reg, + sect: sect, + shy: shy, + sup1: sup1, + sup2: sup2, + sup3: sup3, + szlig: szlig, + thorn: thorn, + times: times, + uacute: uacute, + ucirc: ucirc, + ugrave: ugrave, + uml: uml, + uuml: uuml, + yacute: yacute, + yen: yen, + yuml: yuml, + 'default': index$1 +}); + +var index$2 = { + "0": "�", + "128": "€", + "130": "‚", + "131": "ƒ", + "132": "„", + "133": "…", + "134": "†", + "135": "‡", + "136": "ˆ", + "137": "‰", + "138": "Š", + "139": "‹", + "140": "Œ", + "142": "Ž", + "145": "‘", + "146": "’", + "147": "“", + "148": "”", + "149": "•", + "150": "–", + "151": "—", + "152": "˜", + "153": "™", + "154": "š", + "155": "›", + "156": "œ", + "158": "ž", + "159": "Ÿ" +}; + +var characterReferenceInvalid = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': index$2 +}); + +var isDecimal = decimal; + +// Check if the given character code, or the character code at the first +// character, is decimal. +function decimal(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return code >= 48 && code <= 57 /* 0-9 */ +} + +var isHexadecimal = hexadecimal; + +// Check if the given character code, or the character code at the first +// character, is hexadecimal. +function hexadecimal(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return ( + (code >= 97 /* a */ && code <= 102) /* z */ || + (code >= 65 /* A */ && code <= 70) /* Z */ || + (code >= 48 /* A */ && code <= 57) /* Z */ + ) +} + +var isAlphabetical = alphabetical; + +// Check if the given character code, or the character code at the first +// character, is alphabetical. +function alphabetical(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return ( + (code >= 97 && code <= 122) /* a-z */ || + (code >= 65 && code <= 90) /* A-Z */ + ) +} + +var isAlphanumerical = alphanumerical; + +// Check if the given character code, or the character code at the first +// character, is alphanumerical. +function alphanumerical(character) { + return isAlphabetical(character) || isDecimal(character) +} + +const AEli = "Æ"; +const AElig$1 = "Æ"; +const AM = "&"; +const AMP$1 = "&"; +const Aacut = "Á"; +const Aacute$1 = "Á"; +const Abreve = "Ă"; +const Acir = "Â"; +const Acirc$1 = "Â"; +const Acy = "А"; +const Afr = "𝔄"; +const Agrav = "À"; +const Agrave$1 = "À"; +const Alpha = "Α"; +const Amacr = "Ā"; +const And = "⩓"; +const Aogon = "Ą"; +const Aopf = "𝔸"; +const ApplyFunction = "⁡"; +const Arin = "Å"; +const Aring$1 = "Å"; +const Ascr = "𝒜"; +const Assign = "≔"; +const Atild = "Ã"; +const Atilde$1 = "Ã"; +const Aum = "Ä"; +const Auml$1 = "Ä"; +const Backslash = "∖"; +const Barv = "⫧"; +const Barwed = "⌆"; +const Bcy = "Б"; +const Because = "∵"; +const Bernoullis = "ℬ"; +const Beta = "Β"; +const Bfr = "𝔅"; +const Bopf = "𝔹"; +const Breve = "˘"; +const Bscr = "ℬ"; +const Bumpeq = "≎"; +const CHcy = "Ч"; +const COP = "©"; +const COPY$1 = "©"; +const Cacute = "Ć"; +const Cap = "⋒"; +const CapitalDifferentialD = "ⅅ"; +const Cayleys = "ℭ"; +const Ccaron = "Č"; +const Ccedi = "Ç"; +const Ccedil$1 = "Ç"; +const Ccirc = "Ĉ"; +const Cconint = "∰"; +const Cdot = "Ċ"; +const Cedilla = "¸"; +const CenterDot = "·"; +const Cfr = "ℭ"; +const Chi = "Χ"; +const CircleDot = "⊙"; +const CircleMinus = "⊖"; +const CirclePlus = "⊕"; +const CircleTimes = "⊗"; +const ClockwiseContourIntegral = "∲"; +const CloseCurlyDoubleQuote = "”"; +const CloseCurlyQuote = "’"; +const Colon = "∷"; +const Colone = "⩴"; +const Congruent = "≡"; +const Conint = "∯"; +const ContourIntegral = "∮"; +const Copf = "ℂ"; +const Coproduct = "∐"; +const CounterClockwiseContourIntegral = "∳"; +const Cross = "⨯"; +const Cscr = "𝒞"; +const Cup = "⋓"; +const CupCap = "≍"; +const DD = "ⅅ"; +const DDotrahd = "⤑"; +const DJcy = "Ђ"; +const DScy = "Ѕ"; +const DZcy = "Џ"; +const Dagger = "‡"; +const Darr = "↡"; +const Dashv = "⫤"; +const Dcaron = "Ď"; +const Dcy = "Д"; +const Del = "∇"; +const Delta = "Δ"; +const Dfr = "𝔇"; +const DiacriticalAcute = "´"; +const DiacriticalDot = "˙"; +const DiacriticalDoubleAcute = "˝"; +const DiacriticalGrave = "`"; +const DiacriticalTilde = "˜"; +const Diamond = "⋄"; +const DifferentialD = "ⅆ"; +const Dopf = "𝔻"; +const Dot = "¨"; +const DotDot = "⃜"; +const DotEqual = "≐"; +const DoubleContourIntegral = "∯"; +const DoubleDot = "¨"; +const DoubleDownArrow = "⇓"; +const DoubleLeftArrow = "⇐"; +const DoubleLeftRightArrow = "⇔"; +const DoubleLeftTee = "⫤"; +const DoubleLongLeftArrow = "⟸"; +const DoubleLongLeftRightArrow = "⟺"; +const DoubleLongRightArrow = "⟹"; +const DoubleRightArrow = "⇒"; +const DoubleRightTee = "⊨"; +const DoubleUpArrow = "⇑"; +const DoubleUpDownArrow = "⇕"; +const DoubleVerticalBar = "∥"; +const DownArrow = "↓"; +const DownArrowBar = "⤓"; +const DownArrowUpArrow = "⇵"; +const DownBreve = "̑"; +const DownLeftRightVector = "⥐"; +const DownLeftTeeVector = "⥞"; +const DownLeftVector = "↽"; +const DownLeftVectorBar = "⥖"; +const DownRightTeeVector = "⥟"; +const DownRightVector = "⇁"; +const DownRightVectorBar = "⥗"; +const DownTee = "⊤"; +const DownTeeArrow = "↧"; +const Downarrow = "⇓"; +const Dscr = "𝒟"; +const Dstrok = "Đ"; +const ENG = "Ŋ"; +const ET = "Ð"; +const ETH$1 = "Ð"; +const Eacut = "É"; +const Eacute$1 = "É"; +const Ecaron = "Ě"; +const Ecir = "Ê"; +const Ecirc$1 = "Ê"; +const Ecy = "Э"; +const Edot = "Ė"; +const Efr = "𝔈"; +const Egrav = "È"; +const Egrave$1 = "È"; +const Element = "∈"; +const Emacr = "Ē"; +const EmptySmallSquare = "◻"; +const EmptyVerySmallSquare = "▫"; +const Eogon = "Ę"; +const Eopf = "𝔼"; +const Epsilon = "Ε"; +const Equal = "⩵"; +const EqualTilde = "≂"; +const Equilibrium = "⇌"; +const Escr = "ℰ"; +const Esim = "⩳"; +const Eta = "Η"; +const Eum = "Ë"; +const Euml$1 = "Ë"; +const Exists = "∃"; +const ExponentialE = "ⅇ"; +const Fcy = "Ф"; +const Ffr = "𝔉"; +const FilledSmallSquare = "◼"; +const FilledVerySmallSquare = "▪"; +const Fopf = "𝔽"; +const ForAll = "∀"; +const Fouriertrf = "ℱ"; +const Fscr = "ℱ"; +const GJcy = "Ѓ"; +const G = ">"; +const GT$1 = ">"; +const Gamma = "Γ"; +const Gammad = "Ϝ"; +const Gbreve = "Ğ"; +const Gcedil = "Ģ"; +const Gcirc = "Ĝ"; +const Gcy = "Г"; +const Gdot = "Ġ"; +const Gfr = "𝔊"; +const Gg = "⋙"; +const Gopf = "𝔾"; +const GreaterEqual = "≥"; +const GreaterEqualLess = "⋛"; +const GreaterFullEqual = "≧"; +const GreaterGreater = "⪢"; +const GreaterLess = "≷"; +const GreaterSlantEqual = "⩾"; +const GreaterTilde = "≳"; +const Gscr = "𝒢"; +const Gt = "≫"; +const HARDcy = "Ъ"; +const Hacek = "ˇ"; +const Hat = "^"; +const Hcirc = "Ĥ"; +const Hfr = "ℌ"; +const HilbertSpace = "ℋ"; +const Hopf = "ℍ"; +const HorizontalLine = "─"; +const Hscr = "ℋ"; +const Hstrok = "Ħ"; +const HumpDownHump = "≎"; +const HumpEqual = "≏"; +const IEcy = "Е"; +const IJlig = "IJ"; +const IOcy = "Ё"; +const Iacut = "Í"; +const Iacute$1 = "Í"; +const Icir = "Î"; +const Icirc$1 = "Î"; +const Icy = "И"; +const Idot = "İ"; +const Ifr = "ℑ"; +const Igrav = "Ì"; +const Igrave$1 = "Ì"; +const Im = "ℑ"; +const Imacr = "Ī"; +const ImaginaryI = "ⅈ"; +const Implies = "⇒"; +const Int = "∬"; +const Integral = "∫"; +const Intersection = "⋂"; +const InvisibleComma = "⁣"; +const InvisibleTimes = "⁢"; +const Iogon = "Į"; +const Iopf = "𝕀"; +const Iota = "Ι"; +const Iscr = "ℐ"; +const Itilde = "Ĩ"; +const Iukcy = "І"; +const Ium = "Ï"; +const Iuml$1 = "Ï"; +const Jcirc = "Ĵ"; +const Jcy = "Й"; +const Jfr = "𝔍"; +const Jopf = "𝕁"; +const Jscr = "𝒥"; +const Jsercy = "Ј"; +const Jukcy = "Є"; +const KHcy = "Х"; +const KJcy = "Ќ"; +const Kappa = "Κ"; +const Kcedil = "Ķ"; +const Kcy = "К"; +const Kfr = "𝔎"; +const Kopf = "𝕂"; +const Kscr = "𝒦"; +const LJcy = "Љ"; +const L = "<"; +const LT$1 = "<"; +const Lacute = "Ĺ"; +const Lambda = "Λ"; +const Lang = "⟪"; +const Laplacetrf = "ℒ"; +const Larr = "↞"; +const Lcaron = "Ľ"; +const Lcedil = "Ļ"; +const Lcy = "Л"; +const LeftAngleBracket = "⟨"; +const LeftArrow = "←"; +const LeftArrowBar = "⇤"; +const LeftArrowRightArrow = "⇆"; +const LeftCeiling = "⌈"; +const LeftDoubleBracket = "⟦"; +const LeftDownTeeVector = "⥡"; +const LeftDownVector = "⇃"; +const LeftDownVectorBar = "⥙"; +const LeftFloor = "⌊"; +const LeftRightArrow = "↔"; +const LeftRightVector = "⥎"; +const LeftTee = "⊣"; +const LeftTeeArrow = "↤"; +const LeftTeeVector = "⥚"; +const LeftTriangle = "⊲"; +const LeftTriangleBar = "⧏"; +const LeftTriangleEqual = "⊴"; +const LeftUpDownVector = "⥑"; +const LeftUpTeeVector = "⥠"; +const LeftUpVector = "↿"; +const LeftUpVectorBar = "⥘"; +const LeftVector = "↼"; +const LeftVectorBar = "⥒"; +const Leftarrow = "⇐"; +const Leftrightarrow = "⇔"; +const LessEqualGreater = "⋚"; +const LessFullEqual = "≦"; +const LessGreater = "≶"; +const LessLess = "⪡"; +const LessSlantEqual = "⩽"; +const LessTilde = "≲"; +const Lfr = "𝔏"; +const Ll = "⋘"; +const Lleftarrow = "⇚"; +const Lmidot = "Ŀ"; +const LongLeftArrow = "⟵"; +const LongLeftRightArrow = "⟷"; +const LongRightArrow = "⟶"; +const Longleftarrow = "⟸"; +const Longleftrightarrow = "⟺"; +const Longrightarrow = "⟹"; +const Lopf = "𝕃"; +const LowerLeftArrow = "↙"; +const LowerRightArrow = "↘"; +const Lscr = "ℒ"; +const Lsh = "↰"; +const Lstrok = "Ł"; +const Lt = "≪"; +const Mcy = "М"; +const MediumSpace = " "; +const Mellintrf = "ℳ"; +const Mfr = "𝔐"; +const MinusPlus = "∓"; +const Mopf = "𝕄"; +const Mscr = "ℳ"; +const Mu = "Μ"; +const NJcy = "Њ"; +const Nacute = "Ń"; +const Ncaron = "Ň"; +const Ncedil = "Ņ"; +const Ncy = "Н"; +const NegativeMediumSpace = "​"; +const NegativeThickSpace = "​"; +const NegativeThinSpace = "​"; +const NegativeVeryThinSpace = "​"; +const NestedGreaterGreater = "≫"; +const NestedLessLess = "≪"; +const NewLine = "\n"; +const Nfr = "𝔑"; +const NoBreak = "⁠"; +const NonBreakingSpace = " "; +const Nopf = "ℕ"; +const Not = "⫬"; +const NotCongruent = "≢"; +const NotCupCap = "≭"; +const NotDoubleVerticalBar = "∦"; +const NotElement = "∉"; +const NotEqual = "≠"; +const NotEqualTilde = "≂̸"; +const NotExists = "∄"; +const NotGreater = "≯"; +const NotGreaterEqual = "≱"; +const NotGreaterFullEqual = "≧̸"; +const NotGreaterGreater = "≫̸"; +const NotGreaterLess = "≹"; +const NotGreaterSlantEqual = "⩾̸"; +const NotGreaterTilde = "≵"; +const NotHumpDownHump = "≎̸"; +const NotHumpEqual = "≏̸"; +const NotLeftTriangle = "⋪"; +const NotLeftTriangleBar = "⧏̸"; +const NotLeftTriangleEqual = "⋬"; +const NotLess = "≮"; +const NotLessEqual = "≰"; +const NotLessGreater = "≸"; +const NotLessLess = "≪̸"; +const NotLessSlantEqual = "⩽̸"; +const NotLessTilde = "≴"; +const NotNestedGreaterGreater = "⪢̸"; +const NotNestedLessLess = "⪡̸"; +const NotPrecedes = "⊀"; +const NotPrecedesEqual = "⪯̸"; +const NotPrecedesSlantEqual = "⋠"; +const NotReverseElement = "∌"; +const NotRightTriangle = "⋫"; +const NotRightTriangleBar = "⧐̸"; +const NotRightTriangleEqual = "⋭"; +const NotSquareSubset = "⊏̸"; +const NotSquareSubsetEqual = "⋢"; +const NotSquareSuperset = "⊐̸"; +const NotSquareSupersetEqual = "⋣"; +const NotSubset = "⊂⃒"; +const NotSubsetEqual = "⊈"; +const NotSucceeds = "⊁"; +const NotSucceedsEqual = "⪰̸"; +const NotSucceedsSlantEqual = "⋡"; +const NotSucceedsTilde = "≿̸"; +const NotSuperset = "⊃⃒"; +const NotSupersetEqual = "⊉"; +const NotTilde = "≁"; +const NotTildeEqual = "≄"; +const NotTildeFullEqual = "≇"; +const NotTildeTilde = "≉"; +const NotVerticalBar = "∤"; +const Nscr = "𝒩"; +const Ntild = "Ñ"; +const Ntilde$1 = "Ñ"; +const Nu = "Ν"; +const OElig = "Œ"; +const Oacut = "Ó"; +const Oacute$1 = "Ó"; +const Ocir = "Ô"; +const Ocirc$1 = "Ô"; +const Ocy = "О"; +const Odblac = "Ő"; +const Ofr = "𝔒"; +const Ograv = "Ò"; +const Ograve$1 = "Ò"; +const Omacr = "Ō"; +const Omega = "Ω"; +const Omicron = "Ο"; +const Oopf = "𝕆"; +const OpenCurlyDoubleQuote = "“"; +const OpenCurlyQuote = "‘"; +const Or = "⩔"; +const Oscr = "𝒪"; +const Oslas = "Ø"; +const Oslash$1 = "Ø"; +const Otild = "Õ"; +const Otilde$1 = "Õ"; +const Otimes = "⨷"; +const Oum = "Ö"; +const Ouml$1 = "Ö"; +const OverBar = "‾"; +const OverBrace = "⏞"; +const OverBracket = "⎴"; +const OverParenthesis = "⏜"; +const PartialD = "∂"; +const Pcy = "П"; +const Pfr = "𝔓"; +const Phi = "Φ"; +const Pi = "Π"; +const PlusMinus = "±"; +const Poincareplane = "ℌ"; +const Popf = "ℙ"; +const Pr = "⪻"; +const Precedes = "≺"; +const PrecedesEqual = "⪯"; +const PrecedesSlantEqual = "≼"; +const PrecedesTilde = "≾"; +const Prime = "″"; +const Product = "∏"; +const Proportion = "∷"; +const Proportional = "∝"; +const Pscr = "𝒫"; +const Psi = "Ψ"; +const QUO = "\""; +const QUOT$1 = "\""; +const Qfr = "𝔔"; +const Qopf = "ℚ"; +const Qscr = "𝒬"; +const RBarr = "⤐"; +const RE = "®"; +const REG$1 = "®"; +const Racute = "Ŕ"; +const Rang = "⟫"; +const Rarr = "↠"; +const Rarrtl = "⤖"; +const Rcaron = "Ř"; +const Rcedil = "Ŗ"; +const Rcy = "Р"; +const Re = "ℜ"; +const ReverseElement = "∋"; +const ReverseEquilibrium = "⇋"; +const ReverseUpEquilibrium = "⥯"; +const Rfr = "ℜ"; +const Rho = "Ρ"; +const RightAngleBracket = "⟩"; +const RightArrow = "→"; +const RightArrowBar = "⇥"; +const RightArrowLeftArrow = "⇄"; +const RightCeiling = "⌉"; +const RightDoubleBracket = "⟧"; +const RightDownTeeVector = "⥝"; +const RightDownVector = "⇂"; +const RightDownVectorBar = "⥕"; +const RightFloor = "⌋"; +const RightTee = "⊢"; +const RightTeeArrow = "↦"; +const RightTeeVector = "⥛"; +const RightTriangle = "⊳"; +const RightTriangleBar = "⧐"; +const RightTriangleEqual = "⊵"; +const RightUpDownVector = "⥏"; +const RightUpTeeVector = "⥜"; +const RightUpVector = "↾"; +const RightUpVectorBar = "⥔"; +const RightVector = "⇀"; +const RightVectorBar = "⥓"; +const Rightarrow = "⇒"; +const Ropf = "ℝ"; +const RoundImplies = "⥰"; +const Rrightarrow = "⇛"; +const Rscr = "ℛ"; +const Rsh = "↱"; +const RuleDelayed = "⧴"; +const SHCHcy = "Щ"; +const SHcy = "Ш"; +const SOFTcy = "Ь"; +const Sacute = "Ś"; +const Sc = "⪼"; +const Scaron = "Š"; +const Scedil = "Ş"; +const Scirc = "Ŝ"; +const Scy = "С"; +const Sfr = "𝔖"; +const ShortDownArrow = "↓"; +const ShortLeftArrow = "←"; +const ShortRightArrow = "→"; +const ShortUpArrow = "↑"; +const Sigma = "Σ"; +const SmallCircle = "∘"; +const Sopf = "𝕊"; +const Sqrt = "√"; +const Square = "□"; +const SquareIntersection = "⊓"; +const SquareSubset = "⊏"; +const SquareSubsetEqual = "⊑"; +const SquareSuperset = "⊐"; +const SquareSupersetEqual = "⊒"; +const SquareUnion = "⊔"; +const Sscr = "𝒮"; +const Star = "⋆"; +const Sub = "⋐"; +const Subset = "⋐"; +const SubsetEqual = "⊆"; +const Succeeds = "≻"; +const SucceedsEqual = "⪰"; +const SucceedsSlantEqual = "≽"; +const SucceedsTilde = "≿"; +const SuchThat = "∋"; +const Sum = "∑"; +const Sup = "⋑"; +const Superset = "⊃"; +const SupersetEqual = "⊇"; +const Supset = "⋑"; +const THOR = "Þ"; +const THORN$1 = "Þ"; +const TRADE = "™"; +const TSHcy = "Ћ"; +const TScy = "Ц"; +const Tab = "\t"; +const Tau = "Τ"; +const Tcaron = "Ť"; +const Tcedil = "Ţ"; +const Tcy = "Т"; +const Tfr = "𝔗"; +const Therefore = "∴"; +const Theta = "Θ"; +const ThickSpace = "  "; +const ThinSpace = " "; +const Tilde = "∼"; +const TildeEqual = "≃"; +const TildeFullEqual = "≅"; +const TildeTilde = "≈"; +const Topf = "𝕋"; +const TripleDot = "⃛"; +const Tscr = "𝒯"; +const Tstrok = "Ŧ"; +const Uacut = "Ú"; +const Uacute$1 = "Ú"; +const Uarr = "↟"; +const Uarrocir = "⥉"; +const Ubrcy = "Ў"; +const Ubreve = "Ŭ"; +const Ucir = "Û"; +const Ucirc$1 = "Û"; +const Ucy = "У"; +const Udblac = "Ű"; +const Ufr = "𝔘"; +const Ugrav = "Ù"; +const Ugrave$1 = "Ù"; +const Umacr = "Ū"; +const UnderBar = "_"; +const UnderBrace = "⏟"; +const UnderBracket = "⎵"; +const UnderParenthesis = "⏝"; +const Union = "⋃"; +const UnionPlus = "⊎"; +const Uogon = "Ų"; +const Uopf = "𝕌"; +const UpArrow = "↑"; +const UpArrowBar = "⤒"; +const UpArrowDownArrow = "⇅"; +const UpDownArrow = "↕"; +const UpEquilibrium = "⥮"; +const UpTee = "⊥"; +const UpTeeArrow = "↥"; +const Uparrow = "⇑"; +const Updownarrow = "⇕"; +const UpperLeftArrow = "↖"; +const UpperRightArrow = "↗"; +const Upsi = "ϒ"; +const Upsilon = "Υ"; +const Uring = "Ů"; +const Uscr = "𝒰"; +const Utilde = "Ũ"; +const Uum = "Ü"; +const Uuml$1 = "Ü"; +const VDash = "⊫"; +const Vbar = "⫫"; +const Vcy = "В"; +const Vdash = "⊩"; +const Vdashl = "⫦"; +const Vee = "⋁"; +const Verbar = "‖"; +const Vert = "‖"; +const VerticalBar = "∣"; +const VerticalLine = "|"; +const VerticalSeparator = "❘"; +const VerticalTilde = "≀"; +const VeryThinSpace = " "; +const Vfr = "𝔙"; +const Vopf = "𝕍"; +const Vscr = "𝒱"; +const Vvdash = "⊪"; +const Wcirc = "Ŵ"; +const Wedge = "⋀"; +const Wfr = "𝔚"; +const Wopf = "𝕎"; +const Wscr = "𝒲"; +const Xfr = "𝔛"; +const Xi = "Ξ"; +const Xopf = "𝕏"; +const Xscr = "𝒳"; +const YAcy = "Я"; +const YIcy = "Ї"; +const YUcy = "Ю"; +const Yacut = "Ý"; +const Yacute$1 = "Ý"; +const Ycirc = "Ŷ"; +const Ycy = "Ы"; +const Yfr = "𝔜"; +const Yopf = "𝕐"; +const Yscr = "𝒴"; +const Yuml = "Ÿ"; +const ZHcy = "Ж"; +const Zacute = "Ź"; +const Zcaron = "Ž"; +const Zcy = "З"; +const Zdot = "Ż"; +const ZeroWidthSpace = "​"; +const Zeta = "Ζ"; +const Zfr = "ℨ"; +const Zopf = "ℤ"; +const Zscr = "𝒵"; +const aacut = "á"; +const aacute$1 = "á"; +const abreve = "ă"; +const ac = "∾"; +const acE = "∾̳"; +const acd = "∿"; +const acir = "â"; +const acirc$1 = "â"; +const acut = "´"; +const acute$1 = "´"; +const acy = "а"; +const aeli = "æ"; +const aelig$1 = "æ"; +const af = "⁡"; +const afr = "𝔞"; +const agrav = "à"; +const agrave$1 = "à"; +const alefsym = "ℵ"; +const aleph = "ℵ"; +const alpha = "α"; +const amacr = "ā"; +const amalg = "⨿"; +const am = "&"; +const amp$1 = "&"; +const and = "∧"; +const andand = "⩕"; +const andd = "⩜"; +const andslope = "⩘"; +const andv = "⩚"; +const ang = "∠"; +const ange = "⦤"; +const angle = "∠"; +const angmsd = "∡"; +const angmsdaa = "⦨"; +const angmsdab = "⦩"; +const angmsdac = "⦪"; +const angmsdad = "⦫"; +const angmsdae = "⦬"; +const angmsdaf = "⦭"; +const angmsdag = "⦮"; +const angmsdah = "⦯"; +const angrt = "∟"; +const angrtvb = "⊾"; +const angrtvbd = "⦝"; +const angsph = "∢"; +const angst = "Å"; +const angzarr = "⍼"; +const aogon = "ą"; +const aopf = "𝕒"; +const ap = "≈"; +const apE = "⩰"; +const apacir = "⩯"; +const ape = "≊"; +const apid = "≋"; +const apos = "'"; +const approx = "≈"; +const approxeq = "≊"; +const arin = "å"; +const aring$1 = "å"; +const ascr = "𝒶"; +const ast = "*"; +const asymp = "≈"; +const asympeq = "≍"; +const atild = "ã"; +const atilde$1 = "ã"; +const aum = "ä"; +const auml$1 = "ä"; +const awconint = "∳"; +const awint = "⨑"; +const bNot = "⫭"; +const backcong = "≌"; +const backepsilon = "϶"; +const backprime = "‵"; +const backsim = "∽"; +const backsimeq = "⋍"; +const barvee = "⊽"; +const barwed = "⌅"; +const barwedge = "⌅"; +const bbrk = "⎵"; +const bbrktbrk = "⎶"; +const bcong = "≌"; +const bcy = "б"; +const bdquo = "„"; +const becaus = "∵"; +const because = "∵"; +const bemptyv = "⦰"; +const bepsi = "϶"; +const bernou = "ℬ"; +const beta = "β"; +const beth = "ℶ"; +const between = "≬"; +const bfr = "𝔟"; +const bigcap = "⋂"; +const bigcirc = "◯"; +const bigcup = "⋃"; +const bigodot = "⨀"; +const bigoplus = "⨁"; +const bigotimes = "⨂"; +const bigsqcup = "⨆"; +const bigstar = "★"; +const bigtriangledown = "▽"; +const bigtriangleup = "△"; +const biguplus = "⨄"; +const bigvee = "⋁"; +const bigwedge = "⋀"; +const bkarow = "⤍"; +const blacklozenge = "⧫"; +const blacksquare = "▪"; +const blacktriangle = "▴"; +const blacktriangledown = "▾"; +const blacktriangleleft = "◂"; +const blacktriangleright = "▸"; +const blank = "␣"; +const blk12 = "▒"; +const blk14 = "░"; +const blk34 = "▓"; +const block = "█"; +const bne = "=⃥"; +const bnequiv = "≡⃥"; +const bnot = "⌐"; +const bopf = "𝕓"; +const bot = "⊥"; +const bottom = "⊥"; +const bowtie = "⋈"; +const boxDL = "╗"; +const boxDR = "╔"; +const boxDl = "╖"; +const boxDr = "╓"; +const boxH = "═"; +const boxHD = "╦"; +const boxHU = "╩"; +const boxHd = "╤"; +const boxHu = "╧"; +const boxUL = "╝"; +const boxUR = "╚"; +const boxUl = "╜"; +const boxUr = "╙"; +const boxV = "║"; +const boxVH = "╬"; +const boxVL = "╣"; +const boxVR = "╠"; +const boxVh = "╫"; +const boxVl = "╢"; +const boxVr = "╟"; +const boxbox = "⧉"; +const boxdL = "╕"; +const boxdR = "╒"; +const boxdl = "┐"; +const boxdr = "┌"; +const boxh = "─"; +const boxhD = "╥"; +const boxhU = "╨"; +const boxhd = "┬"; +const boxhu = "┴"; +const boxminus = "⊟"; +const boxplus = "⊞"; +const boxtimes = "⊠"; +const boxuL = "╛"; +const boxuR = "╘"; +const boxul = "┘"; +const boxur = "└"; +const boxv = "│"; +const boxvH = "╪"; +const boxvL = "╡"; +const boxvR = "╞"; +const boxvh = "┼"; +const boxvl = "┤"; +const boxvr = "├"; +const bprime = "‵"; +const breve = "˘"; +const brvba = "¦"; +const brvbar$1 = "¦"; +const bscr = "𝒷"; +const bsemi = "⁏"; +const bsim = "∽"; +const bsime = "⋍"; +const bsol = "\\"; +const bsolb = "⧅"; +const bsolhsub = "⟈"; +const bull = "•"; +const bullet = "•"; +const bump = "≎"; +const bumpE = "⪮"; +const bumpe = "≏"; +const bumpeq = "≏"; +const cacute = "ć"; +const cap = "∩"; +const capand = "⩄"; +const capbrcup = "⩉"; +const capcap = "⩋"; +const capcup = "⩇"; +const capdot = "⩀"; +const caps = "∩︀"; +const caret = "⁁"; +const caron = "ˇ"; +const ccaps = "⩍"; +const ccaron = "č"; +const ccedi = "ç"; +const ccedil$1 = "ç"; +const ccirc = "ĉ"; +const ccups = "⩌"; +const ccupssm = "⩐"; +const cdot = "ċ"; +const cedi = "¸"; +const cedil$1 = "¸"; +const cemptyv = "⦲"; +const cen = "¢"; +const cent$1 = "¢"; +const centerdot = "·"; +const cfr = "𝔠"; +const chcy = "ч"; +const check$2 = "✓"; +const checkmark = "✓"; +const chi = "χ"; +const cir = "○"; +const cirE = "⧃"; +const circ = "ˆ"; +const circeq = "≗"; +const circlearrowleft = "↺"; +const circlearrowright = "↻"; +const circledR = "®"; +const circledS = "Ⓢ"; +const circledast = "⊛"; +const circledcirc = "⊚"; +const circleddash = "⊝"; +const cire = "≗"; +const cirfnint = "⨐"; +const cirmid = "⫯"; +const cirscir = "⧂"; +const clubs = "♣"; +const clubsuit = "♣"; +const colon = ":"; +const colone = "≔"; +const coloneq = "≔"; +const comma = ","; +const commat = "@"; +const comp = "∁"; +const compfn = "∘"; +const complement = "∁"; +const complexes = "ℂ"; +const cong = "≅"; +const congdot = "⩭"; +const conint = "∮"; +const copf = "𝕔"; +const coprod = "∐"; +const cop = "©"; +const copy$2 = "©"; +const copysr = "℗"; +const crarr = "↵"; +const cross = "✗"; +const cscr = "𝒸"; +const csub = "⫏"; +const csube = "⫑"; +const csup = "⫐"; +const csupe = "⫒"; +const ctdot = "⋯"; +const cudarrl = "⤸"; +const cudarrr = "⤵"; +const cuepr = "⋞"; +const cuesc = "⋟"; +const cularr = "↶"; +const cularrp = "⤽"; +const cup = "∪"; +const cupbrcap = "⩈"; +const cupcap = "⩆"; +const cupcup = "⩊"; +const cupdot = "⊍"; +const cupor = "⩅"; +const cups = "∪︀"; +const curarr = "↷"; +const curarrm = "⤼"; +const curlyeqprec = "⋞"; +const curlyeqsucc = "⋟"; +const curlyvee = "⋎"; +const curlywedge = "⋏"; +const curre = "¤"; +const curren$1 = "¤"; +const curvearrowleft = "↶"; +const curvearrowright = "↷"; +const cuvee = "⋎"; +const cuwed = "⋏"; +const cwconint = "∲"; +const cwint = "∱"; +const cylcty = "⌭"; +const dArr = "⇓"; +const dHar = "⥥"; +const dagger = "†"; +const daleth = "ℸ"; +const darr = "↓"; +const dash = "‐"; +const dashv = "⊣"; +const dbkarow = "⤏"; +const dblac = "˝"; +const dcaron = "ď"; +const dcy = "д"; +const dd = "ⅆ"; +const ddagger = "‡"; +const ddarr = "⇊"; +const ddotseq = "⩷"; +const de = "°"; +const deg$1 = "°"; +const delta = "δ"; +const demptyv = "⦱"; +const dfisht = "⥿"; +const dfr = "𝔡"; +const dharl = "⇃"; +const dharr = "⇂"; +const diam = "⋄"; +const diamond = "⋄"; +const diamondsuit = "♦"; +const diams = "♦"; +const die = "¨"; +const digamma = "ϝ"; +const disin = "⋲"; +const div = "÷"; +const divid = "÷"; +const divide$1 = "÷"; +const divideontimes = "⋇"; +const divonx = "⋇"; +const djcy = "ђ"; +const dlcorn = "⌞"; +const dlcrop = "⌍"; +const dollar = "$"; +const dopf = "𝕕"; +const dot = "˙"; +const doteq = "≐"; +const doteqdot = "≑"; +const dotminus = "∸"; +const dotplus = "∔"; +const dotsquare = "⊡"; +const doublebarwedge = "⌆"; +const downarrow = "↓"; +const downdownarrows = "⇊"; +const downharpoonleft = "⇃"; +const downharpoonright = "⇂"; +const drbkarow = "⤐"; +const drcorn = "⌟"; +const drcrop = "⌌"; +const dscr = "𝒹"; +const dscy = "ѕ"; +const dsol = "⧶"; +const dstrok = "đ"; +const dtdot = "⋱"; +const dtri = "▿"; +const dtrif = "▾"; +const duarr = "⇵"; +const duhar = "⥯"; +const dwangle = "⦦"; +const dzcy = "џ"; +const dzigrarr = "⟿"; +const eDDot = "⩷"; +const eDot = "≑"; +const eacut = "é"; +const eacute$1 = "é"; +const easter = "⩮"; +const ecaron = "ě"; +const ecir = "ê"; +const ecirc$1 = "ê"; +const ecolon = "≕"; +const ecy = "э"; +const edot = "ė"; +const ee = "ⅇ"; +const efDot = "≒"; +const efr = "𝔢"; +const eg = "⪚"; +const egrav = "è"; +const egrave$1 = "è"; +const egs = "⪖"; +const egsdot = "⪘"; +const el = "⪙"; +const elinters = "⏧"; +const ell = "ℓ"; +const els = "⪕"; +const elsdot = "⪗"; +const emacr = "ē"; +const empty = "∅"; +const emptyset = "∅"; +const emptyv = "∅"; +const emsp13 = " "; +const emsp14 = " "; +const emsp = " "; +const eng = "ŋ"; +const ensp = " "; +const eogon = "ę"; +const eopf = "𝕖"; +const epar = "⋕"; +const eparsl = "⧣"; +const eplus = "⩱"; +const epsi = "ε"; +const epsilon = "ε"; +const epsiv = "ϵ"; +const eqcirc = "≖"; +const eqcolon = "≕"; +const eqsim = "≂"; +const eqslantgtr = "⪖"; +const eqslantless = "⪕"; +const equals = "="; +const equest = "≟"; +const equiv = "≡"; +const equivDD = "⩸"; +const eqvparsl = "⧥"; +const erDot = "≓"; +const erarr = "⥱"; +const escr = "ℯ"; +const esdot = "≐"; +const esim = "≂"; +const eta = "η"; +const et = "ð"; +const eth$1 = "ð"; +const eum = "ë"; +const euml$1 = "ë"; +const euro = "€"; +const excl = "!"; +const exist = "∃"; +const expectation = "ℰ"; +const exponentiale = "ⅇ"; +const fallingdotseq = "≒"; +const fcy = "ф"; +const female = "♀"; +const ffilig = "ffi"; +const fflig = "ff"; +const ffllig = "ffl"; +const ffr = "𝔣"; +const filig = "fi"; +const fjlig = "fj"; +const flat = "♭"; +const fllig = "fl"; +const fltns = "▱"; +const fnof = "ƒ"; +const fopf = "𝕗"; +const forall = "∀"; +const fork = "⋔"; +const forkv = "⫙"; +const fpartint = "⨍"; +const frac1 = "¼"; +const frac12$1 = "½"; +const frac13 = "⅓"; +const frac14$1 = "¼"; +const frac15 = "⅕"; +const frac16 = "⅙"; +const frac18 = "⅛"; +const frac23 = "⅔"; +const frac25 = "⅖"; +const frac3 = "¾"; +const frac34$1 = "¾"; +const frac35 = "⅗"; +const frac38 = "⅜"; +const frac45 = "⅘"; +const frac56 = "⅚"; +const frac58 = "⅝"; +const frac78 = "⅞"; +const frasl = "⁄"; +const frown = "⌢"; +const fscr = "𝒻"; +const gE = "≧"; +const gEl = "⪌"; +const gacute = "ǵ"; +const gamma = "γ"; +const gammad = "ϝ"; +const gap = "⪆"; +const gbreve = "ğ"; +const gcirc = "ĝ"; +const gcy = "г"; +const gdot = "ġ"; +const ge = "≥"; +const gel = "⋛"; +const geq = "≥"; +const geqq = "≧"; +const geqslant = "⩾"; +const ges = "⩾"; +const gescc = "⪩"; +const gesdot = "⪀"; +const gesdoto = "⪂"; +const gesdotol = "⪄"; +const gesl = "⋛︀"; +const gesles = "⪔"; +const gfr = "𝔤"; +const gg = "≫"; +const ggg = "⋙"; +const gimel = "ℷ"; +const gjcy = "ѓ"; +const gl = "≷"; +const glE = "⪒"; +const gla = "⪥"; +const glj = "⪤"; +const gnE = "≩"; +const gnap = "⪊"; +const gnapprox = "⪊"; +const gne = "⪈"; +const gneq = "⪈"; +const gneqq = "≩"; +const gnsim = "⋧"; +const gopf = "𝕘"; +const grave = "`"; +const gscr = "ℊ"; +const gsim = "≳"; +const gsime = "⪎"; +const gsiml = "⪐"; +const g = ">"; +const gt$1 = ">"; +const gtcc = "⪧"; +const gtcir = "⩺"; +const gtdot = "⋗"; +const gtlPar = "⦕"; +const gtquest = "⩼"; +const gtrapprox = "⪆"; +const gtrarr = "⥸"; +const gtrdot = "⋗"; +const gtreqless = "⋛"; +const gtreqqless = "⪌"; +const gtrless = "≷"; +const gtrsim = "≳"; +const gvertneqq = "≩︀"; +const gvnE = "≩︀"; +const hArr = "⇔"; +const hairsp = " "; +const half = "½"; +const hamilt = "ℋ"; +const hardcy = "ъ"; +const harr = "↔"; +const harrcir = "⥈"; +const harrw = "↭"; +const hbar = "ℏ"; +const hcirc = "ĥ"; +const hearts = "♥"; +const heartsuit = "♥"; +const hellip = "…"; +const hercon = "⊹"; +const hfr = "𝔥"; +const hksearow = "⤥"; +const hkswarow = "⤦"; +const hoarr = "⇿"; +const homtht = "∻"; +const hookleftarrow = "↩"; +const hookrightarrow = "↪"; +const hopf = "𝕙"; +const horbar = "―"; +const hscr = "𝒽"; +const hslash = "ℏ"; +const hstrok = "ħ"; +const hybull = "⁃"; +const hyphen = "‐"; +const iacut = "í"; +const iacute$1 = "í"; +const ic = "⁣"; +const icir = "î"; +const icirc$1 = "î"; +const icy = "и"; +const iecy = "е"; +const iexc = "¡"; +const iexcl$1 = "¡"; +const iff = "⇔"; +const ifr = "𝔦"; +const igrav = "ì"; +const igrave$1 = "ì"; +const ii = "ⅈ"; +const iiiint = "⨌"; +const iiint = "∭"; +const iinfin = "⧜"; +const iiota = "℩"; +const ijlig = "ij"; +const imacr = "ī"; +const image = "ℑ"; +const imagline = "ℐ"; +const imagpart = "ℑ"; +const imath = "ı"; +const imof = "⊷"; +const imped = "Ƶ"; +const incare = "℅"; +const infin = "∞"; +const infintie = "⧝"; +const inodot = "ı"; +const int = "∫"; +const intcal = "⊺"; +const integers = "ℤ"; +const intercal = "⊺"; +const intlarhk = "⨗"; +const intprod = "⨼"; +const iocy = "ё"; +const iogon = "į"; +const iopf = "𝕚"; +const iota = "ι"; +const iprod = "⨼"; +const iques = "¿"; +const iquest$1 = "¿"; +const iscr = "𝒾"; +const isin = "∈"; +const isinE = "⋹"; +const isindot = "⋵"; +const isins = "⋴"; +const isinsv = "⋳"; +const isinv = "∈"; +const it = "⁢"; +const itilde = "ĩ"; +const iukcy = "і"; +const ium = "ï"; +const iuml$1 = "ï"; +const jcirc = "ĵ"; +const jcy = "й"; +const jfr = "𝔧"; +const jmath = "ȷ"; +const jopf = "𝕛"; +const jscr = "𝒿"; +const jsercy = "ј"; +const jukcy = "є"; +const kappa = "κ"; +const kappav = "ϰ"; +const kcedil = "ķ"; +const kcy = "к"; +const kfr = "𝔨"; +const kgreen = "ĸ"; +const khcy = "х"; +const kjcy = "ќ"; +const kopf = "𝕜"; +const kscr = "𝓀"; +const lAarr = "⇚"; +const lArr = "⇐"; +const lAtail = "⤛"; +const lBarr = "⤎"; +const lE = "≦"; +const lEg = "⪋"; +const lHar = "⥢"; +const lacute = "ĺ"; +const laemptyv = "⦴"; +const lagran = "ℒ"; +const lambda = "λ"; +const lang = "⟨"; +const langd = "⦑"; +const langle = "⟨"; +const lap = "⪅"; +const laqu = "«"; +const laquo$1 = "«"; +const larr = "←"; +const larrb = "⇤"; +const larrbfs = "⤟"; +const larrfs = "⤝"; +const larrhk = "↩"; +const larrlp = "↫"; +const larrpl = "⤹"; +const larrsim = "⥳"; +const larrtl = "↢"; +const lat = "⪫"; +const latail = "⤙"; +const late = "⪭"; +const lates = "⪭︀"; +const lbarr = "⤌"; +const lbbrk = "❲"; +const lbrace = "{"; +const lbrack = "["; +const lbrke = "⦋"; +const lbrksld = "⦏"; +const lbrkslu = "⦍"; +const lcaron = "ľ"; +const lcedil = "ļ"; +const lceil = "⌈"; +const lcub = "{"; +const lcy = "л"; +const ldca = "⤶"; +const ldquo = "“"; +const ldquor = "„"; +const ldrdhar = "⥧"; +const ldrushar = "⥋"; +const ldsh = "↲"; +const le = "≤"; +const leftarrow = "←"; +const leftarrowtail = "↢"; +const leftharpoondown = "↽"; +const leftharpoonup = "↼"; +const leftleftarrows = "⇇"; +const leftrightarrow = "↔"; +const leftrightarrows = "⇆"; +const leftrightharpoons = "⇋"; +const leftrightsquigarrow = "↭"; +const leftthreetimes = "⋋"; +const leg = "⋚"; +const leq = "≤"; +const leqq = "≦"; +const leqslant = "⩽"; +const les = "⩽"; +const lescc = "⪨"; +const lesdot = "⩿"; +const lesdoto = "⪁"; +const lesdotor = "⪃"; +const lesg = "⋚︀"; +const lesges = "⪓"; +const lessapprox = "⪅"; +const lessdot = "⋖"; +const lesseqgtr = "⋚"; +const lesseqqgtr = "⪋"; +const lessgtr = "≶"; +const lesssim = "≲"; +const lfisht = "⥼"; +const lfloor = "⌊"; +const lfr = "𝔩"; +const lg = "≶"; +const lgE = "⪑"; +const lhard = "↽"; +const lharu = "↼"; +const lharul = "⥪"; +const lhblk = "▄"; +const ljcy = "љ"; +const ll = "≪"; +const llarr = "⇇"; +const llcorner = "⌞"; +const llhard = "⥫"; +const lltri = "◺"; +const lmidot = "ŀ"; +const lmoust = "⎰"; +const lmoustache = "⎰"; +const lnE = "≨"; +const lnap = "⪉"; +const lnapprox = "⪉"; +const lne = "⪇"; +const lneq = "⪇"; +const lneqq = "≨"; +const lnsim = "⋦"; +const loang = "⟬"; +const loarr = "⇽"; +const lobrk = "⟦"; +const longleftarrow = "⟵"; +const longleftrightarrow = "⟷"; +const longmapsto = "⟼"; +const longrightarrow = "⟶"; +const looparrowleft = "↫"; +const looparrowright = "↬"; +const lopar = "⦅"; +const lopf = "𝕝"; +const loplus = "⨭"; +const lotimes = "⨴"; +const lowast = "∗"; +const lowbar = "_"; +const loz = "◊"; +const lozenge = "◊"; +const lozf = "⧫"; +const lpar = "("; +const lparlt = "⦓"; +const lrarr = "⇆"; +const lrcorner = "⌟"; +const lrhar = "⇋"; +const lrhard = "⥭"; +const lrm = "‎"; +const lrtri = "⊿"; +const lsaquo = "‹"; +const lscr = "𝓁"; +const lsh = "↰"; +const lsim = "≲"; +const lsime = "⪍"; +const lsimg = "⪏"; +const lsqb = "["; +const lsquo = "‘"; +const lsquor = "‚"; +const lstrok = "ł"; +const l = "<"; +const lt$1 = "<"; +const ltcc = "⪦"; +const ltcir = "⩹"; +const ltdot = "⋖"; +const lthree = "⋋"; +const ltimes = "⋉"; +const ltlarr = "⥶"; +const ltquest = "⩻"; +const ltrPar = "⦖"; +const ltri = "◃"; +const ltrie = "⊴"; +const ltrif = "◂"; +const lurdshar = "⥊"; +const luruhar = "⥦"; +const lvertneqq = "≨︀"; +const lvnE = "≨︀"; +const mDDot = "∺"; +const mac = "¯"; +const macr$1 = "¯"; +const male = "♂"; +const malt = "✠"; +const maltese = "✠"; +const map$2 = "↦"; +const mapsto = "↦"; +const mapstodown = "↧"; +const mapstoleft = "↤"; +const mapstoup = "↥"; +const marker = "▮"; +const mcomma = "⨩"; +const mcy = "м"; +const mdash = "—"; +const measuredangle = "∡"; +const mfr = "𝔪"; +const mho = "℧"; +const micr = "µ"; +const micro$1 = "µ"; +const mid = "∣"; +const midast = "*"; +const midcir = "⫰"; +const middo = "·"; +const middot$1 = "·"; +const minus = "−"; +const minusb = "⊟"; +const minusd = "∸"; +const minusdu = "⨪"; +const mlcp = "⫛"; +const mldr = "…"; +const mnplus = "∓"; +const models$1 = "⊧"; +const mopf = "𝕞"; +const mp = "∓"; +const mscr = "𝓂"; +const mstpos = "∾"; +const mu = "μ"; +const multimap = "⊸"; +const mumap = "⊸"; +const nGg = "⋙̸"; +const nGt = "≫⃒"; +const nGtv = "≫̸"; +const nLeftarrow = "⇍"; +const nLeftrightarrow = "⇎"; +const nLl = "⋘̸"; +const nLt = "≪⃒"; +const nLtv = "≪̸"; +const nRightarrow = "⇏"; +const nVDash = "⊯"; +const nVdash = "⊮"; +const nabla = "∇"; +const nacute = "ń"; +const nang = "∠⃒"; +const nap = "≉"; +const napE = "⩰̸"; +const napid = "≋̸"; +const napos = "ʼn"; +const napprox = "≉"; +const natur = "♮"; +const natural = "♮"; +const naturals = "ℕ"; +const nbs = " "; +const nbsp$1 = " "; +const nbump = "≎̸"; +const nbumpe = "≏̸"; +const ncap = "⩃"; +const ncaron = "ň"; +const ncedil = "ņ"; +const ncong = "≇"; +const ncongdot = "⩭̸"; +const ncup = "⩂"; +const ncy = "н"; +const ndash = "–"; +const ne = "≠"; +const neArr = "⇗"; +const nearhk = "⤤"; +const nearr = "↗"; +const nearrow = "↗"; +const nedot = "≐̸"; +const nequiv = "≢"; +const nesear = "⤨"; +const nesim = "≂̸"; +const nexist = "∄"; +const nexists = "∄"; +const nfr = "𝔫"; +const ngE = "≧̸"; +const nge = "≱"; +const ngeq = "≱"; +const ngeqq = "≧̸"; +const ngeqslant = "⩾̸"; +const nges = "⩾̸"; +const ngsim = "≵"; +const ngt = "≯"; +const ngtr = "≯"; +const nhArr = "⇎"; +const nharr = "↮"; +const nhpar = "⫲"; +const ni = "∋"; +const nis = "⋼"; +const nisd = "⋺"; +const niv = "∋"; +const njcy = "њ"; +const nlArr = "⇍"; +const nlE = "≦̸"; +const nlarr = "↚"; +const nldr = "‥"; +const nle = "≰"; +const nleftarrow = "↚"; +const nleftrightarrow = "↮"; +const nleq = "≰"; +const nleqq = "≦̸"; +const nleqslant = "⩽̸"; +const nles = "⩽̸"; +const nless = "≮"; +const nlsim = "≴"; +const nlt = "≮"; +const nltri = "⋪"; +const nltrie = "⋬"; +const nmid = "∤"; +const nopf = "𝕟"; +const no = "¬"; +const not$1 = "¬"; +const notin = "∉"; +const notinE = "⋹̸"; +const notindot = "⋵̸"; +const notinva = "∉"; +const notinvb = "⋷"; +const notinvc = "⋶"; +const notni = "∌"; +const notniva = "∌"; +const notnivb = "⋾"; +const notnivc = "⋽"; +const npar = "∦"; +const nparallel = "∦"; +const nparsl = "⫽⃥"; +const npart = "∂̸"; +const npolint = "⨔"; +const npr = "⊀"; +const nprcue = "⋠"; +const npre = "⪯̸"; +const nprec = "⊀"; +const npreceq = "⪯̸"; +const nrArr = "⇏"; +const nrarr = "↛"; +const nrarrc = "⤳̸"; +const nrarrw = "↝̸"; +const nrightarrow = "↛"; +const nrtri = "⋫"; +const nrtrie = "⋭"; +const nsc = "⊁"; +const nsccue = "⋡"; +const nsce = "⪰̸"; +const nscr = "𝓃"; +const nshortmid = "∤"; +const nshortparallel = "∦"; +const nsim = "≁"; +const nsime = "≄"; +const nsimeq = "≄"; +const nsmid = "∤"; +const nspar = "∦"; +const nsqsube = "⋢"; +const nsqsupe = "⋣"; +const nsub = "⊄"; +const nsubE = "⫅̸"; +const nsube = "⊈"; +const nsubset = "⊂⃒"; +const nsubseteq = "⊈"; +const nsubseteqq = "⫅̸"; +const nsucc = "⊁"; +const nsucceq = "⪰̸"; +const nsup = "⊅"; +const nsupE = "⫆̸"; +const nsupe = "⊉"; +const nsupset = "⊃⃒"; +const nsupseteq = "⊉"; +const nsupseteqq = "⫆̸"; +const ntgl = "≹"; +const ntild = "ñ"; +const ntilde$1 = "ñ"; +const ntlg = "≸"; +const ntriangleleft = "⋪"; +const ntrianglelefteq = "⋬"; +const ntriangleright = "⋫"; +const ntrianglerighteq = "⋭"; +const nu = "ν"; +const num = "#"; +const numero = "№"; +const numsp = " "; +const nvDash = "⊭"; +const nvHarr = "⤄"; +const nvap = "≍⃒"; +const nvdash = "⊬"; +const nvge = "≥⃒"; +const nvgt = ">⃒"; +const nvinfin = "⧞"; +const nvlArr = "⤂"; +const nvle = "≤⃒"; +const nvlt = "<⃒"; +const nvltrie = "⊴⃒"; +const nvrArr = "⤃"; +const nvrtrie = "⊵⃒"; +const nvsim = "∼⃒"; +const nwArr = "⇖"; +const nwarhk = "⤣"; +const nwarr = "↖"; +const nwarrow = "↖"; +const nwnear = "⤧"; +const oS = "Ⓢ"; +const oacut = "ó"; +const oacute$1 = "ó"; +const oast = "⊛"; +const ocir = "ô"; +const ocirc$1 = "ô"; +const ocy = "о"; +const odash = "⊝"; +const odblac = "ő"; +const odiv = "⨸"; +const odot = "⊙"; +const odsold = "⦼"; +const oelig = "œ"; +const ofcir = "⦿"; +const ofr = "𝔬"; +const ogon = "˛"; +const ograv = "ò"; +const ograve$1 = "ò"; +const ogt = "⧁"; +const ohbar = "⦵"; +const ohm = "Ω"; +const oint = "∮"; +const olarr = "↺"; +const olcir = "⦾"; +const olcross = "⦻"; +const oline = "‾"; +const olt = "⧀"; +const omacr = "ō"; +const omega = "ω"; +const omicron = "ο"; +const omid = "⦶"; +const ominus = "⊖"; +const oopf = "𝕠"; +const opar = "⦷"; +const operp = "⦹"; +const oplus = "⊕"; +const or = "∨"; +const orarr = "↻"; +const ord = "º"; +const order$1 = "ℴ"; +const orderof = "ℴ"; +const ordf$1 = "ª"; +const ordm$1 = "º"; +const origof = "⊶"; +const oror = "⩖"; +const orslope = "⩗"; +const orv = "⩛"; +const oscr = "ℴ"; +const oslas = "ø"; +const oslash$1 = "ø"; +const osol = "⊘"; +const otild = "õ"; +const otilde$1 = "õ"; +const otimes = "⊗"; +const otimesas = "⨶"; +const oum = "ö"; +const ouml$1 = "ö"; +const ovbar = "⌽"; +const par = "¶"; +const para$1 = "¶"; +const parallel = "∥"; +const parsim = "⫳"; +const parsl = "⫽"; +const part = "∂"; +const pcy = "п"; +const percnt = "%"; +const period = "."; +const permil = "‰"; +const perp = "⊥"; +const pertenk = "‱"; +const pfr = "𝔭"; +const phi = "φ"; +const phiv = "ϕ"; +const phmmat = "ℳ"; +const phone = "☎"; +const pi = "π"; +const pitchfork = "⋔"; +const piv = "ϖ"; +const planck = "ℏ"; +const planckh = "ℎ"; +const plankv = "ℏ"; +const plus = "+"; +const plusacir = "⨣"; +const plusb = "⊞"; +const pluscir = "⨢"; +const plusdo = "∔"; +const plusdu = "⨥"; +const pluse = "⩲"; +const plusm = "±"; +const plusmn$1 = "±"; +const plussim = "⨦"; +const plustwo = "⨧"; +const pm = "±"; +const pointint = "⨕"; +const popf = "𝕡"; +const poun = "£"; +const pound$1 = "£"; +const pr = "≺"; +const prE = "⪳"; +const prap = "⪷"; +const prcue = "≼"; +const pre = "⪯"; +const prec = "≺"; +const precapprox = "⪷"; +const preccurlyeq = "≼"; +const preceq = "⪯"; +const precnapprox = "⪹"; +const precneqq = "⪵"; +const precnsim = "⋨"; +const precsim = "≾"; +const prime = "′"; +const primes = "ℙ"; +const prnE = "⪵"; +const prnap = "⪹"; +const prnsim = "⋨"; +const prod = "∏"; +const profalar = "⌮"; +const profline = "⌒"; +const profsurf = "⌓"; +const prop = "∝"; +const propto = "∝"; +const prsim = "≾"; +const prurel = "⊰"; +const pscr = "𝓅"; +const psi = "ψ"; +const puncsp = " "; +const qfr = "𝔮"; +const qint = "⨌"; +const qopf = "𝕢"; +const qprime = "⁗"; +const qscr = "𝓆"; +const quaternions = "ℍ"; +const quatint = "⨖"; +const quest = "?"; +const questeq = "≟"; +const quo = "\""; +const quot$1 = "\""; +const rAarr = "⇛"; +const rArr = "⇒"; +const rAtail = "⤜"; +const rBarr = "⤏"; +const rHar = "⥤"; +const race = "∽̱"; +const racute = "ŕ"; +const radic = "√"; +const raemptyv = "⦳"; +const rang = "⟩"; +const rangd = "⦒"; +const range$1 = "⦥"; +const rangle = "⟩"; +const raqu = "»"; +const raquo$1 = "»"; +const rarr = "→"; +const rarrap = "⥵"; +const rarrb = "⇥"; +const rarrbfs = "⤠"; +const rarrc = "⤳"; +const rarrfs = "⤞"; +const rarrhk = "↪"; +const rarrlp = "↬"; +const rarrpl = "⥅"; +const rarrsim = "⥴"; +const rarrtl = "↣"; +const rarrw = "↝"; +const ratail = "⤚"; +const ratio = "∶"; +const rationals = "ℚ"; +const rbarr = "⤍"; +const rbbrk = "❳"; +const rbrace = "}"; +const rbrack = "]"; +const rbrke = "⦌"; +const rbrksld = "⦎"; +const rbrkslu = "⦐"; +const rcaron = "ř"; +const rcedil = "ŗ"; +const rceil = "⌉"; +const rcub = "}"; +const rcy = "р"; +const rdca = "⤷"; +const rdldhar = "⥩"; +const rdquo = "”"; +const rdquor = "”"; +const rdsh = "↳"; +const real = "ℜ"; +const realine = "ℛ"; +const realpart = "ℜ"; +const reals = "ℝ"; +const rect = "▭"; +const re = "®"; +const reg$1 = "®"; +const rfisht = "⥽"; +const rfloor = "⌋"; +const rfr = "𝔯"; +const rhard = "⇁"; +const rharu = "⇀"; +const rharul = "⥬"; +const rho = "ρ"; +const rhov = "ϱ"; +const rightarrow = "→"; +const rightarrowtail = "↣"; +const rightharpoondown = "⇁"; +const rightharpoonup = "⇀"; +const rightleftarrows = "⇄"; +const rightleftharpoons = "⇌"; +const rightrightarrows = "⇉"; +const rightsquigarrow = "↝"; +const rightthreetimes = "⋌"; +const ring = "˚"; +const risingdotseq = "≓"; +const rlarr = "⇄"; +const rlhar = "⇌"; +const rlm = "‏"; +const rmoust = "⎱"; +const rmoustache = "⎱"; +const rnmid = "⫮"; +const roang = "⟭"; +const roarr = "⇾"; +const robrk = "⟧"; +const ropar = "⦆"; +const ropf = "𝕣"; +const roplus = "⨮"; +const rotimes = "⨵"; +const rpar = ")"; +const rpargt = "⦔"; +const rppolint = "⨒"; +const rrarr = "⇉"; +const rsaquo = "›"; +const rscr = "𝓇"; +const rsh = "↱"; +const rsqb = "]"; +const rsquo = "’"; +const rsquor = "’"; +const rthree = "⋌"; +const rtimes = "⋊"; +const rtri = "▹"; +const rtrie = "⊵"; +const rtrif = "▸"; +const rtriltri = "⧎"; +const ruluhar = "⥨"; +const rx = "℞"; +const sacute = "ś"; +const sbquo = "‚"; +const sc = "≻"; +const scE = "⪴"; +const scap = "⪸"; +const scaron = "š"; +const sccue = "≽"; +const sce = "⪰"; +const scedil = "ş"; +const scirc = "ŝ"; +const scnE = "⪶"; +const scnap = "⪺"; +const scnsim = "⋩"; +const scpolint = "⨓"; +const scsim = "≿"; +const scy = "с"; +const sdot = "⋅"; +const sdotb = "⊡"; +const sdote = "⩦"; +const seArr = "⇘"; +const searhk = "⤥"; +const searr = "↘"; +const searrow = "↘"; +const sec = "§"; +const sect$1 = "§"; +const semi = ";"; +const seswar = "⤩"; +const setminus = "∖"; +const setmn = "∖"; +const sext = "✶"; +const sfr = "𝔰"; +const sfrown = "⌢"; +const sharp = "♯"; +const shchcy = "щ"; +const shcy = "ш"; +const shortmid = "∣"; +const shortparallel = "∥"; +const sh = "­"; +const shy$1 = "­"; +const sigma = "σ"; +const sigmaf = "ς"; +const sigmav = "ς"; +const sim = "∼"; +const simdot = "⩪"; +const sime = "≃"; +const simeq = "≃"; +const simg = "⪞"; +const simgE = "⪠"; +const siml = "⪝"; +const simlE = "⪟"; +const simne = "≆"; +const simplus = "⨤"; +const simrarr = "⥲"; +const slarr = "←"; +const smallsetminus = "∖"; +const smashp = "⨳"; +const smeparsl = "⧤"; +const smid = "∣"; +const smile = "⌣"; +const smt = "⪪"; +const smte = "⪬"; +const smtes = "⪬︀"; +const softcy = "ь"; +const sol = "/"; +const solb = "⧄"; +const solbar = "⌿"; +const sopf = "𝕤"; +const spades = "♠"; +const spadesuit = "♠"; +const spar = "∥"; +const sqcap = "⊓"; +const sqcaps = "⊓︀"; +const sqcup = "⊔"; +const sqcups = "⊔︀"; +const sqsub = "⊏"; +const sqsube = "⊑"; +const sqsubset = "⊏"; +const sqsubseteq = "⊑"; +const sqsup = "⊐"; +const sqsupe = "⊒"; +const sqsupset = "⊐"; +const sqsupseteq = "⊒"; +const squ = "□"; +const square = "□"; +const squarf = "▪"; +const squf = "▪"; +const srarr = "→"; +const sscr = "𝓈"; +const ssetmn = "∖"; +const ssmile = "⌣"; +const sstarf = "⋆"; +const star$1 = "☆"; +const starf = "★"; +const straightepsilon = "ϵ"; +const straightphi = "ϕ"; +const strns = "¯"; +const sub = "⊂"; +const subE = "⫅"; +const subdot = "⪽"; +const sube = "⊆"; +const subedot = "⫃"; +const submult = "⫁"; +const subnE = "⫋"; +const subne = "⊊"; +const subplus = "⪿"; +const subrarr = "⥹"; +const subset = "⊂"; +const subseteq = "⊆"; +const subseteqq = "⫅"; +const subsetneq = "⊊"; +const subsetneqq = "⫋"; +const subsim = "⫇"; +const subsub = "⫕"; +const subsup = "⫓"; +const succ = "≻"; +const succapprox = "⪸"; +const succcurlyeq = "≽"; +const succeq = "⪰"; +const succnapprox = "⪺"; +const succneqq = "⪶"; +const succnsim = "⋩"; +const succsim = "≿"; +const sum = "∑"; +const sung = "♪"; +const sup = "⊃"; +const sup1$1 = "¹"; +const sup2$1 = "²"; +const sup3$1 = "³"; +const supE = "⫆"; +const supdot = "⪾"; +const supdsub = "⫘"; +const supe = "⊇"; +const supedot = "⫄"; +const suphsol = "⟉"; +const suphsub = "⫗"; +const suplarr = "⥻"; +const supmult = "⫂"; +const supnE = "⫌"; +const supne = "⊋"; +const supplus = "⫀"; +const supset = "⊃"; +const supseteq = "⊇"; +const supseteqq = "⫆"; +const supsetneq = "⊋"; +const supsetneqq = "⫌"; +const supsim = "⫈"; +const supsub = "⫔"; +const supsup = "⫖"; +const swArr = "⇙"; +const swarhk = "⤦"; +const swarr = "↙"; +const swarrow = "↙"; +const swnwar = "⤪"; +const szli = "ß"; +const szlig$1 = "ß"; +const target = "⌖"; +const tau = "τ"; +const tbrk = "⎴"; +const tcaron = "ť"; +const tcedil = "ţ"; +const tcy = "т"; +const tdot = "⃛"; +const telrec = "⌕"; +const tfr = "𝔱"; +const there4 = "∴"; +const therefore = "∴"; +const theta = "θ"; +const thetasym = "ϑ"; +const thetav = "ϑ"; +const thickapprox = "≈"; +const thicksim = "∼"; +const thinsp = " "; +const thkap = "≈"; +const thksim = "∼"; +const thor = "þ"; +const thorn$1 = "þ"; +const tilde = "˜"; +const time = "×"; +const times$1 = "×"; +const timesb = "⊠"; +const timesbar = "⨱"; +const timesd = "⨰"; +const tint = "∭"; +const toea = "⤨"; +const top = "⊤"; +const topbot = "⌶"; +const topcir = "⫱"; +const topf = "𝕥"; +const topfork = "⫚"; +const tosa = "⤩"; +const tprime = "‴"; +const trade = "™"; +const triangle = "▵"; +const triangledown = "▿"; +const triangleleft = "◃"; +const trianglelefteq = "⊴"; +const triangleq = "≜"; +const triangleright = "▹"; +const trianglerighteq = "⊵"; +const tridot = "◬"; +const trie = "≜"; +const triminus = "⨺"; +const triplus = "⨹"; +const trisb = "⧍"; +const tritime = "⨻"; +const trpezium = "⏢"; +const tscr = "𝓉"; +const tscy = "ц"; +const tshcy = "ћ"; +const tstrok = "ŧ"; +const twixt = "≬"; +const twoheadleftarrow = "↞"; +const twoheadrightarrow = "↠"; +const uArr = "⇑"; +const uHar = "⥣"; +const uacut = "ú"; +const uacute$1 = "ú"; +const uarr = "↑"; +const ubrcy = "ў"; +const ubreve = "ŭ"; +const ucir = "û"; +const ucirc$1 = "û"; +const ucy = "у"; +const udarr = "⇅"; +const udblac = "ű"; +const udhar = "⥮"; +const ufisht = "⥾"; +const ufr = "𝔲"; +const ugrav = "ù"; +const ugrave$1 = "ù"; +const uharl = "↿"; +const uharr = "↾"; +const uhblk = "▀"; +const ulcorn = "⌜"; +const ulcorner = "⌜"; +const ulcrop = "⌏"; +const ultri = "◸"; +const umacr = "ū"; +const um = "¨"; +const uml$1 = "¨"; +const uogon = "ų"; +const uopf = "𝕦"; +const uparrow = "↑"; +const updownarrow = "↕"; +const upharpoonleft = "↿"; +const upharpoonright = "↾"; +const uplus = "⊎"; +const upsi = "υ"; +const upsih = "ϒ"; +const upsilon = "υ"; +const upuparrows = "⇈"; +const urcorn = "⌝"; +const urcorner = "⌝"; +const urcrop = "⌎"; +const uring = "ů"; +const urtri = "◹"; +const uscr = "𝓊"; +const utdot = "⋰"; +const utilde = "ũ"; +const utri = "▵"; +const utrif = "▴"; +const uuarr = "⇈"; +const uum = "ü"; +const uuml$1 = "ü"; +const uwangle = "⦧"; +const vArr = "⇕"; +const vBar = "⫨"; +const vBarv = "⫩"; +const vDash = "⊨"; +const vangrt = "⦜"; +const varepsilon = "ϵ"; +const varkappa = "ϰ"; +const varnothing = "∅"; +const varphi = "ϕ"; +const varpi = "ϖ"; +const varpropto = "∝"; +const varr = "↕"; +const varrho = "ϱ"; +const varsigma = "ς"; +const varsubsetneq = "⊊︀"; +const varsubsetneqq = "⫋︀"; +const varsupsetneq = "⊋︀"; +const varsupsetneqq = "⫌︀"; +const vartheta = "ϑ"; +const vartriangleleft = "⊲"; +const vartriangleright = "⊳"; +const vcy = "в"; +const vdash = "⊢"; +const vee = "∨"; +const veebar = "⊻"; +const veeeq = "≚"; +const vellip = "⋮"; +const verbar = "|"; +const vert = "|"; +const vfr = "𝔳"; +const vltri = "⊲"; +const vnsub = "⊂⃒"; +const vnsup = "⊃⃒"; +const vopf = "𝕧"; +const vprop = "∝"; +const vrtri = "⊳"; +const vscr = "𝓋"; +const vsubnE = "⫋︀"; +const vsubne = "⊊︀"; +const vsupnE = "⫌︀"; +const vsupne = "⊋︀"; +const vzigzag = "⦚"; +const wcirc = "ŵ"; +const wedbar = "⩟"; +const wedge = "∧"; +const wedgeq = "≙"; +const weierp = "℘"; +const wfr = "𝔴"; +const wopf = "𝕨"; +const wp = "℘"; +const wr = "≀"; +const wreath = "≀"; +const wscr = "𝓌"; +const xcap = "⋂"; +const xcirc = "◯"; +const xcup = "⋃"; +const xdtri = "▽"; +const xfr = "𝔵"; +const xhArr = "⟺"; +const xharr = "⟷"; +const xi = "ξ"; +const xlArr = "⟸"; +const xlarr = "⟵"; +const xmap = "⟼"; +const xnis = "⋻"; +const xodot = "⨀"; +const xopf = "𝕩"; +const xoplus = "⨁"; +const xotime = "⨂"; +const xrArr = "⟹"; +const xrarr = "⟶"; +const xscr = "𝓍"; +const xsqcup = "⨆"; +const xuplus = "⨄"; +const xutri = "△"; +const xvee = "⋁"; +const xwedge = "⋀"; +const yacut = "ý"; +const yacute$1 = "ý"; +const yacy = "я"; +const ycirc = "ŷ"; +const ycy = "ы"; +const ye = "¥"; +const yen$1 = "¥"; +const yfr = "𝔶"; +const yicy = "ї"; +const yopf = "𝕪"; +const yscr = "𝓎"; +const yucy = "ю"; +const yum = "ÿ"; +const yuml$1 = "ÿ"; +const zacute = "ź"; +const zcaron = "ž"; +const zcy = "з"; +const zdot = "ż"; +const zeetrf = "ℨ"; +const zeta = "ζ"; +const zfr = "𝔷"; +const zhcy = "ж"; +const zigrarr = "⇝"; +const zopf = "𝕫"; +const zscr = "𝓏"; +const zwj = "‍"; +const zwnj = "‌"; +var index$3 = { + AEli: AEli, + AElig: AElig$1, + AM: AM, + AMP: AMP$1, + Aacut: Aacut, + Aacute: Aacute$1, + Abreve: Abreve, + Acir: Acir, + Acirc: Acirc$1, + Acy: Acy, + Afr: Afr, + Agrav: Agrav, + Agrave: Agrave$1, + Alpha: Alpha, + Amacr: Amacr, + And: And, + Aogon: Aogon, + Aopf: Aopf, + ApplyFunction: ApplyFunction, + Arin: Arin, + Aring: Aring$1, + Ascr: Ascr, + Assign: Assign, + Atild: Atild, + Atilde: Atilde$1, + Aum: Aum, + Auml: Auml$1, + Backslash: Backslash, + Barv: Barv, + Barwed: Barwed, + Bcy: Bcy, + Because: Because, + Bernoullis: Bernoullis, + Beta: Beta, + Bfr: Bfr, + Bopf: Bopf, + Breve: Breve, + Bscr: Bscr, + Bumpeq: Bumpeq, + CHcy: CHcy, + COP: COP, + COPY: COPY$1, + Cacute: Cacute, + Cap: Cap, + CapitalDifferentialD: CapitalDifferentialD, + Cayleys: Cayleys, + Ccaron: Ccaron, + Ccedi: Ccedi, + Ccedil: Ccedil$1, + Ccirc: Ccirc, + Cconint: Cconint, + Cdot: Cdot, + Cedilla: Cedilla, + CenterDot: CenterDot, + Cfr: Cfr, + Chi: Chi, + CircleDot: CircleDot, + CircleMinus: CircleMinus, + CirclePlus: CirclePlus, + CircleTimes: CircleTimes, + ClockwiseContourIntegral: ClockwiseContourIntegral, + CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, + CloseCurlyQuote: CloseCurlyQuote, + Colon: Colon, + Colone: Colone, + Congruent: Congruent, + Conint: Conint, + ContourIntegral: ContourIntegral, + Copf: Copf, + Coproduct: Coproduct, + CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, + Cross: Cross, + Cscr: Cscr, + Cup: Cup, + CupCap: CupCap, + DD: DD, + DDotrahd: DDotrahd, + DJcy: DJcy, + DScy: DScy, + DZcy: DZcy, + Dagger: Dagger, + Darr: Darr, + Dashv: Dashv, + Dcaron: Dcaron, + Dcy: Dcy, + Del: Del, + Delta: Delta, + Dfr: Dfr, + DiacriticalAcute: DiacriticalAcute, + DiacriticalDot: DiacriticalDot, + DiacriticalDoubleAcute: DiacriticalDoubleAcute, + DiacriticalGrave: DiacriticalGrave, + DiacriticalTilde: DiacriticalTilde, + Diamond: Diamond, + DifferentialD: DifferentialD, + Dopf: Dopf, + Dot: Dot, + DotDot: DotDot, + DotEqual: DotEqual, + DoubleContourIntegral: DoubleContourIntegral, + DoubleDot: DoubleDot, + DoubleDownArrow: DoubleDownArrow, + DoubleLeftArrow: DoubleLeftArrow, + DoubleLeftRightArrow: DoubleLeftRightArrow, + DoubleLeftTee: DoubleLeftTee, + DoubleLongLeftArrow: DoubleLongLeftArrow, + DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, + DoubleLongRightArrow: DoubleLongRightArrow, + DoubleRightArrow: DoubleRightArrow, + DoubleRightTee: DoubleRightTee, + DoubleUpArrow: DoubleUpArrow, + DoubleUpDownArrow: DoubleUpDownArrow, + DoubleVerticalBar: DoubleVerticalBar, + DownArrow: DownArrow, + DownArrowBar: DownArrowBar, + DownArrowUpArrow: DownArrowUpArrow, + DownBreve: DownBreve, + DownLeftRightVector: DownLeftRightVector, + DownLeftTeeVector: DownLeftTeeVector, + DownLeftVector: DownLeftVector, + DownLeftVectorBar: DownLeftVectorBar, + DownRightTeeVector: DownRightTeeVector, + DownRightVector: DownRightVector, + DownRightVectorBar: DownRightVectorBar, + DownTee: DownTee, + DownTeeArrow: DownTeeArrow, + Downarrow: Downarrow, + Dscr: Dscr, + Dstrok: Dstrok, + ENG: ENG, + ET: ET, + ETH: ETH$1, + Eacut: Eacut, + Eacute: Eacute$1, + Ecaron: Ecaron, + Ecir: Ecir, + Ecirc: Ecirc$1, + Ecy: Ecy, + Edot: Edot, + Efr: Efr, + Egrav: Egrav, + Egrave: Egrave$1, + Element: Element, + Emacr: Emacr, + EmptySmallSquare: EmptySmallSquare, + EmptyVerySmallSquare: EmptyVerySmallSquare, + Eogon: Eogon, + Eopf: Eopf, + Epsilon: Epsilon, + Equal: Equal, + EqualTilde: EqualTilde, + Equilibrium: Equilibrium, + Escr: Escr, + Esim: Esim, + Eta: Eta, + Eum: Eum, + Euml: Euml$1, + Exists: Exists, + ExponentialE: ExponentialE, + Fcy: Fcy, + Ffr: Ffr, + FilledSmallSquare: FilledSmallSquare, + FilledVerySmallSquare: FilledVerySmallSquare, + Fopf: Fopf, + ForAll: ForAll, + Fouriertrf: Fouriertrf, + Fscr: Fscr, + GJcy: GJcy, + G: G, + GT: GT$1, + Gamma: Gamma, + Gammad: Gammad, + Gbreve: Gbreve, + Gcedil: Gcedil, + Gcirc: Gcirc, + Gcy: Gcy, + Gdot: Gdot, + Gfr: Gfr, + Gg: Gg, + Gopf: Gopf, + GreaterEqual: GreaterEqual, + GreaterEqualLess: GreaterEqualLess, + GreaterFullEqual: GreaterFullEqual, + GreaterGreater: GreaterGreater, + GreaterLess: GreaterLess, + GreaterSlantEqual: GreaterSlantEqual, + GreaterTilde: GreaterTilde, + Gscr: Gscr, + Gt: Gt, + HARDcy: HARDcy, + Hacek: Hacek, + Hat: Hat, + Hcirc: Hcirc, + Hfr: Hfr, + HilbertSpace: HilbertSpace, + Hopf: Hopf, + HorizontalLine: HorizontalLine, + Hscr: Hscr, + Hstrok: Hstrok, + HumpDownHump: HumpDownHump, + HumpEqual: HumpEqual, + IEcy: IEcy, + IJlig: IJlig, + IOcy: IOcy, + Iacut: Iacut, + Iacute: Iacute$1, + Icir: Icir, + Icirc: Icirc$1, + Icy: Icy, + Idot: Idot, + Ifr: Ifr, + Igrav: Igrav, + Igrave: Igrave$1, + Im: Im, + Imacr: Imacr, + ImaginaryI: ImaginaryI, + Implies: Implies, + Int: Int, + Integral: Integral, + Intersection: Intersection, + InvisibleComma: InvisibleComma, + InvisibleTimes: InvisibleTimes, + Iogon: Iogon, + Iopf: Iopf, + Iota: Iota, + Iscr: Iscr, + Itilde: Itilde, + Iukcy: Iukcy, + Ium: Ium, + Iuml: Iuml$1, + Jcirc: Jcirc, + Jcy: Jcy, + Jfr: Jfr, + Jopf: Jopf, + Jscr: Jscr, + Jsercy: Jsercy, + Jukcy: Jukcy, + KHcy: KHcy, + KJcy: KJcy, + Kappa: Kappa, + Kcedil: Kcedil, + Kcy: Kcy, + Kfr: Kfr, + Kopf: Kopf, + Kscr: Kscr, + LJcy: LJcy, + L: L, + LT: LT$1, + Lacute: Lacute, + Lambda: Lambda, + Lang: Lang, + Laplacetrf: Laplacetrf, + Larr: Larr, + Lcaron: Lcaron, + Lcedil: Lcedil, + Lcy: Lcy, + LeftAngleBracket: LeftAngleBracket, + LeftArrow: LeftArrow, + LeftArrowBar: LeftArrowBar, + LeftArrowRightArrow: LeftArrowRightArrow, + LeftCeiling: LeftCeiling, + LeftDoubleBracket: LeftDoubleBracket, + LeftDownTeeVector: LeftDownTeeVector, + LeftDownVector: LeftDownVector, + LeftDownVectorBar: LeftDownVectorBar, + LeftFloor: LeftFloor, + LeftRightArrow: LeftRightArrow, + LeftRightVector: LeftRightVector, + LeftTee: LeftTee, + LeftTeeArrow: LeftTeeArrow, + LeftTeeVector: LeftTeeVector, + LeftTriangle: LeftTriangle, + LeftTriangleBar: LeftTriangleBar, + LeftTriangleEqual: LeftTriangleEqual, + LeftUpDownVector: LeftUpDownVector, + LeftUpTeeVector: LeftUpTeeVector, + LeftUpVector: LeftUpVector, + LeftUpVectorBar: LeftUpVectorBar, + LeftVector: LeftVector, + LeftVectorBar: LeftVectorBar, + Leftarrow: Leftarrow, + Leftrightarrow: Leftrightarrow, + LessEqualGreater: LessEqualGreater, + LessFullEqual: LessFullEqual, + LessGreater: LessGreater, + LessLess: LessLess, + LessSlantEqual: LessSlantEqual, + LessTilde: LessTilde, + Lfr: Lfr, + Ll: Ll, + Lleftarrow: Lleftarrow, + Lmidot: Lmidot, + LongLeftArrow: LongLeftArrow, + LongLeftRightArrow: LongLeftRightArrow, + LongRightArrow: LongRightArrow, + Longleftarrow: Longleftarrow, + Longleftrightarrow: Longleftrightarrow, + Longrightarrow: Longrightarrow, + Lopf: Lopf, + LowerLeftArrow: LowerLeftArrow, + LowerRightArrow: LowerRightArrow, + Lscr: Lscr, + Lsh: Lsh, + Lstrok: Lstrok, + Lt: Lt, + "Map": "⤅", + Mcy: Mcy, + MediumSpace: MediumSpace, + Mellintrf: Mellintrf, + Mfr: Mfr, + MinusPlus: MinusPlus, + Mopf: Mopf, + Mscr: Mscr, + Mu: Mu, + NJcy: NJcy, + Nacute: Nacute, + Ncaron: Ncaron, + Ncedil: Ncedil, + Ncy: Ncy, + NegativeMediumSpace: NegativeMediumSpace, + NegativeThickSpace: NegativeThickSpace, + NegativeThinSpace: NegativeThinSpace, + NegativeVeryThinSpace: NegativeVeryThinSpace, + NestedGreaterGreater: NestedGreaterGreater, + NestedLessLess: NestedLessLess, + NewLine: NewLine, + Nfr: Nfr, + NoBreak: NoBreak, + NonBreakingSpace: NonBreakingSpace, + Nopf: Nopf, + Not: Not, + NotCongruent: NotCongruent, + NotCupCap: NotCupCap, + NotDoubleVerticalBar: NotDoubleVerticalBar, + NotElement: NotElement, + NotEqual: NotEqual, + NotEqualTilde: NotEqualTilde, + NotExists: NotExists, + NotGreater: NotGreater, + NotGreaterEqual: NotGreaterEqual, + NotGreaterFullEqual: NotGreaterFullEqual, + NotGreaterGreater: NotGreaterGreater, + NotGreaterLess: NotGreaterLess, + NotGreaterSlantEqual: NotGreaterSlantEqual, + NotGreaterTilde: NotGreaterTilde, + NotHumpDownHump: NotHumpDownHump, + NotHumpEqual: NotHumpEqual, + NotLeftTriangle: NotLeftTriangle, + NotLeftTriangleBar: NotLeftTriangleBar, + NotLeftTriangleEqual: NotLeftTriangleEqual, + NotLess: NotLess, + NotLessEqual: NotLessEqual, + NotLessGreater: NotLessGreater, + NotLessLess: NotLessLess, + NotLessSlantEqual: NotLessSlantEqual, + NotLessTilde: NotLessTilde, + NotNestedGreaterGreater: NotNestedGreaterGreater, + NotNestedLessLess: NotNestedLessLess, + NotPrecedes: NotPrecedes, + NotPrecedesEqual: NotPrecedesEqual, + NotPrecedesSlantEqual: NotPrecedesSlantEqual, + NotReverseElement: NotReverseElement, + NotRightTriangle: NotRightTriangle, + NotRightTriangleBar: NotRightTriangleBar, + NotRightTriangleEqual: NotRightTriangleEqual, + NotSquareSubset: NotSquareSubset, + NotSquareSubsetEqual: NotSquareSubsetEqual, + NotSquareSuperset: NotSquareSuperset, + NotSquareSupersetEqual: NotSquareSupersetEqual, + NotSubset: NotSubset, + NotSubsetEqual: NotSubsetEqual, + NotSucceeds: NotSucceeds, + NotSucceedsEqual: NotSucceedsEqual, + NotSucceedsSlantEqual: NotSucceedsSlantEqual, + NotSucceedsTilde: NotSucceedsTilde, + NotSuperset: NotSuperset, + NotSupersetEqual: NotSupersetEqual, + NotTilde: NotTilde, + NotTildeEqual: NotTildeEqual, + NotTildeFullEqual: NotTildeFullEqual, + NotTildeTilde: NotTildeTilde, + NotVerticalBar: NotVerticalBar, + Nscr: Nscr, + Ntild: Ntild, + Ntilde: Ntilde$1, + Nu: Nu, + OElig: OElig, + Oacut: Oacut, + Oacute: Oacute$1, + Ocir: Ocir, + Ocirc: Ocirc$1, + Ocy: Ocy, + Odblac: Odblac, + Ofr: Ofr, + Ograv: Ograv, + Ograve: Ograve$1, + Omacr: Omacr, + Omega: Omega, + Omicron: Omicron, + Oopf: Oopf, + OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, + OpenCurlyQuote: OpenCurlyQuote, + Or: Or, + Oscr: Oscr, + Oslas: Oslas, + Oslash: Oslash$1, + Otild: Otild, + Otilde: Otilde$1, + Otimes: Otimes, + Oum: Oum, + Ouml: Ouml$1, + OverBar: OverBar, + OverBrace: OverBrace, + OverBracket: OverBracket, + OverParenthesis: OverParenthesis, + PartialD: PartialD, + Pcy: Pcy, + Pfr: Pfr, + Phi: Phi, + Pi: Pi, + PlusMinus: PlusMinus, + Poincareplane: Poincareplane, + Popf: Popf, + Pr: Pr, + Precedes: Precedes, + PrecedesEqual: PrecedesEqual, + PrecedesSlantEqual: PrecedesSlantEqual, + PrecedesTilde: PrecedesTilde, + Prime: Prime, + Product: Product, + Proportion: Proportion, + Proportional: Proportional, + Pscr: Pscr, + Psi: Psi, + QUO: QUO, + QUOT: QUOT$1, + Qfr: Qfr, + Qopf: Qopf, + Qscr: Qscr, + RBarr: RBarr, + RE: RE, + REG: REG$1, + Racute: Racute, + Rang: Rang, + Rarr: Rarr, + Rarrtl: Rarrtl, + Rcaron: Rcaron, + Rcedil: Rcedil, + Rcy: Rcy, + Re: Re, + ReverseElement: ReverseElement, + ReverseEquilibrium: ReverseEquilibrium, + ReverseUpEquilibrium: ReverseUpEquilibrium, + Rfr: Rfr, + Rho: Rho, + RightAngleBracket: RightAngleBracket, + RightArrow: RightArrow, + RightArrowBar: RightArrowBar, + RightArrowLeftArrow: RightArrowLeftArrow, + RightCeiling: RightCeiling, + RightDoubleBracket: RightDoubleBracket, + RightDownTeeVector: RightDownTeeVector, + RightDownVector: RightDownVector, + RightDownVectorBar: RightDownVectorBar, + RightFloor: RightFloor, + RightTee: RightTee, + RightTeeArrow: RightTeeArrow, + RightTeeVector: RightTeeVector, + RightTriangle: RightTriangle, + RightTriangleBar: RightTriangleBar, + RightTriangleEqual: RightTriangleEqual, + RightUpDownVector: RightUpDownVector, + RightUpTeeVector: RightUpTeeVector, + RightUpVector: RightUpVector, + RightUpVectorBar: RightUpVectorBar, + RightVector: RightVector, + RightVectorBar: RightVectorBar, + Rightarrow: Rightarrow, + Ropf: Ropf, + RoundImplies: RoundImplies, + Rrightarrow: Rrightarrow, + Rscr: Rscr, + Rsh: Rsh, + RuleDelayed: RuleDelayed, + SHCHcy: SHCHcy, + SHcy: SHcy, + SOFTcy: SOFTcy, + Sacute: Sacute, + Sc: Sc, + Scaron: Scaron, + Scedil: Scedil, + Scirc: Scirc, + Scy: Scy, + Sfr: Sfr, + ShortDownArrow: ShortDownArrow, + ShortLeftArrow: ShortLeftArrow, + ShortRightArrow: ShortRightArrow, + ShortUpArrow: ShortUpArrow, + Sigma: Sigma, + SmallCircle: SmallCircle, + Sopf: Sopf, + Sqrt: Sqrt, + Square: Square, + SquareIntersection: SquareIntersection, + SquareSubset: SquareSubset, + SquareSubsetEqual: SquareSubsetEqual, + SquareSuperset: SquareSuperset, + SquareSupersetEqual: SquareSupersetEqual, + SquareUnion: SquareUnion, + Sscr: Sscr, + Star: Star, + Sub: Sub, + Subset: Subset, + SubsetEqual: SubsetEqual, + Succeeds: Succeeds, + SucceedsEqual: SucceedsEqual, + SucceedsSlantEqual: SucceedsSlantEqual, + SucceedsTilde: SucceedsTilde, + SuchThat: SuchThat, + Sum: Sum, + Sup: Sup, + Superset: Superset, + SupersetEqual: SupersetEqual, + Supset: Supset, + THOR: THOR, + THORN: THORN$1, + TRADE: TRADE, + TSHcy: TSHcy, + TScy: TScy, + Tab: Tab, + Tau: Tau, + Tcaron: Tcaron, + Tcedil: Tcedil, + Tcy: Tcy, + Tfr: Tfr, + Therefore: Therefore, + Theta: Theta, + ThickSpace: ThickSpace, + ThinSpace: ThinSpace, + Tilde: Tilde, + TildeEqual: TildeEqual, + TildeFullEqual: TildeFullEqual, + TildeTilde: TildeTilde, + Topf: Topf, + TripleDot: TripleDot, + Tscr: Tscr, + Tstrok: Tstrok, + Uacut: Uacut, + Uacute: Uacute$1, + Uarr: Uarr, + Uarrocir: Uarrocir, + Ubrcy: Ubrcy, + Ubreve: Ubreve, + Ucir: Ucir, + Ucirc: Ucirc$1, + Ucy: Ucy, + Udblac: Udblac, + Ufr: Ufr, + Ugrav: Ugrav, + Ugrave: Ugrave$1, + Umacr: Umacr, + UnderBar: UnderBar, + UnderBrace: UnderBrace, + UnderBracket: UnderBracket, + UnderParenthesis: UnderParenthesis, + Union: Union, + UnionPlus: UnionPlus, + Uogon: Uogon, + Uopf: Uopf, + UpArrow: UpArrow, + UpArrowBar: UpArrowBar, + UpArrowDownArrow: UpArrowDownArrow, + UpDownArrow: UpDownArrow, + UpEquilibrium: UpEquilibrium, + UpTee: UpTee, + UpTeeArrow: UpTeeArrow, + Uparrow: Uparrow, + Updownarrow: Updownarrow, + UpperLeftArrow: UpperLeftArrow, + UpperRightArrow: UpperRightArrow, + Upsi: Upsi, + Upsilon: Upsilon, + Uring: Uring, + Uscr: Uscr, + Utilde: Utilde, + Uum: Uum, + Uuml: Uuml$1, + VDash: VDash, + Vbar: Vbar, + Vcy: Vcy, + Vdash: Vdash, + Vdashl: Vdashl, + Vee: Vee, + Verbar: Verbar, + Vert: Vert, + VerticalBar: VerticalBar, + VerticalLine: VerticalLine, + VerticalSeparator: VerticalSeparator, + VerticalTilde: VerticalTilde, + VeryThinSpace: VeryThinSpace, + Vfr: Vfr, + Vopf: Vopf, + Vscr: Vscr, + Vvdash: Vvdash, + Wcirc: Wcirc, + Wedge: Wedge, + Wfr: Wfr, + Wopf: Wopf, + Wscr: Wscr, + Xfr: Xfr, + Xi: Xi, + Xopf: Xopf, + Xscr: Xscr, + YAcy: YAcy, + YIcy: YIcy, + YUcy: YUcy, + Yacut: Yacut, + Yacute: Yacute$1, + Ycirc: Ycirc, + Ycy: Ycy, + Yfr: Yfr, + Yopf: Yopf, + Yscr: Yscr, + Yuml: Yuml, + ZHcy: ZHcy, + Zacute: Zacute, + Zcaron: Zcaron, + Zcy: Zcy, + Zdot: Zdot, + ZeroWidthSpace: ZeroWidthSpace, + Zeta: Zeta, + Zfr: Zfr, + Zopf: Zopf, + Zscr: Zscr, + aacut: aacut, + aacute: aacute$1, + abreve: abreve, + ac: ac, + acE: acE, + acd: acd, + acir: acir, + acirc: acirc$1, + acut: acut, + acute: acute$1, + acy: acy, + aeli: aeli, + aelig: aelig$1, + af: af, + afr: afr, + agrav: agrav, + agrave: agrave$1, + alefsym: alefsym, + aleph: aleph, + alpha: alpha, + amacr: amacr, + amalg: amalg, + am: am, + amp: amp$1, + and: and, + andand: andand, + andd: andd, + andslope: andslope, + andv: andv, + ang: ang, + ange: ange, + angle: angle, + angmsd: angmsd, + angmsdaa: angmsdaa, + angmsdab: angmsdab, + angmsdac: angmsdac, + angmsdad: angmsdad, + angmsdae: angmsdae, + angmsdaf: angmsdaf, + angmsdag: angmsdag, + angmsdah: angmsdah, + angrt: angrt, + angrtvb: angrtvb, + angrtvbd: angrtvbd, + angsph: angsph, + angst: angst, + angzarr: angzarr, + aogon: aogon, + aopf: aopf, + ap: ap, + apE: apE, + apacir: apacir, + ape: ape, + apid: apid, + apos: apos, + approx: approx, + approxeq: approxeq, + arin: arin, + aring: aring$1, + ascr: ascr, + ast: ast, + asymp: asymp, + asympeq: asympeq, + atild: atild, + atilde: atilde$1, + aum: aum, + auml: auml$1, + awconint: awconint, + awint: awint, + bNot: bNot, + backcong: backcong, + backepsilon: backepsilon, + backprime: backprime, + backsim: backsim, + backsimeq: backsimeq, + barvee: barvee, + barwed: barwed, + barwedge: barwedge, + bbrk: bbrk, + bbrktbrk: bbrktbrk, + bcong: bcong, + bcy: bcy, + bdquo: bdquo, + becaus: becaus, + because: because, + bemptyv: bemptyv, + bepsi: bepsi, + bernou: bernou, + beta: beta, + beth: beth, + between: between, + bfr: bfr, + bigcap: bigcap, + bigcirc: bigcirc, + bigcup: bigcup, + bigodot: bigodot, + bigoplus: bigoplus, + bigotimes: bigotimes, + bigsqcup: bigsqcup, + bigstar: bigstar, + bigtriangledown: bigtriangledown, + bigtriangleup: bigtriangleup, + biguplus: biguplus, + bigvee: bigvee, + bigwedge: bigwedge, + bkarow: bkarow, + blacklozenge: blacklozenge, + blacksquare: blacksquare, + blacktriangle: blacktriangle, + blacktriangledown: blacktriangledown, + blacktriangleleft: blacktriangleleft, + blacktriangleright: blacktriangleright, + blank: blank, + blk12: blk12, + blk14: blk14, + blk34: blk34, + block: block, + bne: bne, + bnequiv: bnequiv, + bnot: bnot, + bopf: bopf, + bot: bot, + bottom: bottom, + bowtie: bowtie, + boxDL: boxDL, + boxDR: boxDR, + boxDl: boxDl, + boxDr: boxDr, + boxH: boxH, + boxHD: boxHD, + boxHU: boxHU, + boxHd: boxHd, + boxHu: boxHu, + boxUL: boxUL, + boxUR: boxUR, + boxUl: boxUl, + boxUr: boxUr, + boxV: boxV, + boxVH: boxVH, + boxVL: boxVL, + boxVR: boxVR, + boxVh: boxVh, + boxVl: boxVl, + boxVr: boxVr, + boxbox: boxbox, + boxdL: boxdL, + boxdR: boxdR, + boxdl: boxdl, + boxdr: boxdr, + boxh: boxh, + boxhD: boxhD, + boxhU: boxhU, + boxhd: boxhd, + boxhu: boxhu, + boxminus: boxminus, + boxplus: boxplus, + boxtimes: boxtimes, + boxuL: boxuL, + boxuR: boxuR, + boxul: boxul, + boxur: boxur, + boxv: boxv, + boxvH: boxvH, + boxvL: boxvL, + boxvR: boxvR, + boxvh: boxvh, + boxvl: boxvl, + boxvr: boxvr, + bprime: bprime, + breve: breve, + brvba: brvba, + brvbar: brvbar$1, + bscr: bscr, + bsemi: bsemi, + bsim: bsim, + bsime: bsime, + bsol: bsol, + bsolb: bsolb, + bsolhsub: bsolhsub, + bull: bull, + bullet: bullet, + bump: bump, + bumpE: bumpE, + bumpe: bumpe, + bumpeq: bumpeq, + cacute: cacute, + cap: cap, + capand: capand, + capbrcup: capbrcup, + capcap: capcap, + capcup: capcup, + capdot: capdot, + caps: caps, + caret: caret, + caron: caron, + ccaps: ccaps, + ccaron: ccaron, + ccedi: ccedi, + ccedil: ccedil$1, + ccirc: ccirc, + ccups: ccups, + ccupssm: ccupssm, + cdot: cdot, + cedi: cedi, + cedil: cedil$1, + cemptyv: cemptyv, + cen: cen, + cent: cent$1, + centerdot: centerdot, + cfr: cfr, + chcy: chcy, + check: check$2, + checkmark: checkmark, + chi: chi, + cir: cir, + cirE: cirE, + circ: circ, + circeq: circeq, + circlearrowleft: circlearrowleft, + circlearrowright: circlearrowright, + circledR: circledR, + circledS: circledS, + circledast: circledast, + circledcirc: circledcirc, + circleddash: circleddash, + cire: cire, + cirfnint: cirfnint, + cirmid: cirmid, + cirscir: cirscir, + clubs: clubs, + clubsuit: clubsuit, + colon: colon, + colone: colone, + coloneq: coloneq, + comma: comma, + commat: commat, + comp: comp, + compfn: compfn, + complement: complement, + complexes: complexes, + cong: cong, + congdot: congdot, + conint: conint, + copf: copf, + coprod: coprod, + cop: cop, + copy: copy$2, + copysr: copysr, + crarr: crarr, + cross: cross, + cscr: cscr, + csub: csub, + csube: csube, + csup: csup, + csupe: csupe, + ctdot: ctdot, + cudarrl: cudarrl, + cudarrr: cudarrr, + cuepr: cuepr, + cuesc: cuesc, + cularr: cularr, + cularrp: cularrp, + cup: cup, + cupbrcap: cupbrcap, + cupcap: cupcap, + cupcup: cupcup, + cupdot: cupdot, + cupor: cupor, + cups: cups, + curarr: curarr, + curarrm: curarrm, + curlyeqprec: curlyeqprec, + curlyeqsucc: curlyeqsucc, + curlyvee: curlyvee, + curlywedge: curlywedge, + curre: curre, + curren: curren$1, + curvearrowleft: curvearrowleft, + curvearrowright: curvearrowright, + cuvee: cuvee, + cuwed: cuwed, + cwconint: cwconint, + cwint: cwint, + cylcty: cylcty, + dArr: dArr, + dHar: dHar, + dagger: dagger, + daleth: daleth, + darr: darr, + dash: dash, + dashv: dashv, + dbkarow: dbkarow, + dblac: dblac, + dcaron: dcaron, + dcy: dcy, + dd: dd, + ddagger: ddagger, + ddarr: ddarr, + ddotseq: ddotseq, + de: de, + deg: deg$1, + delta: delta, + demptyv: demptyv, + dfisht: dfisht, + dfr: dfr, + dharl: dharl, + dharr: dharr, + diam: diam, + diamond: diamond, + diamondsuit: diamondsuit, + diams: diams, + die: die, + digamma: digamma, + disin: disin, + div: div, + divid: divid, + divide: divide$1, + divideontimes: divideontimes, + divonx: divonx, + djcy: djcy, + dlcorn: dlcorn, + dlcrop: dlcrop, + dollar: dollar, + dopf: dopf, + dot: dot, + doteq: doteq, + doteqdot: doteqdot, + dotminus: dotminus, + dotplus: dotplus, + dotsquare: dotsquare, + doublebarwedge: doublebarwedge, + downarrow: downarrow, + downdownarrows: downdownarrows, + downharpoonleft: downharpoonleft, + downharpoonright: downharpoonright, + drbkarow: drbkarow, + drcorn: drcorn, + drcrop: drcrop, + dscr: dscr, + dscy: dscy, + dsol: dsol, + dstrok: dstrok, + dtdot: dtdot, + dtri: dtri, + dtrif: dtrif, + duarr: duarr, + duhar: duhar, + dwangle: dwangle, + dzcy: dzcy, + dzigrarr: dzigrarr, + eDDot: eDDot, + eDot: eDot, + eacut: eacut, + eacute: eacute$1, + easter: easter, + ecaron: ecaron, + ecir: ecir, + ecirc: ecirc$1, + ecolon: ecolon, + ecy: ecy, + edot: edot, + ee: ee, + efDot: efDot, + efr: efr, + eg: eg, + egrav: egrav, + egrave: egrave$1, + egs: egs, + egsdot: egsdot, + el: el, + elinters: elinters, + ell: ell, + els: els, + elsdot: elsdot, + emacr: emacr, + empty: empty, + emptyset: emptyset, + emptyv: emptyv, + emsp13: emsp13, + emsp14: emsp14, + emsp: emsp, + eng: eng, + ensp: ensp, + eogon: eogon, + eopf: eopf, + epar: epar, + eparsl: eparsl, + eplus: eplus, + epsi: epsi, + epsilon: epsilon, + epsiv: epsiv, + eqcirc: eqcirc, + eqcolon: eqcolon, + eqsim: eqsim, + eqslantgtr: eqslantgtr, + eqslantless: eqslantless, + equals: equals, + equest: equest, + equiv: equiv, + equivDD: equivDD, + eqvparsl: eqvparsl, + erDot: erDot, + erarr: erarr, + escr: escr, + esdot: esdot, + esim: esim, + eta: eta, + et: et, + eth: eth$1, + eum: eum, + euml: euml$1, + euro: euro, + excl: excl, + exist: exist, + expectation: expectation, + exponentiale: exponentiale, + fallingdotseq: fallingdotseq, + fcy: fcy, + female: female, + ffilig: ffilig, + fflig: fflig, + ffllig: ffllig, + ffr: ffr, + filig: filig, + fjlig: fjlig, + flat: flat, + fllig: fllig, + fltns: fltns, + fnof: fnof, + fopf: fopf, + forall: forall, + fork: fork, + forkv: forkv, + fpartint: fpartint, + frac1: frac1, + frac12: frac12$1, + frac13: frac13, + frac14: frac14$1, + frac15: frac15, + frac16: frac16, + frac18: frac18, + frac23: frac23, + frac25: frac25, + frac3: frac3, + frac34: frac34$1, + frac35: frac35, + frac38: frac38, + frac45: frac45, + frac56: frac56, + frac58: frac58, + frac78: frac78, + frasl: frasl, + frown: frown, + fscr: fscr, + gE: gE, + gEl: gEl, + gacute: gacute, + gamma: gamma, + gammad: gammad, + gap: gap, + gbreve: gbreve, + gcirc: gcirc, + gcy: gcy, + gdot: gdot, + ge: ge, + gel: gel, + geq: geq, + geqq: geqq, + geqslant: geqslant, + ges: ges, + gescc: gescc, + gesdot: gesdot, + gesdoto: gesdoto, + gesdotol: gesdotol, + gesl: gesl, + gesles: gesles, + gfr: gfr, + gg: gg, + ggg: ggg, + gimel: gimel, + gjcy: gjcy, + gl: gl, + glE: glE, + gla: gla, + glj: glj, + gnE: gnE, + gnap: gnap, + gnapprox: gnapprox, + gne: gne, + gneq: gneq, + gneqq: gneqq, + gnsim: gnsim, + gopf: gopf, + grave: grave, + gscr: gscr, + gsim: gsim, + gsime: gsime, + gsiml: gsiml, + g: g, + gt: gt$1, + gtcc: gtcc, + gtcir: gtcir, + gtdot: gtdot, + gtlPar: gtlPar, + gtquest: gtquest, + gtrapprox: gtrapprox, + gtrarr: gtrarr, + gtrdot: gtrdot, + gtreqless: gtreqless, + gtreqqless: gtreqqless, + gtrless: gtrless, + gtrsim: gtrsim, + gvertneqq: gvertneqq, + gvnE: gvnE, + hArr: hArr, + hairsp: hairsp, + half: half, + hamilt: hamilt, + hardcy: hardcy, + harr: harr, + harrcir: harrcir, + harrw: harrw, + hbar: hbar, + hcirc: hcirc, + hearts: hearts, + heartsuit: heartsuit, + hellip: hellip, + hercon: hercon, + hfr: hfr, + hksearow: hksearow, + hkswarow: hkswarow, + hoarr: hoarr, + homtht: homtht, + hookleftarrow: hookleftarrow, + hookrightarrow: hookrightarrow, + hopf: hopf, + horbar: horbar, + hscr: hscr, + hslash: hslash, + hstrok: hstrok, + hybull: hybull, + hyphen: hyphen, + iacut: iacut, + iacute: iacute$1, + ic: ic, + icir: icir, + icirc: icirc$1, + icy: icy, + iecy: iecy, + iexc: iexc, + iexcl: iexcl$1, + iff: iff, + ifr: ifr, + igrav: igrav, + igrave: igrave$1, + ii: ii, + iiiint: iiiint, + iiint: iiint, + iinfin: iinfin, + iiota: iiota, + ijlig: ijlig, + imacr: imacr, + image: image, + imagline: imagline, + imagpart: imagpart, + imath: imath, + imof: imof, + imped: imped, + "in": "∈", + incare: incare, + infin: infin, + infintie: infintie, + inodot: inodot, + int: int, + intcal: intcal, + integers: integers, + intercal: intercal, + intlarhk: intlarhk, + intprod: intprod, + iocy: iocy, + iogon: iogon, + iopf: iopf, + iota: iota, + iprod: iprod, + iques: iques, + iquest: iquest$1, + iscr: iscr, + isin: isin, + isinE: isinE, + isindot: isindot, + isins: isins, + isinsv: isinsv, + isinv: isinv, + it: it, + itilde: itilde, + iukcy: iukcy, + ium: ium, + iuml: iuml$1, + jcirc: jcirc, + jcy: jcy, + jfr: jfr, + jmath: jmath, + jopf: jopf, + jscr: jscr, + jsercy: jsercy, + jukcy: jukcy, + kappa: kappa, + kappav: kappav, + kcedil: kcedil, + kcy: kcy, + kfr: kfr, + kgreen: kgreen, + khcy: khcy, + kjcy: kjcy, + kopf: kopf, + kscr: kscr, + lAarr: lAarr, + lArr: lArr, + lAtail: lAtail, + lBarr: lBarr, + lE: lE, + lEg: lEg, + lHar: lHar, + lacute: lacute, + laemptyv: laemptyv, + lagran: lagran, + lambda: lambda, + lang: lang, + langd: langd, + langle: langle, + lap: lap, + laqu: laqu, + laquo: laquo$1, + larr: larr, + larrb: larrb, + larrbfs: larrbfs, + larrfs: larrfs, + larrhk: larrhk, + larrlp: larrlp, + larrpl: larrpl, + larrsim: larrsim, + larrtl: larrtl, + lat: lat, + latail: latail, + late: late, + lates: lates, + lbarr: lbarr, + lbbrk: lbbrk, + lbrace: lbrace, + lbrack: lbrack, + lbrke: lbrke, + lbrksld: lbrksld, + lbrkslu: lbrkslu, + lcaron: lcaron, + lcedil: lcedil, + lceil: lceil, + lcub: lcub, + lcy: lcy, + ldca: ldca, + ldquo: ldquo, + ldquor: ldquor, + ldrdhar: ldrdhar, + ldrushar: ldrushar, + ldsh: ldsh, + le: le, + leftarrow: leftarrow, + leftarrowtail: leftarrowtail, + leftharpoondown: leftharpoondown, + leftharpoonup: leftharpoonup, + leftleftarrows: leftleftarrows, + leftrightarrow: leftrightarrow, + leftrightarrows: leftrightarrows, + leftrightharpoons: leftrightharpoons, + leftrightsquigarrow: leftrightsquigarrow, + leftthreetimes: leftthreetimes, + leg: leg, + leq: leq, + leqq: leqq, + leqslant: leqslant, + les: les, + lescc: lescc, + lesdot: lesdot, + lesdoto: lesdoto, + lesdotor: lesdotor, + lesg: lesg, + lesges: lesges, + lessapprox: lessapprox, + lessdot: lessdot, + lesseqgtr: lesseqgtr, + lesseqqgtr: lesseqqgtr, + lessgtr: lessgtr, + lesssim: lesssim, + lfisht: lfisht, + lfloor: lfloor, + lfr: lfr, + lg: lg, + lgE: lgE, + lhard: lhard, + lharu: lharu, + lharul: lharul, + lhblk: lhblk, + ljcy: ljcy, + ll: ll, + llarr: llarr, + llcorner: llcorner, + llhard: llhard, + lltri: lltri, + lmidot: lmidot, + lmoust: lmoust, + lmoustache: lmoustache, + lnE: lnE, + lnap: lnap, + lnapprox: lnapprox, + lne: lne, + lneq: lneq, + lneqq: lneqq, + lnsim: lnsim, + loang: loang, + loarr: loarr, + lobrk: lobrk, + longleftarrow: longleftarrow, + longleftrightarrow: longleftrightarrow, + longmapsto: longmapsto, + longrightarrow: longrightarrow, + looparrowleft: looparrowleft, + looparrowright: looparrowright, + lopar: lopar, + lopf: lopf, + loplus: loplus, + lotimes: lotimes, + lowast: lowast, + lowbar: lowbar, + loz: loz, + lozenge: lozenge, + lozf: lozf, + lpar: lpar, + lparlt: lparlt, + lrarr: lrarr, + lrcorner: lrcorner, + lrhar: lrhar, + lrhard: lrhard, + lrm: lrm, + lrtri: lrtri, + lsaquo: lsaquo, + lscr: lscr, + lsh: lsh, + lsim: lsim, + lsime: lsime, + lsimg: lsimg, + lsqb: lsqb, + lsquo: lsquo, + lsquor: lsquor, + lstrok: lstrok, + l: l, + lt: lt$1, + ltcc: ltcc, + ltcir: ltcir, + ltdot: ltdot, + lthree: lthree, + ltimes: ltimes, + ltlarr: ltlarr, + ltquest: ltquest, + ltrPar: ltrPar, + ltri: ltri, + ltrie: ltrie, + ltrif: ltrif, + lurdshar: lurdshar, + luruhar: luruhar, + lvertneqq: lvertneqq, + lvnE: lvnE, + mDDot: mDDot, + mac: mac, + macr: macr$1, + male: male, + malt: malt, + maltese: maltese, + map: map$2, + mapsto: mapsto, + mapstodown: mapstodown, + mapstoleft: mapstoleft, + mapstoup: mapstoup, + marker: marker, + mcomma: mcomma, + mcy: mcy, + mdash: mdash, + measuredangle: measuredangle, + mfr: mfr, + mho: mho, + micr: micr, + micro: micro$1, + mid: mid, + midast: midast, + midcir: midcir, + middo: middo, + middot: middot$1, + minus: minus, + minusb: minusb, + minusd: minusd, + minusdu: minusdu, + mlcp: mlcp, + mldr: mldr, + mnplus: mnplus, + models: models$1, + mopf: mopf, + mp: mp, + mscr: mscr, + mstpos: mstpos, + mu: mu, + multimap: multimap, + mumap: mumap, + nGg: nGg, + nGt: nGt, + nGtv: nGtv, + nLeftarrow: nLeftarrow, + nLeftrightarrow: nLeftrightarrow, + nLl: nLl, + nLt: nLt, + nLtv: nLtv, + nRightarrow: nRightarrow, + nVDash: nVDash, + nVdash: nVdash, + nabla: nabla, + nacute: nacute, + nang: nang, + nap: nap, + napE: napE, + napid: napid, + napos: napos, + napprox: napprox, + natur: natur, + natural: natural, + naturals: naturals, + nbs: nbs, + nbsp: nbsp$1, + nbump: nbump, + nbumpe: nbumpe, + ncap: ncap, + ncaron: ncaron, + ncedil: ncedil, + ncong: ncong, + ncongdot: ncongdot, + ncup: ncup, + ncy: ncy, + ndash: ndash, + ne: ne, + neArr: neArr, + nearhk: nearhk, + nearr: nearr, + nearrow: nearrow, + nedot: nedot, + nequiv: nequiv, + nesear: nesear, + nesim: nesim, + nexist: nexist, + nexists: nexists, + nfr: nfr, + ngE: ngE, + nge: nge, + ngeq: ngeq, + ngeqq: ngeqq, + ngeqslant: ngeqslant, + nges: nges, + ngsim: ngsim, + ngt: ngt, + ngtr: ngtr, + nhArr: nhArr, + nharr: nharr, + nhpar: nhpar, + ni: ni, + nis: nis, + nisd: nisd, + niv: niv, + njcy: njcy, + nlArr: nlArr, + nlE: nlE, + nlarr: nlarr, + nldr: nldr, + nle: nle, + nleftarrow: nleftarrow, + nleftrightarrow: nleftrightarrow, + nleq: nleq, + nleqq: nleqq, + nleqslant: nleqslant, + nles: nles, + nless: nless, + nlsim: nlsim, + nlt: nlt, + nltri: nltri, + nltrie: nltrie, + nmid: nmid, + nopf: nopf, + no: no, + not: not$1, + notin: notin, + notinE: notinE, + notindot: notindot, + notinva: notinva, + notinvb: notinvb, + notinvc: notinvc, + notni: notni, + notniva: notniva, + notnivb: notnivb, + notnivc: notnivc, + npar: npar, + nparallel: nparallel, + nparsl: nparsl, + npart: npart, + npolint: npolint, + npr: npr, + nprcue: nprcue, + npre: npre, + nprec: nprec, + npreceq: npreceq, + nrArr: nrArr, + nrarr: nrarr, + nrarrc: nrarrc, + nrarrw: nrarrw, + nrightarrow: nrightarrow, + nrtri: nrtri, + nrtrie: nrtrie, + nsc: nsc, + nsccue: nsccue, + nsce: nsce, + nscr: nscr, + nshortmid: nshortmid, + nshortparallel: nshortparallel, + nsim: nsim, + nsime: nsime, + nsimeq: nsimeq, + nsmid: nsmid, + nspar: nspar, + nsqsube: nsqsube, + nsqsupe: nsqsupe, + nsub: nsub, + nsubE: nsubE, + nsube: nsube, + nsubset: nsubset, + nsubseteq: nsubseteq, + nsubseteqq: nsubseteqq, + nsucc: nsucc, + nsucceq: nsucceq, + nsup: nsup, + nsupE: nsupE, + nsupe: nsupe, + nsupset: nsupset, + nsupseteq: nsupseteq, + nsupseteqq: nsupseteqq, + ntgl: ntgl, + ntild: ntild, + ntilde: ntilde$1, + ntlg: ntlg, + ntriangleleft: ntriangleleft, + ntrianglelefteq: ntrianglelefteq, + ntriangleright: ntriangleright, + ntrianglerighteq: ntrianglerighteq, + nu: nu, + num: num, + numero: numero, + numsp: numsp, + nvDash: nvDash, + nvHarr: nvHarr, + nvap: nvap, + nvdash: nvdash, + nvge: nvge, + nvgt: nvgt, + nvinfin: nvinfin, + nvlArr: nvlArr, + nvle: nvle, + nvlt: nvlt, + nvltrie: nvltrie, + nvrArr: nvrArr, + nvrtrie: nvrtrie, + nvsim: nvsim, + nwArr: nwArr, + nwarhk: nwarhk, + nwarr: nwarr, + nwarrow: nwarrow, + nwnear: nwnear, + oS: oS, + oacut: oacut, + oacute: oacute$1, + oast: oast, + ocir: ocir, + ocirc: ocirc$1, + ocy: ocy, + odash: odash, + odblac: odblac, + odiv: odiv, + odot: odot, + odsold: odsold, + oelig: oelig, + ofcir: ofcir, + ofr: ofr, + ogon: ogon, + ograv: ograv, + ograve: ograve$1, + ogt: ogt, + ohbar: ohbar, + ohm: ohm, + oint: oint, + olarr: olarr, + olcir: olcir, + olcross: olcross, + oline: oline, + olt: olt, + omacr: omacr, + omega: omega, + omicron: omicron, + omid: omid, + ominus: ominus, + oopf: oopf, + opar: opar, + operp: operp, + oplus: oplus, + or: or, + orarr: orarr, + ord: ord, + order: order$1, + orderof: orderof, + ordf: ordf$1, + ordm: ordm$1, + origof: origof, + oror: oror, + orslope: orslope, + orv: orv, + oscr: oscr, + oslas: oslas, + oslash: oslash$1, + osol: osol, + otild: otild, + otilde: otilde$1, + otimes: otimes, + otimesas: otimesas, + oum: oum, + ouml: ouml$1, + ovbar: ovbar, + par: par, + para: para$1, + parallel: parallel, + parsim: parsim, + parsl: parsl, + part: part, + pcy: pcy, + percnt: percnt, + period: period, + permil: permil, + perp: perp, + pertenk: pertenk, + pfr: pfr, + phi: phi, + phiv: phiv, + phmmat: phmmat, + phone: phone, + pi: pi, + pitchfork: pitchfork, + piv: piv, + planck: planck, + planckh: planckh, + plankv: plankv, + plus: plus, + plusacir: plusacir, + plusb: plusb, + pluscir: pluscir, + plusdo: plusdo, + plusdu: plusdu, + pluse: pluse, + plusm: plusm, + plusmn: plusmn$1, + plussim: plussim, + plustwo: plustwo, + pm: pm, + pointint: pointint, + popf: popf, + poun: poun, + pound: pound$1, + pr: pr, + prE: prE, + prap: prap, + prcue: prcue, + pre: pre, + prec: prec, + precapprox: precapprox, + preccurlyeq: preccurlyeq, + preceq: preceq, + precnapprox: precnapprox, + precneqq: precneqq, + precnsim: precnsim, + precsim: precsim, + prime: prime, + primes: primes, + prnE: prnE, + prnap: prnap, + prnsim: prnsim, + prod: prod, + profalar: profalar, + profline: profline, + profsurf: profsurf, + prop: prop, + propto: propto, + prsim: prsim, + prurel: prurel, + pscr: pscr, + psi: psi, + puncsp: puncsp, + qfr: qfr, + qint: qint, + qopf: qopf, + qprime: qprime, + qscr: qscr, + quaternions: quaternions, + quatint: quatint, + quest: quest, + questeq: questeq, + quo: quo, + quot: quot$1, + rAarr: rAarr, + rArr: rArr, + rAtail: rAtail, + rBarr: rBarr, + rHar: rHar, + race: race, + racute: racute, + radic: radic, + raemptyv: raemptyv, + rang: rang, + rangd: rangd, + range: range$1, + rangle: rangle, + raqu: raqu, + raquo: raquo$1, + rarr: rarr, + rarrap: rarrap, + rarrb: rarrb, + rarrbfs: rarrbfs, + rarrc: rarrc, + rarrfs: rarrfs, + rarrhk: rarrhk, + rarrlp: rarrlp, + rarrpl: rarrpl, + rarrsim: rarrsim, + rarrtl: rarrtl, + rarrw: rarrw, + ratail: ratail, + ratio: ratio, + rationals: rationals, + rbarr: rbarr, + rbbrk: rbbrk, + rbrace: rbrace, + rbrack: rbrack, + rbrke: rbrke, + rbrksld: rbrksld, + rbrkslu: rbrkslu, + rcaron: rcaron, + rcedil: rcedil, + rceil: rceil, + rcub: rcub, + rcy: rcy, + rdca: rdca, + rdldhar: rdldhar, + rdquo: rdquo, + rdquor: rdquor, + rdsh: rdsh, + real: real, + realine: realine, + realpart: realpart, + reals: reals, + rect: rect, + re: re, + reg: reg$1, + rfisht: rfisht, + rfloor: rfloor, + rfr: rfr, + rhard: rhard, + rharu: rharu, + rharul: rharul, + rho: rho, + rhov: rhov, + rightarrow: rightarrow, + rightarrowtail: rightarrowtail, + rightharpoondown: rightharpoondown, + rightharpoonup: rightharpoonup, + rightleftarrows: rightleftarrows, + rightleftharpoons: rightleftharpoons, + rightrightarrows: rightrightarrows, + rightsquigarrow: rightsquigarrow, + rightthreetimes: rightthreetimes, + ring: ring, + risingdotseq: risingdotseq, + rlarr: rlarr, + rlhar: rlhar, + rlm: rlm, + rmoust: rmoust, + rmoustache: rmoustache, + rnmid: rnmid, + roang: roang, + roarr: roarr, + robrk: robrk, + ropar: ropar, + ropf: ropf, + roplus: roplus, + rotimes: rotimes, + rpar: rpar, + rpargt: rpargt, + rppolint: rppolint, + rrarr: rrarr, + rsaquo: rsaquo, + rscr: rscr, + rsh: rsh, + rsqb: rsqb, + rsquo: rsquo, + rsquor: rsquor, + rthree: rthree, + rtimes: rtimes, + rtri: rtri, + rtrie: rtrie, + rtrif: rtrif, + rtriltri: rtriltri, + ruluhar: ruluhar, + rx: rx, + sacute: sacute, + sbquo: sbquo, + sc: sc, + scE: scE, + scap: scap, + scaron: scaron, + sccue: sccue, + sce: sce, + scedil: scedil, + scirc: scirc, + scnE: scnE, + scnap: scnap, + scnsim: scnsim, + scpolint: scpolint, + scsim: scsim, + scy: scy, + sdot: sdot, + sdotb: sdotb, + sdote: sdote, + seArr: seArr, + searhk: searhk, + searr: searr, + searrow: searrow, + sec: sec, + sect: sect$1, + semi: semi, + seswar: seswar, + setminus: setminus, + setmn: setmn, + sext: sext, + sfr: sfr, + sfrown: sfrown, + sharp: sharp, + shchcy: shchcy, + shcy: shcy, + shortmid: shortmid, + shortparallel: shortparallel, + sh: sh, + shy: shy$1, + sigma: sigma, + sigmaf: sigmaf, + sigmav: sigmav, + sim: sim, + simdot: simdot, + sime: sime, + simeq: simeq, + simg: simg, + simgE: simgE, + siml: siml, + simlE: simlE, + simne: simne, + simplus: simplus, + simrarr: simrarr, + slarr: slarr, + smallsetminus: smallsetminus, + smashp: smashp, + smeparsl: smeparsl, + smid: smid, + smile: smile, + smt: smt, + smte: smte, + smtes: smtes, + softcy: softcy, + sol: sol, + solb: solb, + solbar: solbar, + sopf: sopf, + spades: spades, + spadesuit: spadesuit, + spar: spar, + sqcap: sqcap, + sqcaps: sqcaps, + sqcup: sqcup, + sqcups: sqcups, + sqsub: sqsub, + sqsube: sqsube, + sqsubset: sqsubset, + sqsubseteq: sqsubseteq, + sqsup: sqsup, + sqsupe: sqsupe, + sqsupset: sqsupset, + sqsupseteq: sqsupseteq, + squ: squ, + square: square, + squarf: squarf, + squf: squf, + srarr: srarr, + sscr: sscr, + ssetmn: ssetmn, + ssmile: ssmile, + sstarf: sstarf, + star: star$1, + starf: starf, + straightepsilon: straightepsilon, + straightphi: straightphi, + strns: strns, + sub: sub, + subE: subE, + subdot: subdot, + sube: sube, + subedot: subedot, + submult: submult, + subnE: subnE, + subne: subne, + subplus: subplus, + subrarr: subrarr, + subset: subset, + subseteq: subseteq, + subseteqq: subseteqq, + subsetneq: subsetneq, + subsetneqq: subsetneqq, + subsim: subsim, + subsub: subsub, + subsup: subsup, + succ: succ, + succapprox: succapprox, + succcurlyeq: succcurlyeq, + succeq: succeq, + succnapprox: succnapprox, + succneqq: succneqq, + succnsim: succnsim, + succsim: succsim, + sum: sum, + sung: sung, + sup: sup, + sup1: sup1$1, + sup2: sup2$1, + sup3: sup3$1, + supE: supE, + supdot: supdot, + supdsub: supdsub, + supe: supe, + supedot: supedot, + suphsol: suphsol, + suphsub: suphsub, + suplarr: suplarr, + supmult: supmult, + supnE: supnE, + supne: supne, + supplus: supplus, + supset: supset, + supseteq: supseteq, + supseteqq: supseteqq, + supsetneq: supsetneq, + supsetneqq: supsetneqq, + supsim: supsim, + supsub: supsub, + supsup: supsup, + swArr: swArr, + swarhk: swarhk, + swarr: swarr, + swarrow: swarrow, + swnwar: swnwar, + szli: szli, + szlig: szlig$1, + target: target, + tau: tau, + tbrk: tbrk, + tcaron: tcaron, + tcedil: tcedil, + tcy: tcy, + tdot: tdot, + telrec: telrec, + tfr: tfr, + there4: there4, + therefore: therefore, + theta: theta, + thetasym: thetasym, + thetav: thetav, + thickapprox: thickapprox, + thicksim: thicksim, + thinsp: thinsp, + thkap: thkap, + thksim: thksim, + thor: thor, + thorn: thorn$1, + tilde: tilde, + time: time, + times: times$1, + timesb: timesb, + timesbar: timesbar, + timesd: timesd, + tint: tint, + toea: toea, + top: top, + topbot: topbot, + topcir: topcir, + topf: topf, + topfork: topfork, + tosa: tosa, + tprime: tprime, + trade: trade, + triangle: triangle, + triangledown: triangledown, + triangleleft: triangleleft, + trianglelefteq: trianglelefteq, + triangleq: triangleq, + triangleright: triangleright, + trianglerighteq: trianglerighteq, + tridot: tridot, + trie: trie, + triminus: triminus, + triplus: triplus, + trisb: trisb, + tritime: tritime, + trpezium: trpezium, + tscr: tscr, + tscy: tscy, + tshcy: tshcy, + tstrok: tstrok, + twixt: twixt, + twoheadleftarrow: twoheadleftarrow, + twoheadrightarrow: twoheadrightarrow, + uArr: uArr, + uHar: uHar, + uacut: uacut, + uacute: uacute$1, + uarr: uarr, + ubrcy: ubrcy, + ubreve: ubreve, + ucir: ucir, + ucirc: ucirc$1, + ucy: ucy, + udarr: udarr, + udblac: udblac, + udhar: udhar, + ufisht: ufisht, + ufr: ufr, + ugrav: ugrav, + ugrave: ugrave$1, + uharl: uharl, + uharr: uharr, + uhblk: uhblk, + ulcorn: ulcorn, + ulcorner: ulcorner, + ulcrop: ulcrop, + ultri: ultri, + umacr: umacr, + um: um, + uml: uml$1, + uogon: uogon, + uopf: uopf, + uparrow: uparrow, + updownarrow: updownarrow, + upharpoonleft: upharpoonleft, + upharpoonright: upharpoonright, + uplus: uplus, + upsi: upsi, + upsih: upsih, + upsilon: upsilon, + upuparrows: upuparrows, + urcorn: urcorn, + urcorner: urcorner, + urcrop: urcrop, + uring: uring, + urtri: urtri, + uscr: uscr, + utdot: utdot, + utilde: utilde, + utri: utri, + utrif: utrif, + uuarr: uuarr, + uum: uum, + uuml: uuml$1, + uwangle: uwangle, + vArr: vArr, + vBar: vBar, + vBarv: vBarv, + vDash: vDash, + vangrt: vangrt, + varepsilon: varepsilon, + varkappa: varkappa, + varnothing: varnothing, + varphi: varphi, + varpi: varpi, + varpropto: varpropto, + varr: varr, + varrho: varrho, + varsigma: varsigma, + varsubsetneq: varsubsetneq, + varsubsetneqq: varsubsetneqq, + varsupsetneq: varsupsetneq, + varsupsetneqq: varsupsetneqq, + vartheta: vartheta, + vartriangleleft: vartriangleleft, + vartriangleright: vartriangleright, + vcy: vcy, + vdash: vdash, + vee: vee, + veebar: veebar, + veeeq: veeeq, + vellip: vellip, + verbar: verbar, + vert: vert, + vfr: vfr, + vltri: vltri, + vnsub: vnsub, + vnsup: vnsup, + vopf: vopf, + vprop: vprop, + vrtri: vrtri, + vscr: vscr, + vsubnE: vsubnE, + vsubne: vsubne, + vsupnE: vsupnE, + vsupne: vsupne, + vzigzag: vzigzag, + wcirc: wcirc, + wedbar: wedbar, + wedge: wedge, + wedgeq: wedgeq, + weierp: weierp, + wfr: wfr, + wopf: wopf, + wp: wp, + wr: wr, + wreath: wreath, + wscr: wscr, + xcap: xcap, + xcirc: xcirc, + xcup: xcup, + xdtri: xdtri, + xfr: xfr, + xhArr: xhArr, + xharr: xharr, + xi: xi, + xlArr: xlArr, + xlarr: xlarr, + xmap: xmap, + xnis: xnis, + xodot: xodot, + xopf: xopf, + xoplus: xoplus, + xotime: xotime, + xrArr: xrArr, + xrarr: xrarr, + xscr: xscr, + xsqcup: xsqcup, + xuplus: xuplus, + xutri: xutri, + xvee: xvee, + xwedge: xwedge, + yacut: yacut, + yacute: yacute$1, + yacy: yacy, + ycirc: ycirc, + ycy: ycy, + ye: ye, + yen: yen$1, + yfr: yfr, + yicy: yicy, + yopf: yopf, + yscr: yscr, + yucy: yucy, + yum: yum, + yuml: yuml$1, + zacute: zacute, + zcaron: zcaron, + zcy: zcy, + zdot: zdot, + zeetrf: zeetrf, + zeta: zeta, + zfr: zfr, + zhcy: zhcy, + zigrarr: zigrarr, + zopf: zopf, + zscr: zscr, + zwj: zwj, + zwnj: zwnj +}; + +var characterEntities = /*#__PURE__*/Object.freeze({ + __proto__: null, + AEli: AEli, + AElig: AElig$1, + AM: AM, + AMP: AMP$1, + Aacut: Aacut, + Aacute: Aacute$1, + Abreve: Abreve, + Acir: Acir, + Acirc: Acirc$1, + Acy: Acy, + Afr: Afr, + Agrav: Agrav, + Agrave: Agrave$1, + Alpha: Alpha, + Amacr: Amacr, + And: And, + Aogon: Aogon, + Aopf: Aopf, + ApplyFunction: ApplyFunction, + Arin: Arin, + Aring: Aring$1, + Ascr: Ascr, + Assign: Assign, + Atild: Atild, + Atilde: Atilde$1, + Aum: Aum, + Auml: Auml$1, + Backslash: Backslash, + Barv: Barv, + Barwed: Barwed, + Bcy: Bcy, + Because: Because, + Bernoullis: Bernoullis, + Beta: Beta, + Bfr: Bfr, + Bopf: Bopf, + Breve: Breve, + Bscr: Bscr, + Bumpeq: Bumpeq, + CHcy: CHcy, + COP: COP, + COPY: COPY$1, + Cacute: Cacute, + Cap: Cap, + CapitalDifferentialD: CapitalDifferentialD, + Cayleys: Cayleys, + Ccaron: Ccaron, + Ccedi: Ccedi, + Ccedil: Ccedil$1, + Ccirc: Ccirc, + Cconint: Cconint, + Cdot: Cdot, + Cedilla: Cedilla, + CenterDot: CenterDot, + Cfr: Cfr, + Chi: Chi, + CircleDot: CircleDot, + CircleMinus: CircleMinus, + CirclePlus: CirclePlus, + CircleTimes: CircleTimes, + ClockwiseContourIntegral: ClockwiseContourIntegral, + CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, + CloseCurlyQuote: CloseCurlyQuote, + Colon: Colon, + Colone: Colone, + Congruent: Congruent, + Conint: Conint, + ContourIntegral: ContourIntegral, + Copf: Copf, + Coproduct: Coproduct, + CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, + Cross: Cross, + Cscr: Cscr, + Cup: Cup, + CupCap: CupCap, + DD: DD, + DDotrahd: DDotrahd, + DJcy: DJcy, + DScy: DScy, + DZcy: DZcy, + Dagger: Dagger, + Darr: Darr, + Dashv: Dashv, + Dcaron: Dcaron, + Dcy: Dcy, + Del: Del, + Delta: Delta, + Dfr: Dfr, + DiacriticalAcute: DiacriticalAcute, + DiacriticalDot: DiacriticalDot, + DiacriticalDoubleAcute: DiacriticalDoubleAcute, + DiacriticalGrave: DiacriticalGrave, + DiacriticalTilde: DiacriticalTilde, + Diamond: Diamond, + DifferentialD: DifferentialD, + Dopf: Dopf, + Dot: Dot, + DotDot: DotDot, + DotEqual: DotEqual, + DoubleContourIntegral: DoubleContourIntegral, + DoubleDot: DoubleDot, + DoubleDownArrow: DoubleDownArrow, + DoubleLeftArrow: DoubleLeftArrow, + DoubleLeftRightArrow: DoubleLeftRightArrow, + DoubleLeftTee: DoubleLeftTee, + DoubleLongLeftArrow: DoubleLongLeftArrow, + DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, + DoubleLongRightArrow: DoubleLongRightArrow, + DoubleRightArrow: DoubleRightArrow, + DoubleRightTee: DoubleRightTee, + DoubleUpArrow: DoubleUpArrow, + DoubleUpDownArrow: DoubleUpDownArrow, + DoubleVerticalBar: DoubleVerticalBar, + DownArrow: DownArrow, + DownArrowBar: DownArrowBar, + DownArrowUpArrow: DownArrowUpArrow, + DownBreve: DownBreve, + DownLeftRightVector: DownLeftRightVector, + DownLeftTeeVector: DownLeftTeeVector, + DownLeftVector: DownLeftVector, + DownLeftVectorBar: DownLeftVectorBar, + DownRightTeeVector: DownRightTeeVector, + DownRightVector: DownRightVector, + DownRightVectorBar: DownRightVectorBar, + DownTee: DownTee, + DownTeeArrow: DownTeeArrow, + Downarrow: Downarrow, + Dscr: Dscr, + Dstrok: Dstrok, + ENG: ENG, + ET: ET, + ETH: ETH$1, + Eacut: Eacut, + Eacute: Eacute$1, + Ecaron: Ecaron, + Ecir: Ecir, + Ecirc: Ecirc$1, + Ecy: Ecy, + Edot: Edot, + Efr: Efr, + Egrav: Egrav, + Egrave: Egrave$1, + Element: Element, + Emacr: Emacr, + EmptySmallSquare: EmptySmallSquare, + EmptyVerySmallSquare: EmptyVerySmallSquare, + Eogon: Eogon, + Eopf: Eopf, + Epsilon: Epsilon, + Equal: Equal, + EqualTilde: EqualTilde, + Equilibrium: Equilibrium, + Escr: Escr, + Esim: Esim, + Eta: Eta, + Eum: Eum, + Euml: Euml$1, + Exists: Exists, + ExponentialE: ExponentialE, + Fcy: Fcy, + Ffr: Ffr, + FilledSmallSquare: FilledSmallSquare, + FilledVerySmallSquare: FilledVerySmallSquare, + Fopf: Fopf, + ForAll: ForAll, + Fouriertrf: Fouriertrf, + Fscr: Fscr, + GJcy: GJcy, + G: G, + GT: GT$1, + Gamma: Gamma, + Gammad: Gammad, + Gbreve: Gbreve, + Gcedil: Gcedil, + Gcirc: Gcirc, + Gcy: Gcy, + Gdot: Gdot, + Gfr: Gfr, + Gg: Gg, + Gopf: Gopf, + GreaterEqual: GreaterEqual, + GreaterEqualLess: GreaterEqualLess, + GreaterFullEqual: GreaterFullEqual, + GreaterGreater: GreaterGreater, + GreaterLess: GreaterLess, + GreaterSlantEqual: GreaterSlantEqual, + GreaterTilde: GreaterTilde, + Gscr: Gscr, + Gt: Gt, + HARDcy: HARDcy, + Hacek: Hacek, + Hat: Hat, + Hcirc: Hcirc, + Hfr: Hfr, + HilbertSpace: HilbertSpace, + Hopf: Hopf, + HorizontalLine: HorizontalLine, + Hscr: Hscr, + Hstrok: Hstrok, + HumpDownHump: HumpDownHump, + HumpEqual: HumpEqual, + IEcy: IEcy, + IJlig: IJlig, + IOcy: IOcy, + Iacut: Iacut, + Iacute: Iacute$1, + Icir: Icir, + Icirc: Icirc$1, + Icy: Icy, + Idot: Idot, + Ifr: Ifr, + Igrav: Igrav, + Igrave: Igrave$1, + Im: Im, + Imacr: Imacr, + ImaginaryI: ImaginaryI, + Implies: Implies, + Int: Int, + Integral: Integral, + Intersection: Intersection, + InvisibleComma: InvisibleComma, + InvisibleTimes: InvisibleTimes, + Iogon: Iogon, + Iopf: Iopf, + Iota: Iota, + Iscr: Iscr, + Itilde: Itilde, + Iukcy: Iukcy, + Ium: Ium, + Iuml: Iuml$1, + Jcirc: Jcirc, + Jcy: Jcy, + Jfr: Jfr, + Jopf: Jopf, + Jscr: Jscr, + Jsercy: Jsercy, + Jukcy: Jukcy, + KHcy: KHcy, + KJcy: KJcy, + Kappa: Kappa, + Kcedil: Kcedil, + Kcy: Kcy, + Kfr: Kfr, + Kopf: Kopf, + Kscr: Kscr, + LJcy: LJcy, + L: L, + LT: LT$1, + Lacute: Lacute, + Lambda: Lambda, + Lang: Lang, + Laplacetrf: Laplacetrf, + Larr: Larr, + Lcaron: Lcaron, + Lcedil: Lcedil, + Lcy: Lcy, + LeftAngleBracket: LeftAngleBracket, + LeftArrow: LeftArrow, + LeftArrowBar: LeftArrowBar, + LeftArrowRightArrow: LeftArrowRightArrow, + LeftCeiling: LeftCeiling, + LeftDoubleBracket: LeftDoubleBracket, + LeftDownTeeVector: LeftDownTeeVector, + LeftDownVector: LeftDownVector, + LeftDownVectorBar: LeftDownVectorBar, + LeftFloor: LeftFloor, + LeftRightArrow: LeftRightArrow, + LeftRightVector: LeftRightVector, + LeftTee: LeftTee, + LeftTeeArrow: LeftTeeArrow, + LeftTeeVector: LeftTeeVector, + LeftTriangle: LeftTriangle, + LeftTriangleBar: LeftTriangleBar, + LeftTriangleEqual: LeftTriangleEqual, + LeftUpDownVector: LeftUpDownVector, + LeftUpTeeVector: LeftUpTeeVector, + LeftUpVector: LeftUpVector, + LeftUpVectorBar: LeftUpVectorBar, + LeftVector: LeftVector, + LeftVectorBar: LeftVectorBar, + Leftarrow: Leftarrow, + Leftrightarrow: Leftrightarrow, + LessEqualGreater: LessEqualGreater, + LessFullEqual: LessFullEqual, + LessGreater: LessGreater, + LessLess: LessLess, + LessSlantEqual: LessSlantEqual, + LessTilde: LessTilde, + Lfr: Lfr, + Ll: Ll, + Lleftarrow: Lleftarrow, + Lmidot: Lmidot, + LongLeftArrow: LongLeftArrow, + LongLeftRightArrow: LongLeftRightArrow, + LongRightArrow: LongRightArrow, + Longleftarrow: Longleftarrow, + Longleftrightarrow: Longleftrightarrow, + Longrightarrow: Longrightarrow, + Lopf: Lopf, + LowerLeftArrow: LowerLeftArrow, + LowerRightArrow: LowerRightArrow, + Lscr: Lscr, + Lsh: Lsh, + Lstrok: Lstrok, + Lt: Lt, + Mcy: Mcy, + MediumSpace: MediumSpace, + Mellintrf: Mellintrf, + Mfr: Mfr, + MinusPlus: MinusPlus, + Mopf: Mopf, + Mscr: Mscr, + Mu: Mu, + NJcy: NJcy, + Nacute: Nacute, + Ncaron: Ncaron, + Ncedil: Ncedil, + Ncy: Ncy, + NegativeMediumSpace: NegativeMediumSpace, + NegativeThickSpace: NegativeThickSpace, + NegativeThinSpace: NegativeThinSpace, + NegativeVeryThinSpace: NegativeVeryThinSpace, + NestedGreaterGreater: NestedGreaterGreater, + NestedLessLess: NestedLessLess, + NewLine: NewLine, + Nfr: Nfr, + NoBreak: NoBreak, + NonBreakingSpace: NonBreakingSpace, + Nopf: Nopf, + Not: Not, + NotCongruent: NotCongruent, + NotCupCap: NotCupCap, + NotDoubleVerticalBar: NotDoubleVerticalBar, + NotElement: NotElement, + NotEqual: NotEqual, + NotEqualTilde: NotEqualTilde, + NotExists: NotExists, + NotGreater: NotGreater, + NotGreaterEqual: NotGreaterEqual, + NotGreaterFullEqual: NotGreaterFullEqual, + NotGreaterGreater: NotGreaterGreater, + NotGreaterLess: NotGreaterLess, + NotGreaterSlantEqual: NotGreaterSlantEqual, + NotGreaterTilde: NotGreaterTilde, + NotHumpDownHump: NotHumpDownHump, + NotHumpEqual: NotHumpEqual, + NotLeftTriangle: NotLeftTriangle, + NotLeftTriangleBar: NotLeftTriangleBar, + NotLeftTriangleEqual: NotLeftTriangleEqual, + NotLess: NotLess, + NotLessEqual: NotLessEqual, + NotLessGreater: NotLessGreater, + NotLessLess: NotLessLess, + NotLessSlantEqual: NotLessSlantEqual, + NotLessTilde: NotLessTilde, + NotNestedGreaterGreater: NotNestedGreaterGreater, + NotNestedLessLess: NotNestedLessLess, + NotPrecedes: NotPrecedes, + NotPrecedesEqual: NotPrecedesEqual, + NotPrecedesSlantEqual: NotPrecedesSlantEqual, + NotReverseElement: NotReverseElement, + NotRightTriangle: NotRightTriangle, + NotRightTriangleBar: NotRightTriangleBar, + NotRightTriangleEqual: NotRightTriangleEqual, + NotSquareSubset: NotSquareSubset, + NotSquareSubsetEqual: NotSquareSubsetEqual, + NotSquareSuperset: NotSquareSuperset, + NotSquareSupersetEqual: NotSquareSupersetEqual, + NotSubset: NotSubset, + NotSubsetEqual: NotSubsetEqual, + NotSucceeds: NotSucceeds, + NotSucceedsEqual: NotSucceedsEqual, + NotSucceedsSlantEqual: NotSucceedsSlantEqual, + NotSucceedsTilde: NotSucceedsTilde, + NotSuperset: NotSuperset, + NotSupersetEqual: NotSupersetEqual, + NotTilde: NotTilde, + NotTildeEqual: NotTildeEqual, + NotTildeFullEqual: NotTildeFullEqual, + NotTildeTilde: NotTildeTilde, + NotVerticalBar: NotVerticalBar, + Nscr: Nscr, + Ntild: Ntild, + Ntilde: Ntilde$1, + Nu: Nu, + OElig: OElig, + Oacut: Oacut, + Oacute: Oacute$1, + Ocir: Ocir, + Ocirc: Ocirc$1, + Ocy: Ocy, + Odblac: Odblac, + Ofr: Ofr, + Ograv: Ograv, + Ograve: Ograve$1, + Omacr: Omacr, + Omega: Omega, + Omicron: Omicron, + Oopf: Oopf, + OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, + OpenCurlyQuote: OpenCurlyQuote, + Or: Or, + Oscr: Oscr, + Oslas: Oslas, + Oslash: Oslash$1, + Otild: Otild, + Otilde: Otilde$1, + Otimes: Otimes, + Oum: Oum, + Ouml: Ouml$1, + OverBar: OverBar, + OverBrace: OverBrace, + OverBracket: OverBracket, + OverParenthesis: OverParenthesis, + PartialD: PartialD, + Pcy: Pcy, + Pfr: Pfr, + Phi: Phi, + Pi: Pi, + PlusMinus: PlusMinus, + Poincareplane: Poincareplane, + Popf: Popf, + Pr: Pr, + Precedes: Precedes, + PrecedesEqual: PrecedesEqual, + PrecedesSlantEqual: PrecedesSlantEqual, + PrecedesTilde: PrecedesTilde, + Prime: Prime, + Product: Product, + Proportion: Proportion, + Proportional: Proportional, + Pscr: Pscr, + Psi: Psi, + QUO: QUO, + QUOT: QUOT$1, + Qfr: Qfr, + Qopf: Qopf, + Qscr: Qscr, + RBarr: RBarr, + RE: RE, + REG: REG$1, + Racute: Racute, + Rang: Rang, + Rarr: Rarr, + Rarrtl: Rarrtl, + Rcaron: Rcaron, + Rcedil: Rcedil, + Rcy: Rcy, + Re: Re, + ReverseElement: ReverseElement, + ReverseEquilibrium: ReverseEquilibrium, + ReverseUpEquilibrium: ReverseUpEquilibrium, + Rfr: Rfr, + Rho: Rho, + RightAngleBracket: RightAngleBracket, + RightArrow: RightArrow, + RightArrowBar: RightArrowBar, + RightArrowLeftArrow: RightArrowLeftArrow, + RightCeiling: RightCeiling, + RightDoubleBracket: RightDoubleBracket, + RightDownTeeVector: RightDownTeeVector, + RightDownVector: RightDownVector, + RightDownVectorBar: RightDownVectorBar, + RightFloor: RightFloor, + RightTee: RightTee, + RightTeeArrow: RightTeeArrow, + RightTeeVector: RightTeeVector, + RightTriangle: RightTriangle, + RightTriangleBar: RightTriangleBar, + RightTriangleEqual: RightTriangleEqual, + RightUpDownVector: RightUpDownVector, + RightUpTeeVector: RightUpTeeVector, + RightUpVector: RightUpVector, + RightUpVectorBar: RightUpVectorBar, + RightVector: RightVector, + RightVectorBar: RightVectorBar, + Rightarrow: Rightarrow, + Ropf: Ropf, + RoundImplies: RoundImplies, + Rrightarrow: Rrightarrow, + Rscr: Rscr, + Rsh: Rsh, + RuleDelayed: RuleDelayed, + SHCHcy: SHCHcy, + SHcy: SHcy, + SOFTcy: SOFTcy, + Sacute: Sacute, + Sc: Sc, + Scaron: Scaron, + Scedil: Scedil, + Scirc: Scirc, + Scy: Scy, + Sfr: Sfr, + ShortDownArrow: ShortDownArrow, + ShortLeftArrow: ShortLeftArrow, + ShortRightArrow: ShortRightArrow, + ShortUpArrow: ShortUpArrow, + Sigma: Sigma, + SmallCircle: SmallCircle, + Sopf: Sopf, + Sqrt: Sqrt, + Square: Square, + SquareIntersection: SquareIntersection, + SquareSubset: SquareSubset, + SquareSubsetEqual: SquareSubsetEqual, + SquareSuperset: SquareSuperset, + SquareSupersetEqual: SquareSupersetEqual, + SquareUnion: SquareUnion, + Sscr: Sscr, + Star: Star, + Sub: Sub, + Subset: Subset, + SubsetEqual: SubsetEqual, + Succeeds: Succeeds, + SucceedsEqual: SucceedsEqual, + SucceedsSlantEqual: SucceedsSlantEqual, + SucceedsTilde: SucceedsTilde, + SuchThat: SuchThat, + Sum: Sum, + Sup: Sup, + Superset: Superset, + SupersetEqual: SupersetEqual, + Supset: Supset, + THOR: THOR, + THORN: THORN$1, + TRADE: TRADE, + TSHcy: TSHcy, + TScy: TScy, + Tab: Tab, + Tau: Tau, + Tcaron: Tcaron, + Tcedil: Tcedil, + Tcy: Tcy, + Tfr: Tfr, + Therefore: Therefore, + Theta: Theta, + ThickSpace: ThickSpace, + ThinSpace: ThinSpace, + Tilde: Tilde, + TildeEqual: TildeEqual, + TildeFullEqual: TildeFullEqual, + TildeTilde: TildeTilde, + Topf: Topf, + TripleDot: TripleDot, + Tscr: Tscr, + Tstrok: Tstrok, + Uacut: Uacut, + Uacute: Uacute$1, + Uarr: Uarr, + Uarrocir: Uarrocir, + Ubrcy: Ubrcy, + Ubreve: Ubreve, + Ucir: Ucir, + Ucirc: Ucirc$1, + Ucy: Ucy, + Udblac: Udblac, + Ufr: Ufr, + Ugrav: Ugrav, + Ugrave: Ugrave$1, + Umacr: Umacr, + UnderBar: UnderBar, + UnderBrace: UnderBrace, + UnderBracket: UnderBracket, + UnderParenthesis: UnderParenthesis, + Union: Union, + UnionPlus: UnionPlus, + Uogon: Uogon, + Uopf: Uopf, + UpArrow: UpArrow, + UpArrowBar: UpArrowBar, + UpArrowDownArrow: UpArrowDownArrow, + UpDownArrow: UpDownArrow, + UpEquilibrium: UpEquilibrium, + UpTee: UpTee, + UpTeeArrow: UpTeeArrow, + Uparrow: Uparrow, + Updownarrow: Updownarrow, + UpperLeftArrow: UpperLeftArrow, + UpperRightArrow: UpperRightArrow, + Upsi: Upsi, + Upsilon: Upsilon, + Uring: Uring, + Uscr: Uscr, + Utilde: Utilde, + Uum: Uum, + Uuml: Uuml$1, + VDash: VDash, + Vbar: Vbar, + Vcy: Vcy, + Vdash: Vdash, + Vdashl: Vdashl, + Vee: Vee, + Verbar: Verbar, + Vert: Vert, + VerticalBar: VerticalBar, + VerticalLine: VerticalLine, + VerticalSeparator: VerticalSeparator, + VerticalTilde: VerticalTilde, + VeryThinSpace: VeryThinSpace, + Vfr: Vfr, + Vopf: Vopf, + Vscr: Vscr, + Vvdash: Vvdash, + Wcirc: Wcirc, + Wedge: Wedge, + Wfr: Wfr, + Wopf: Wopf, + Wscr: Wscr, + Xfr: Xfr, + Xi: Xi, + Xopf: Xopf, + Xscr: Xscr, + YAcy: YAcy, + YIcy: YIcy, + YUcy: YUcy, + Yacut: Yacut, + Yacute: Yacute$1, + Ycirc: Ycirc, + Ycy: Ycy, + Yfr: Yfr, + Yopf: Yopf, + Yscr: Yscr, + Yuml: Yuml, + ZHcy: ZHcy, + Zacute: Zacute, + Zcaron: Zcaron, + Zcy: Zcy, + Zdot: Zdot, + ZeroWidthSpace: ZeroWidthSpace, + Zeta: Zeta, + Zfr: Zfr, + Zopf: Zopf, + Zscr: Zscr, + aacut: aacut, + aacute: aacute$1, + abreve: abreve, + ac: ac, + acE: acE, + acd: acd, + acir: acir, + acirc: acirc$1, + acut: acut, + acute: acute$1, + acy: acy, + aeli: aeli, + aelig: aelig$1, + af: af, + afr: afr, + agrav: agrav, + agrave: agrave$1, + alefsym: alefsym, + aleph: aleph, + alpha: alpha, + amacr: amacr, + amalg: amalg, + am: am, + amp: amp$1, + and: and, + andand: andand, + andd: andd, + andslope: andslope, + andv: andv, + ang: ang, + ange: ange, + angle: angle, + angmsd: angmsd, + angmsdaa: angmsdaa, + angmsdab: angmsdab, + angmsdac: angmsdac, + angmsdad: angmsdad, + angmsdae: angmsdae, + angmsdaf: angmsdaf, + angmsdag: angmsdag, + angmsdah: angmsdah, + angrt: angrt, + angrtvb: angrtvb, + angrtvbd: angrtvbd, + angsph: angsph, + angst: angst, + angzarr: angzarr, + aogon: aogon, + aopf: aopf, + ap: ap, + apE: apE, + apacir: apacir, + ape: ape, + apid: apid, + apos: apos, + approx: approx, + approxeq: approxeq, + arin: arin, + aring: aring$1, + ascr: ascr, + ast: ast, + asymp: asymp, + asympeq: asympeq, + atild: atild, + atilde: atilde$1, + aum: aum, + auml: auml$1, + awconint: awconint, + awint: awint, + bNot: bNot, + backcong: backcong, + backepsilon: backepsilon, + backprime: backprime, + backsim: backsim, + backsimeq: backsimeq, + barvee: barvee, + barwed: barwed, + barwedge: barwedge, + bbrk: bbrk, + bbrktbrk: bbrktbrk, + bcong: bcong, + bcy: bcy, + bdquo: bdquo, + becaus: becaus, + because: because, + bemptyv: bemptyv, + bepsi: bepsi, + bernou: bernou, + beta: beta, + beth: beth, + between: between, + bfr: bfr, + bigcap: bigcap, + bigcirc: bigcirc, + bigcup: bigcup, + bigodot: bigodot, + bigoplus: bigoplus, + bigotimes: bigotimes, + bigsqcup: bigsqcup, + bigstar: bigstar, + bigtriangledown: bigtriangledown, + bigtriangleup: bigtriangleup, + biguplus: biguplus, + bigvee: bigvee, + bigwedge: bigwedge, + bkarow: bkarow, + blacklozenge: blacklozenge, + blacksquare: blacksquare, + blacktriangle: blacktriangle, + blacktriangledown: blacktriangledown, + blacktriangleleft: blacktriangleleft, + blacktriangleright: blacktriangleright, + blank: blank, + blk12: blk12, + blk14: blk14, + blk34: blk34, + block: block, + bne: bne, + bnequiv: bnequiv, + bnot: bnot, + bopf: bopf, + bot: bot, + bottom: bottom, + bowtie: bowtie, + boxDL: boxDL, + boxDR: boxDR, + boxDl: boxDl, + boxDr: boxDr, + boxH: boxH, + boxHD: boxHD, + boxHU: boxHU, + boxHd: boxHd, + boxHu: boxHu, + boxUL: boxUL, + boxUR: boxUR, + boxUl: boxUl, + boxUr: boxUr, + boxV: boxV, + boxVH: boxVH, + boxVL: boxVL, + boxVR: boxVR, + boxVh: boxVh, + boxVl: boxVl, + boxVr: boxVr, + boxbox: boxbox, + boxdL: boxdL, + boxdR: boxdR, + boxdl: boxdl, + boxdr: boxdr, + boxh: boxh, + boxhD: boxhD, + boxhU: boxhU, + boxhd: boxhd, + boxhu: boxhu, + boxminus: boxminus, + boxplus: boxplus, + boxtimes: boxtimes, + boxuL: boxuL, + boxuR: boxuR, + boxul: boxul, + boxur: boxur, + boxv: boxv, + boxvH: boxvH, + boxvL: boxvL, + boxvR: boxvR, + boxvh: boxvh, + boxvl: boxvl, + boxvr: boxvr, + bprime: bprime, + breve: breve, + brvba: brvba, + brvbar: brvbar$1, + bscr: bscr, + bsemi: bsemi, + bsim: bsim, + bsime: bsime, + bsol: bsol, + bsolb: bsolb, + bsolhsub: bsolhsub, + bull: bull, + bullet: bullet, + bump: bump, + bumpE: bumpE, + bumpe: bumpe, + bumpeq: bumpeq, + cacute: cacute, + cap: cap, + capand: capand, + capbrcup: capbrcup, + capcap: capcap, + capcup: capcup, + capdot: capdot, + caps: caps, + caret: caret, + caron: caron, + ccaps: ccaps, + ccaron: ccaron, + ccedi: ccedi, + ccedil: ccedil$1, + ccirc: ccirc, + ccups: ccups, + ccupssm: ccupssm, + cdot: cdot, + cedi: cedi, + cedil: cedil$1, + cemptyv: cemptyv, + cen: cen, + cent: cent$1, + centerdot: centerdot, + cfr: cfr, + chcy: chcy, + check: check$2, + checkmark: checkmark, + chi: chi, + cir: cir, + cirE: cirE, + circ: circ, + circeq: circeq, + circlearrowleft: circlearrowleft, + circlearrowright: circlearrowright, + circledR: circledR, + circledS: circledS, + circledast: circledast, + circledcirc: circledcirc, + circleddash: circleddash, + cire: cire, + cirfnint: cirfnint, + cirmid: cirmid, + cirscir: cirscir, + clubs: clubs, + clubsuit: clubsuit, + colon: colon, + colone: colone, + coloneq: coloneq, + comma: comma, + commat: commat, + comp: comp, + compfn: compfn, + complement: complement, + complexes: complexes, + cong: cong, + congdot: congdot, + conint: conint, + copf: copf, + coprod: coprod, + cop: cop, + copy: copy$2, + copysr: copysr, + crarr: crarr, + cross: cross, + cscr: cscr, + csub: csub, + csube: csube, + csup: csup, + csupe: csupe, + ctdot: ctdot, + cudarrl: cudarrl, + cudarrr: cudarrr, + cuepr: cuepr, + cuesc: cuesc, + cularr: cularr, + cularrp: cularrp, + cup: cup, + cupbrcap: cupbrcap, + cupcap: cupcap, + cupcup: cupcup, + cupdot: cupdot, + cupor: cupor, + cups: cups, + curarr: curarr, + curarrm: curarrm, + curlyeqprec: curlyeqprec, + curlyeqsucc: curlyeqsucc, + curlyvee: curlyvee, + curlywedge: curlywedge, + curre: curre, + curren: curren$1, + curvearrowleft: curvearrowleft, + curvearrowright: curvearrowright, + cuvee: cuvee, + cuwed: cuwed, + cwconint: cwconint, + cwint: cwint, + cylcty: cylcty, + dArr: dArr, + dHar: dHar, + dagger: dagger, + daleth: daleth, + darr: darr, + dash: dash, + dashv: dashv, + dbkarow: dbkarow, + dblac: dblac, + dcaron: dcaron, + dcy: dcy, + dd: dd, + ddagger: ddagger, + ddarr: ddarr, + ddotseq: ddotseq, + de: de, + deg: deg$1, + delta: delta, + demptyv: demptyv, + dfisht: dfisht, + dfr: dfr, + dharl: dharl, + dharr: dharr, + diam: diam, + diamond: diamond, + diamondsuit: diamondsuit, + diams: diams, + die: die, + digamma: digamma, + disin: disin, + div: div, + divid: divid, + divide: divide$1, + divideontimes: divideontimes, + divonx: divonx, + djcy: djcy, + dlcorn: dlcorn, + dlcrop: dlcrop, + dollar: dollar, + dopf: dopf, + dot: dot, + doteq: doteq, + doteqdot: doteqdot, + dotminus: dotminus, + dotplus: dotplus, + dotsquare: dotsquare, + doublebarwedge: doublebarwedge, + downarrow: downarrow, + downdownarrows: downdownarrows, + downharpoonleft: downharpoonleft, + downharpoonright: downharpoonright, + drbkarow: drbkarow, + drcorn: drcorn, + drcrop: drcrop, + dscr: dscr, + dscy: dscy, + dsol: dsol, + dstrok: dstrok, + dtdot: dtdot, + dtri: dtri, + dtrif: dtrif, + duarr: duarr, + duhar: duhar, + dwangle: dwangle, + dzcy: dzcy, + dzigrarr: dzigrarr, + eDDot: eDDot, + eDot: eDot, + eacut: eacut, + eacute: eacute$1, + easter: easter, + ecaron: ecaron, + ecir: ecir, + ecirc: ecirc$1, + ecolon: ecolon, + ecy: ecy, + edot: edot, + ee: ee, + efDot: efDot, + efr: efr, + eg: eg, + egrav: egrav, + egrave: egrave$1, + egs: egs, + egsdot: egsdot, + el: el, + elinters: elinters, + ell: ell, + els: els, + elsdot: elsdot, + emacr: emacr, + empty: empty, + emptyset: emptyset, + emptyv: emptyv, + emsp13: emsp13, + emsp14: emsp14, + emsp: emsp, + eng: eng, + ensp: ensp, + eogon: eogon, + eopf: eopf, + epar: epar, + eparsl: eparsl, + eplus: eplus, + epsi: epsi, + epsilon: epsilon, + epsiv: epsiv, + eqcirc: eqcirc, + eqcolon: eqcolon, + eqsim: eqsim, + eqslantgtr: eqslantgtr, + eqslantless: eqslantless, + equals: equals, + equest: equest, + equiv: equiv, + equivDD: equivDD, + eqvparsl: eqvparsl, + erDot: erDot, + erarr: erarr, + escr: escr, + esdot: esdot, + esim: esim, + eta: eta, + et: et, + eth: eth$1, + eum: eum, + euml: euml$1, + euro: euro, + excl: excl, + exist: exist, + expectation: expectation, + exponentiale: exponentiale, + fallingdotseq: fallingdotseq, + fcy: fcy, + female: female, + ffilig: ffilig, + fflig: fflig, + ffllig: ffllig, + ffr: ffr, + filig: filig, + fjlig: fjlig, + flat: flat, + fllig: fllig, + fltns: fltns, + fnof: fnof, + fopf: fopf, + forall: forall, + fork: fork, + forkv: forkv, + fpartint: fpartint, + frac1: frac1, + frac12: frac12$1, + frac13: frac13, + frac14: frac14$1, + frac15: frac15, + frac16: frac16, + frac18: frac18, + frac23: frac23, + frac25: frac25, + frac3: frac3, + frac34: frac34$1, + frac35: frac35, + frac38: frac38, + frac45: frac45, + frac56: frac56, + frac58: frac58, + frac78: frac78, + frasl: frasl, + frown: frown, + fscr: fscr, + gE: gE, + gEl: gEl, + gacute: gacute, + gamma: gamma, + gammad: gammad, + gap: gap, + gbreve: gbreve, + gcirc: gcirc, + gcy: gcy, + gdot: gdot, + ge: ge, + gel: gel, + geq: geq, + geqq: geqq, + geqslant: geqslant, + ges: ges, + gescc: gescc, + gesdot: gesdot, + gesdoto: gesdoto, + gesdotol: gesdotol, + gesl: gesl, + gesles: gesles, + gfr: gfr, + gg: gg, + ggg: ggg, + gimel: gimel, + gjcy: gjcy, + gl: gl, + glE: glE, + gla: gla, + glj: glj, + gnE: gnE, + gnap: gnap, + gnapprox: gnapprox, + gne: gne, + gneq: gneq, + gneqq: gneqq, + gnsim: gnsim, + gopf: gopf, + grave: grave, + gscr: gscr, + gsim: gsim, + gsime: gsime, + gsiml: gsiml, + g: g, + gt: gt$1, + gtcc: gtcc, + gtcir: gtcir, + gtdot: gtdot, + gtlPar: gtlPar, + gtquest: gtquest, + gtrapprox: gtrapprox, + gtrarr: gtrarr, + gtrdot: gtrdot, + gtreqless: gtreqless, + gtreqqless: gtreqqless, + gtrless: gtrless, + gtrsim: gtrsim, + gvertneqq: gvertneqq, + gvnE: gvnE, + hArr: hArr, + hairsp: hairsp, + half: half, + hamilt: hamilt, + hardcy: hardcy, + harr: harr, + harrcir: harrcir, + harrw: harrw, + hbar: hbar, + hcirc: hcirc, + hearts: hearts, + heartsuit: heartsuit, + hellip: hellip, + hercon: hercon, + hfr: hfr, + hksearow: hksearow, + hkswarow: hkswarow, + hoarr: hoarr, + homtht: homtht, + hookleftarrow: hookleftarrow, + hookrightarrow: hookrightarrow, + hopf: hopf, + horbar: horbar, + hscr: hscr, + hslash: hslash, + hstrok: hstrok, + hybull: hybull, + hyphen: hyphen, + iacut: iacut, + iacute: iacute$1, + ic: ic, + icir: icir, + icirc: icirc$1, + icy: icy, + iecy: iecy, + iexc: iexc, + iexcl: iexcl$1, + iff: iff, + ifr: ifr, + igrav: igrav, + igrave: igrave$1, + ii: ii, + iiiint: iiiint, + iiint: iiint, + iinfin: iinfin, + iiota: iiota, + ijlig: ijlig, + imacr: imacr, + image: image, + imagline: imagline, + imagpart: imagpart, + imath: imath, + imof: imof, + imped: imped, + incare: incare, + infin: infin, + infintie: infintie, + inodot: inodot, + int: int, + intcal: intcal, + integers: integers, + intercal: intercal, + intlarhk: intlarhk, + intprod: intprod, + iocy: iocy, + iogon: iogon, + iopf: iopf, + iota: iota, + iprod: iprod, + iques: iques, + iquest: iquest$1, + iscr: iscr, + isin: isin, + isinE: isinE, + isindot: isindot, + isins: isins, + isinsv: isinsv, + isinv: isinv, + it: it, + itilde: itilde, + iukcy: iukcy, + ium: ium, + iuml: iuml$1, + jcirc: jcirc, + jcy: jcy, + jfr: jfr, + jmath: jmath, + jopf: jopf, + jscr: jscr, + jsercy: jsercy, + jukcy: jukcy, + kappa: kappa, + kappav: kappav, + kcedil: kcedil, + kcy: kcy, + kfr: kfr, + kgreen: kgreen, + khcy: khcy, + kjcy: kjcy, + kopf: kopf, + kscr: kscr, + lAarr: lAarr, + lArr: lArr, + lAtail: lAtail, + lBarr: lBarr, + lE: lE, + lEg: lEg, + lHar: lHar, + lacute: lacute, + laemptyv: laemptyv, + lagran: lagran, + lambda: lambda, + lang: lang, + langd: langd, + langle: langle, + lap: lap, + laqu: laqu, + laquo: laquo$1, + larr: larr, + larrb: larrb, + larrbfs: larrbfs, + larrfs: larrfs, + larrhk: larrhk, + larrlp: larrlp, + larrpl: larrpl, + larrsim: larrsim, + larrtl: larrtl, + lat: lat, + latail: latail, + late: late, + lates: lates, + lbarr: lbarr, + lbbrk: lbbrk, + lbrace: lbrace, + lbrack: lbrack, + lbrke: lbrke, + lbrksld: lbrksld, + lbrkslu: lbrkslu, + lcaron: lcaron, + lcedil: lcedil, + lceil: lceil, + lcub: lcub, + lcy: lcy, + ldca: ldca, + ldquo: ldquo, + ldquor: ldquor, + ldrdhar: ldrdhar, + ldrushar: ldrushar, + ldsh: ldsh, + le: le, + leftarrow: leftarrow, + leftarrowtail: leftarrowtail, + leftharpoondown: leftharpoondown, + leftharpoonup: leftharpoonup, + leftleftarrows: leftleftarrows, + leftrightarrow: leftrightarrow, + leftrightarrows: leftrightarrows, + leftrightharpoons: leftrightharpoons, + leftrightsquigarrow: leftrightsquigarrow, + leftthreetimes: leftthreetimes, + leg: leg, + leq: leq, + leqq: leqq, + leqslant: leqslant, + les: les, + lescc: lescc, + lesdot: lesdot, + lesdoto: lesdoto, + lesdotor: lesdotor, + lesg: lesg, + lesges: lesges, + lessapprox: lessapprox, + lessdot: lessdot, + lesseqgtr: lesseqgtr, + lesseqqgtr: lesseqqgtr, + lessgtr: lessgtr, + lesssim: lesssim, + lfisht: lfisht, + lfloor: lfloor, + lfr: lfr, + lg: lg, + lgE: lgE, + lhard: lhard, + lharu: lharu, + lharul: lharul, + lhblk: lhblk, + ljcy: ljcy, + ll: ll, + llarr: llarr, + llcorner: llcorner, + llhard: llhard, + lltri: lltri, + lmidot: lmidot, + lmoust: lmoust, + lmoustache: lmoustache, + lnE: lnE, + lnap: lnap, + lnapprox: lnapprox, + lne: lne, + lneq: lneq, + lneqq: lneqq, + lnsim: lnsim, + loang: loang, + loarr: loarr, + lobrk: lobrk, + longleftarrow: longleftarrow, + longleftrightarrow: longleftrightarrow, + longmapsto: longmapsto, + longrightarrow: longrightarrow, + looparrowleft: looparrowleft, + looparrowright: looparrowright, + lopar: lopar, + lopf: lopf, + loplus: loplus, + lotimes: lotimes, + lowast: lowast, + lowbar: lowbar, + loz: loz, + lozenge: lozenge, + lozf: lozf, + lpar: lpar, + lparlt: lparlt, + lrarr: lrarr, + lrcorner: lrcorner, + lrhar: lrhar, + lrhard: lrhard, + lrm: lrm, + lrtri: lrtri, + lsaquo: lsaquo, + lscr: lscr, + lsh: lsh, + lsim: lsim, + lsime: lsime, + lsimg: lsimg, + lsqb: lsqb, + lsquo: lsquo, + lsquor: lsquor, + lstrok: lstrok, + l: l, + lt: lt$1, + ltcc: ltcc, + ltcir: ltcir, + ltdot: ltdot, + lthree: lthree, + ltimes: ltimes, + ltlarr: ltlarr, + ltquest: ltquest, + ltrPar: ltrPar, + ltri: ltri, + ltrie: ltrie, + ltrif: ltrif, + lurdshar: lurdshar, + luruhar: luruhar, + lvertneqq: lvertneqq, + lvnE: lvnE, + mDDot: mDDot, + mac: mac, + macr: macr$1, + male: male, + malt: malt, + maltese: maltese, + map: map$2, + mapsto: mapsto, + mapstodown: mapstodown, + mapstoleft: mapstoleft, + mapstoup: mapstoup, + marker: marker, + mcomma: mcomma, + mcy: mcy, + mdash: mdash, + measuredangle: measuredangle, + mfr: mfr, + mho: mho, + micr: micr, + micro: micro$1, + mid: mid, + midast: midast, + midcir: midcir, + middo: middo, + middot: middot$1, + minus: minus, + minusb: minusb, + minusd: minusd, + minusdu: minusdu, + mlcp: mlcp, + mldr: mldr, + mnplus: mnplus, + models: models$1, + mopf: mopf, + mp: mp, + mscr: mscr, + mstpos: mstpos, + mu: mu, + multimap: multimap, + mumap: mumap, + nGg: nGg, + nGt: nGt, + nGtv: nGtv, + nLeftarrow: nLeftarrow, + nLeftrightarrow: nLeftrightarrow, + nLl: nLl, + nLt: nLt, + nLtv: nLtv, + nRightarrow: nRightarrow, + nVDash: nVDash, + nVdash: nVdash, + nabla: nabla, + nacute: nacute, + nang: nang, + nap: nap, + napE: napE, + napid: napid, + napos: napos, + napprox: napprox, + natur: natur, + natural: natural, + naturals: naturals, + nbs: nbs, + nbsp: nbsp$1, + nbump: nbump, + nbumpe: nbumpe, + ncap: ncap, + ncaron: ncaron, + ncedil: ncedil, + ncong: ncong, + ncongdot: ncongdot, + ncup: ncup, + ncy: ncy, + ndash: ndash, + ne: ne, + neArr: neArr, + nearhk: nearhk, + nearr: nearr, + nearrow: nearrow, + nedot: nedot, + nequiv: nequiv, + nesear: nesear, + nesim: nesim, + nexist: nexist, + nexists: nexists, + nfr: nfr, + ngE: ngE, + nge: nge, + ngeq: ngeq, + ngeqq: ngeqq, + ngeqslant: ngeqslant, + nges: nges, + ngsim: ngsim, + ngt: ngt, + ngtr: ngtr, + nhArr: nhArr, + nharr: nharr, + nhpar: nhpar, + ni: ni, + nis: nis, + nisd: nisd, + niv: niv, + njcy: njcy, + nlArr: nlArr, + nlE: nlE, + nlarr: nlarr, + nldr: nldr, + nle: nle, + nleftarrow: nleftarrow, + nleftrightarrow: nleftrightarrow, + nleq: nleq, + nleqq: nleqq, + nleqslant: nleqslant, + nles: nles, + nless: nless, + nlsim: nlsim, + nlt: nlt, + nltri: nltri, + nltrie: nltrie, + nmid: nmid, + nopf: nopf, + no: no, + not: not$1, + notin: notin, + notinE: notinE, + notindot: notindot, + notinva: notinva, + notinvb: notinvb, + notinvc: notinvc, + notni: notni, + notniva: notniva, + notnivb: notnivb, + notnivc: notnivc, + npar: npar, + nparallel: nparallel, + nparsl: nparsl, + npart: npart, + npolint: npolint, + npr: npr, + nprcue: nprcue, + npre: npre, + nprec: nprec, + npreceq: npreceq, + nrArr: nrArr, + nrarr: nrarr, + nrarrc: nrarrc, + nrarrw: nrarrw, + nrightarrow: nrightarrow, + nrtri: nrtri, + nrtrie: nrtrie, + nsc: nsc, + nsccue: nsccue, + nsce: nsce, + nscr: nscr, + nshortmid: nshortmid, + nshortparallel: nshortparallel, + nsim: nsim, + nsime: nsime, + nsimeq: nsimeq, + nsmid: nsmid, + nspar: nspar, + nsqsube: nsqsube, + nsqsupe: nsqsupe, + nsub: nsub, + nsubE: nsubE, + nsube: nsube, + nsubset: nsubset, + nsubseteq: nsubseteq, + nsubseteqq: nsubseteqq, + nsucc: nsucc, + nsucceq: nsucceq, + nsup: nsup, + nsupE: nsupE, + nsupe: nsupe, + nsupset: nsupset, + nsupseteq: nsupseteq, + nsupseteqq: nsupseteqq, + ntgl: ntgl, + ntild: ntild, + ntilde: ntilde$1, + ntlg: ntlg, + ntriangleleft: ntriangleleft, + ntrianglelefteq: ntrianglelefteq, + ntriangleright: ntriangleright, + ntrianglerighteq: ntrianglerighteq, + nu: nu, + num: num, + numero: numero, + numsp: numsp, + nvDash: nvDash, + nvHarr: nvHarr, + nvap: nvap, + nvdash: nvdash, + nvge: nvge, + nvgt: nvgt, + nvinfin: nvinfin, + nvlArr: nvlArr, + nvle: nvle, + nvlt: nvlt, + nvltrie: nvltrie, + nvrArr: nvrArr, + nvrtrie: nvrtrie, + nvsim: nvsim, + nwArr: nwArr, + nwarhk: nwarhk, + nwarr: nwarr, + nwarrow: nwarrow, + nwnear: nwnear, + oS: oS, + oacut: oacut, + oacute: oacute$1, + oast: oast, + ocir: ocir, + ocirc: ocirc$1, + ocy: ocy, + odash: odash, + odblac: odblac, + odiv: odiv, + odot: odot, + odsold: odsold, + oelig: oelig, + ofcir: ofcir, + ofr: ofr, + ogon: ogon, + ograv: ograv, + ograve: ograve$1, + ogt: ogt, + ohbar: ohbar, + ohm: ohm, + oint: oint, + olarr: olarr, + olcir: olcir, + olcross: olcross, + oline: oline, + olt: olt, + omacr: omacr, + omega: omega, + omicron: omicron, + omid: omid, + ominus: ominus, + oopf: oopf, + opar: opar, + operp: operp, + oplus: oplus, + or: or, + orarr: orarr, + ord: ord, + order: order$1, + orderof: orderof, + ordf: ordf$1, + ordm: ordm$1, + origof: origof, + oror: oror, + orslope: orslope, + orv: orv, + oscr: oscr, + oslas: oslas, + oslash: oslash$1, + osol: osol, + otild: otild, + otilde: otilde$1, + otimes: otimes, + otimesas: otimesas, + oum: oum, + ouml: ouml$1, + ovbar: ovbar, + par: par, + para: para$1, + parallel: parallel, + parsim: parsim, + parsl: parsl, + part: part, + pcy: pcy, + percnt: percnt, + period: period, + permil: permil, + perp: perp, + pertenk: pertenk, + pfr: pfr, + phi: phi, + phiv: phiv, + phmmat: phmmat, + phone: phone, + pi: pi, + pitchfork: pitchfork, + piv: piv, + planck: planck, + planckh: planckh, + plankv: plankv, + plus: plus, + plusacir: plusacir, + plusb: plusb, + pluscir: pluscir, + plusdo: plusdo, + plusdu: plusdu, + pluse: pluse, + plusm: plusm, + plusmn: plusmn$1, + plussim: plussim, + plustwo: plustwo, + pm: pm, + pointint: pointint, + popf: popf, + poun: poun, + pound: pound$1, + pr: pr, + prE: prE, + prap: prap, + prcue: prcue, + pre: pre, + prec: prec, + precapprox: precapprox, + preccurlyeq: preccurlyeq, + preceq: preceq, + precnapprox: precnapprox, + precneqq: precneqq, + precnsim: precnsim, + precsim: precsim, + prime: prime, + primes: primes, + prnE: prnE, + prnap: prnap, + prnsim: prnsim, + prod: prod, + profalar: profalar, + profline: profline, + profsurf: profsurf, + prop: prop, + propto: propto, + prsim: prsim, + prurel: prurel, + pscr: pscr, + psi: psi, + puncsp: puncsp, + qfr: qfr, + qint: qint, + qopf: qopf, + qprime: qprime, + qscr: qscr, + quaternions: quaternions, + quatint: quatint, + quest: quest, + questeq: questeq, + quo: quo, + quot: quot$1, + rAarr: rAarr, + rArr: rArr, + rAtail: rAtail, + rBarr: rBarr, + rHar: rHar, + race: race, + racute: racute, + radic: radic, + raemptyv: raemptyv, + rang: rang, + rangd: rangd, + range: range$1, + rangle: rangle, + raqu: raqu, + raquo: raquo$1, + rarr: rarr, + rarrap: rarrap, + rarrb: rarrb, + rarrbfs: rarrbfs, + rarrc: rarrc, + rarrfs: rarrfs, + rarrhk: rarrhk, + rarrlp: rarrlp, + rarrpl: rarrpl, + rarrsim: rarrsim, + rarrtl: rarrtl, + rarrw: rarrw, + ratail: ratail, + ratio: ratio, + rationals: rationals, + rbarr: rbarr, + rbbrk: rbbrk, + rbrace: rbrace, + rbrack: rbrack, + rbrke: rbrke, + rbrksld: rbrksld, + rbrkslu: rbrkslu, + rcaron: rcaron, + rcedil: rcedil, + rceil: rceil, + rcub: rcub, + rcy: rcy, + rdca: rdca, + rdldhar: rdldhar, + rdquo: rdquo, + rdquor: rdquor, + rdsh: rdsh, + real: real, + realine: realine, + realpart: realpart, + reals: reals, + rect: rect, + re: re, + reg: reg$1, + rfisht: rfisht, + rfloor: rfloor, + rfr: rfr, + rhard: rhard, + rharu: rharu, + rharul: rharul, + rho: rho, + rhov: rhov, + rightarrow: rightarrow, + rightarrowtail: rightarrowtail, + rightharpoondown: rightharpoondown, + rightharpoonup: rightharpoonup, + rightleftarrows: rightleftarrows, + rightleftharpoons: rightleftharpoons, + rightrightarrows: rightrightarrows, + rightsquigarrow: rightsquigarrow, + rightthreetimes: rightthreetimes, + ring: ring, + risingdotseq: risingdotseq, + rlarr: rlarr, + rlhar: rlhar, + rlm: rlm, + rmoust: rmoust, + rmoustache: rmoustache, + rnmid: rnmid, + roang: roang, + roarr: roarr, + robrk: robrk, + ropar: ropar, + ropf: ropf, + roplus: roplus, + rotimes: rotimes, + rpar: rpar, + rpargt: rpargt, + rppolint: rppolint, + rrarr: rrarr, + rsaquo: rsaquo, + rscr: rscr, + rsh: rsh, + rsqb: rsqb, + rsquo: rsquo, + rsquor: rsquor, + rthree: rthree, + rtimes: rtimes, + rtri: rtri, + rtrie: rtrie, + rtrif: rtrif, + rtriltri: rtriltri, + ruluhar: ruluhar, + rx: rx, + sacute: sacute, + sbquo: sbquo, + sc: sc, + scE: scE, + scap: scap, + scaron: scaron, + sccue: sccue, + sce: sce, + scedil: scedil, + scirc: scirc, + scnE: scnE, + scnap: scnap, + scnsim: scnsim, + scpolint: scpolint, + scsim: scsim, + scy: scy, + sdot: sdot, + sdotb: sdotb, + sdote: sdote, + seArr: seArr, + searhk: searhk, + searr: searr, + searrow: searrow, + sec: sec, + sect: sect$1, + semi: semi, + seswar: seswar, + setminus: setminus, + setmn: setmn, + sext: sext, + sfr: sfr, + sfrown: sfrown, + sharp: sharp, + shchcy: shchcy, + shcy: shcy, + shortmid: shortmid, + shortparallel: shortparallel, + sh: sh, + shy: shy$1, + sigma: sigma, + sigmaf: sigmaf, + sigmav: sigmav, + sim: sim, + simdot: simdot, + sime: sime, + simeq: simeq, + simg: simg, + simgE: simgE, + siml: siml, + simlE: simlE, + simne: simne, + simplus: simplus, + simrarr: simrarr, + slarr: slarr, + smallsetminus: smallsetminus, + smashp: smashp, + smeparsl: smeparsl, + smid: smid, + smile: smile, + smt: smt, + smte: smte, + smtes: smtes, + softcy: softcy, + sol: sol, + solb: solb, + solbar: solbar, + sopf: sopf, + spades: spades, + spadesuit: spadesuit, + spar: spar, + sqcap: sqcap, + sqcaps: sqcaps, + sqcup: sqcup, + sqcups: sqcups, + sqsub: sqsub, + sqsube: sqsube, + sqsubset: sqsubset, + sqsubseteq: sqsubseteq, + sqsup: sqsup, + sqsupe: sqsupe, + sqsupset: sqsupset, + sqsupseteq: sqsupseteq, + squ: squ, + square: square, + squarf: squarf, + squf: squf, + srarr: srarr, + sscr: sscr, + ssetmn: ssetmn, + ssmile: ssmile, + sstarf: sstarf, + star: star$1, + starf: starf, + straightepsilon: straightepsilon, + straightphi: straightphi, + strns: strns, + sub: sub, + subE: subE, + subdot: subdot, + sube: sube, + subedot: subedot, + submult: submult, + subnE: subnE, + subne: subne, + subplus: subplus, + subrarr: subrarr, + subset: subset, + subseteq: subseteq, + subseteqq: subseteqq, + subsetneq: subsetneq, + subsetneqq: subsetneqq, + subsim: subsim, + subsub: subsub, + subsup: subsup, + succ: succ, + succapprox: succapprox, + succcurlyeq: succcurlyeq, + succeq: succeq, + succnapprox: succnapprox, + succneqq: succneqq, + succnsim: succnsim, + succsim: succsim, + sum: sum, + sung: sung, + sup: sup, + sup1: sup1$1, + sup2: sup2$1, + sup3: sup3$1, + supE: supE, + supdot: supdot, + supdsub: supdsub, + supe: supe, + supedot: supedot, + suphsol: suphsol, + suphsub: suphsub, + suplarr: suplarr, + supmult: supmult, + supnE: supnE, + supne: supne, + supplus: supplus, + supset: supset, + supseteq: supseteq, + supseteqq: supseteqq, + supsetneq: supsetneq, + supsetneqq: supsetneqq, + supsim: supsim, + supsub: supsub, + supsup: supsup, + swArr: swArr, + swarhk: swarhk, + swarr: swarr, + swarrow: swarrow, + swnwar: swnwar, + szli: szli, + szlig: szlig$1, + target: target, + tau: tau, + tbrk: tbrk, + tcaron: tcaron, + tcedil: tcedil, + tcy: tcy, + tdot: tdot, + telrec: telrec, + tfr: tfr, + there4: there4, + therefore: therefore, + theta: theta, + thetasym: thetasym, + thetav: thetav, + thickapprox: thickapprox, + thicksim: thicksim, + thinsp: thinsp, + thkap: thkap, + thksim: thksim, + thor: thor, + thorn: thorn$1, + tilde: tilde, + time: time, + times: times$1, + timesb: timesb, + timesbar: timesbar, + timesd: timesd, + tint: tint, + toea: toea, + top: top, + topbot: topbot, + topcir: topcir, + topf: topf, + topfork: topfork, + tosa: tosa, + tprime: tprime, + trade: trade, + triangle: triangle, + triangledown: triangledown, + triangleleft: triangleleft, + trianglelefteq: trianglelefteq, + triangleq: triangleq, + triangleright: triangleright, + trianglerighteq: trianglerighteq, + tridot: tridot, + trie: trie, + triminus: triminus, + triplus: triplus, + trisb: trisb, + tritime: tritime, + trpezium: trpezium, + tscr: tscr, + tscy: tscy, + tshcy: tshcy, + tstrok: tstrok, + twixt: twixt, + twoheadleftarrow: twoheadleftarrow, + twoheadrightarrow: twoheadrightarrow, + uArr: uArr, + uHar: uHar, + uacut: uacut, + uacute: uacute$1, + uarr: uarr, + ubrcy: ubrcy, + ubreve: ubreve, + ucir: ucir, + ucirc: ucirc$1, + ucy: ucy, + udarr: udarr, + udblac: udblac, + udhar: udhar, + ufisht: ufisht, + ufr: ufr, + ugrav: ugrav, + ugrave: ugrave$1, + uharl: uharl, + uharr: uharr, + uhblk: uhblk, + ulcorn: ulcorn, + ulcorner: ulcorner, + ulcrop: ulcrop, + ultri: ultri, + umacr: umacr, + um: um, + uml: uml$1, + uogon: uogon, + uopf: uopf, + uparrow: uparrow, + updownarrow: updownarrow, + upharpoonleft: upharpoonleft, + upharpoonright: upharpoonright, + uplus: uplus, + upsi: upsi, + upsih: upsih, + upsilon: upsilon, + upuparrows: upuparrows, + urcorn: urcorn, + urcorner: urcorner, + urcrop: urcrop, + uring: uring, + urtri: urtri, + uscr: uscr, + utdot: utdot, + utilde: utilde, + utri: utri, + utrif: utrif, + uuarr: uuarr, + uum: uum, + uuml: uuml$1, + uwangle: uwangle, + vArr: vArr, + vBar: vBar, + vBarv: vBarv, + vDash: vDash, + vangrt: vangrt, + varepsilon: varepsilon, + varkappa: varkappa, + varnothing: varnothing, + varphi: varphi, + varpi: varpi, + varpropto: varpropto, + varr: varr, + varrho: varrho, + varsigma: varsigma, + varsubsetneq: varsubsetneq, + varsubsetneqq: varsubsetneqq, + varsupsetneq: varsupsetneq, + varsupsetneqq: varsupsetneqq, + vartheta: vartheta, + vartriangleleft: vartriangleleft, + vartriangleright: vartriangleright, + vcy: vcy, + vdash: vdash, + vee: vee, + veebar: veebar, + veeeq: veeeq, + vellip: vellip, + verbar: verbar, + vert: vert, + vfr: vfr, + vltri: vltri, + vnsub: vnsub, + vnsup: vnsup, + vopf: vopf, + vprop: vprop, + vrtri: vrtri, + vscr: vscr, + vsubnE: vsubnE, + vsubne: vsubne, + vsupnE: vsupnE, + vsupne: vsupne, + vzigzag: vzigzag, + wcirc: wcirc, + wedbar: wedbar, + wedge: wedge, + wedgeq: wedgeq, + weierp: weierp, + wfr: wfr, + wopf: wopf, + wp: wp, + wr: wr, + wreath: wreath, + wscr: wscr, + xcap: xcap, + xcirc: xcirc, + xcup: xcup, + xdtri: xdtri, + xfr: xfr, + xhArr: xhArr, + xharr: xharr, + xi: xi, + xlArr: xlArr, + xlarr: xlarr, + xmap: xmap, + xnis: xnis, + xodot: xodot, + xopf: xopf, + xoplus: xoplus, + xotime: xotime, + xrArr: xrArr, + xrarr: xrarr, + xscr: xscr, + xsqcup: xsqcup, + xuplus: xuplus, + xutri: xutri, + xvee: xvee, + xwedge: xwedge, + yacut: yacut, + yacute: yacute$1, + yacy: yacy, + ycirc: ycirc, + ycy: ycy, + ye: ye, + yen: yen$1, + yfr: yfr, + yicy: yicy, + yopf: yopf, + yscr: yscr, + yucy: yucy, + yum: yum, + yuml: yuml$1, + zacute: zacute, + zcaron: zcaron, + zcy: zcy, + zdot: zdot, + zeetrf: zeetrf, + zeta: zeta, + zfr: zfr, + zhcy: zhcy, + zigrarr: zigrarr, + zopf: zopf, + zscr: zscr, + zwj: zwj, + zwnj: zwnj, + 'default': index$3 +}); + +var characterEntities$1 = getCjsExportFromNamespace(characterEntities); + +var decodeEntity_1 = decodeEntity; + +var own$3 = {}.hasOwnProperty; + +function decodeEntity(characters) { + return own$3.call(characterEntities$1, characters) + ? characterEntities$1[characters] + : false +} + +var legacy = getCjsExportFromNamespace(characterEntitiesLegacy); + +var invalid = getCjsExportFromNamespace(characterReferenceInvalid); + +var parseEntities_1 = parseEntities; + +var own$4 = {}.hasOwnProperty; +var fromCharCode = String.fromCharCode; +var noop$2 = Function.prototype; + +// Default settings. +var defaults = { + warning: null, + reference: null, + text: null, + warningContext: null, + referenceContext: null, + textContext: null, + position: {}, + additional: null, + attribute: false, + nonTerminated: true +}; + +// Characters. +var tab = 9; // '\t' +var lineFeed = 10; // '\n' +var formFeed = 12; // '\f' +var space = 32; // ' ' +var ampersand = 38; // '&' +var semicolon = 59; // ';' +var lessThan = 60; // '<' +var equalsTo = 61; // '=' +var numberSign = 35; // '#' +var uppercaseX = 88; // 'X' +var lowercaseX = 120; // 'x' +var replacementCharacter = 65533; // '�' + +// Reference types. +var name = 'named'; +var hexa = 'hexadecimal'; +var deci = 'decimal'; + +// Map of bases. +var bases = {}; + +bases[hexa] = 16; +bases[deci] = 10; + +// Map of types to tests. +// Each type of character reference accepts different characters. +// This test is used to detect whether a reference has ended (as the semicolon +// is not strictly needed). +var tests = {}; + +tests[name] = isAlphanumerical; +tests[deci] = isDecimal; +tests[hexa] = isHexadecimal; + +// Warning types. +var namedNotTerminated = 1; +var numericNotTerminated = 2; +var namedEmpty = 3; +var numericEmpty = 4; +var namedUnknown = 5; +var numericDisallowed = 6; +var numericProhibited = 7; + +// Warning messages. +var messages = {}; + +messages[namedNotTerminated] = + 'Named character references must be terminated by a semicolon'; +messages[numericNotTerminated] = + 'Numeric character references must be terminated by a semicolon'; +messages[namedEmpty] = 'Named character references cannot be empty'; +messages[numericEmpty] = 'Numeric character references cannot be empty'; +messages[namedUnknown] = 'Named character references must be known'; +messages[numericDisallowed] = + 'Numeric character references cannot be disallowed'; +messages[numericProhibited] = + 'Numeric character references cannot be outside the permissible Unicode range'; + +// Wrap to ensure clean parameters are given to `parse`. +function parseEntities(value, options) { + var settings = {}; + var option; + var key; + + if (!options) { + options = {}; + } + + for (key in defaults) { + option = options[key]; + settings[key] = + option === null || option === undefined ? defaults[key] : option; + } + + if (settings.position.indent || settings.position.start) { + settings.indent = settings.position.indent || []; + settings.position = settings.position.start; + } + + return parse$8(value, settings) +} + +// Parse entities. +// eslint-disable-next-line complexity +function parse$8(value, settings) { + var additional = settings.additional; + var nonTerminated = settings.nonTerminated; + var handleText = settings.text; + var handleReference = settings.reference; + var handleWarning = settings.warning; + var textContext = settings.textContext; + var referenceContext = settings.referenceContext; + var warningContext = settings.warningContext; + var pos = settings.position; + var indent = settings.indent || []; + var length = value.length; + var index = 0; + var lines = -1; + var column = pos.column || 1; + var line = pos.line || 1; + var queue = ''; + var result = []; + var entityCharacters; + var namedEntity; + var terminated; + var characters; + var character; + var reference; + var following; + var warning; + var reason; + var output; + var entity; + var begin; + var start; + var type; + var test; + var prev; + var next; + var diff; + var end; + + if (typeof additional === 'string') { + additional = additional.charCodeAt(0); + } + + // Cache the current point. + prev = now(); + + // Wrap `handleWarning`. + warning = handleWarning ? parseError : noop$2; + + // Ensure the algorithm walks over the first character and the end (inclusive). + index--; + length++; + + while (++index < length) { + // If the previous character was a newline. + if (character === lineFeed) { + column = indent[lines] || 1; + } + + character = value.charCodeAt(index); + + if (character === ampersand) { + following = value.charCodeAt(index + 1); + + // The behaviour depends on the identity of the next character. + if ( + following === tab || + following === lineFeed || + following === formFeed || + following === space || + following === ampersand || + following === lessThan || + following !== following || + (additional && following === additional) + ) { + // Not a character reference. + // No characters are consumed, and nothing is returned. + // This is not an error, either. + queue += fromCharCode(character); + column++; + + continue + } + + start = index + 1; + begin = start; + end = start; + + if (following === numberSign) { + // Numerical entity. + end = ++begin; + + // The behaviour further depends on the next character. + following = value.charCodeAt(end); + + if (following === uppercaseX || following === lowercaseX) { + // ASCII hex digits. + type = hexa; + end = ++begin; + } else { + // ASCII digits. + type = deci; + } + } else { + // Named entity. + type = name; + } + + entityCharacters = ''; + entity = ''; + characters = ''; + test = tests[type]; + end--; + + while (++end < length) { + following = value.charCodeAt(end); + + if (!test(following)) { + break + } + + characters += fromCharCode(following); + + // Check if we can match a legacy named reference. + // If so, we cache that as the last viable named reference. + // This ensures we do not need to walk backwards later. + if (type === name && own$4.call(legacy, characters)) { + entityCharacters = characters; + entity = legacy[characters]; + } + } + + terminated = value.charCodeAt(end) === semicolon; + + if (terminated) { + end++; + + namedEntity = type === name ? decodeEntity_1(characters) : false; + + if (namedEntity) { + entityCharacters = characters; + entity = namedEntity; + } + } + + diff = 1 + end - start; + + if (!terminated && !nonTerminated) ; else if (!characters) { + // An empty (possible) entity is valid, unless it’s numeric (thus an + // ampersand followed by an octothorp). + if (type !== name) { + warning(numericEmpty, diff); + } + } else if (type === name) { + // An ampersand followed by anything unknown, and not terminated, is + // invalid. + if (terminated && !entity) { + warning(namedUnknown, 1); + } else { + // If theres something after an entity name which is not known, cap + // the reference. + if (entityCharacters !== characters) { + end = begin + entityCharacters.length; + diff = 1 + end - begin; + terminated = false; + } + + // If the reference is not terminated, warn. + if (!terminated) { + reason = entityCharacters ? namedNotTerminated : namedEmpty; + + if (settings.attribute) { + following = value.charCodeAt(end); + + if (following === equalsTo) { + warning(reason, diff); + entity = null; + } else if (isAlphanumerical(following)) { + entity = null; + } else { + warning(reason, diff); + } + } else { + warning(reason, diff); + } + } + } + + reference = entity; + } else { + if (!terminated) { + // All non-terminated numeric entities are not rendered, and trigger a + // warning. + warning(numericNotTerminated, diff); + } + + // When terminated and number, parse as either hexadecimal or decimal. + reference = parseInt(characters, bases[type]); + + // Trigger a warning when the parsed number is prohibited, and replace + // with replacement character. + if (prohibited(reference)) { + warning(numericProhibited, diff); + reference = fromCharCode(replacementCharacter); + } else if (reference in invalid) { + // Trigger a warning when the parsed number is disallowed, and replace + // by an alternative. + warning(numericDisallowed, diff); + reference = invalid[reference]; + } else { + // Parse the number. + output = ''; + + // Trigger a warning when the parsed number should not be used. + if (disallowed(reference)) { + warning(numericDisallowed, diff); + } + + // Stringify the number. + if (reference > 0xffff) { + reference -= 0x10000; + output += fromCharCode((reference >>> (10 & 0x3ff)) | 0xd800); + reference = 0xdc00 | (reference & 0x3ff); + } + + reference = output + fromCharCode(reference); + } + } + + // Found it! + // First eat the queued characters as normal text, then eat an entity. + if (reference) { + flush(); + + prev = now(); + index = end - 1; + column += end - start + 1; + result.push(reference); + next = now(); + next.offset++; + + if (handleReference) { + handleReference.call( + referenceContext, + reference, + {start: prev, end: next}, + value.slice(start - 1, end) + ); + } + + prev = next; + } else { + // If we could not find a reference, queue the checked characters (as + // normal characters), and move the pointer to their end. + // This is possible because we can be certain neither newlines nor + // ampersands are included. + characters = value.slice(start - 1, end); + queue += characters; + column += characters.length; + index = end - 1; + } + } else { + // Handle anything other than an ampersand, including newlines and EOF. + if ( + character === 10 // Line feed + ) { + line++; + lines++; + column = 0; + } + + if (character === character) { + queue += fromCharCode(character); + column++; + } else { + flush(); + } + } + } + + // Return the reduced nodes, and any possible warnings. + return result.join('') + + // Get current position. + function now() { + return { + line: line, + column: column, + offset: index + (pos.offset || 0) + } + } + + // “Throw” a parse-error: a warning. + function parseError(code, offset) { + var position = now(); + + position.column += offset; + position.offset += offset; + + handleWarning.call(warningContext, messages[code], position, code); + } + + // Flush `queue` (normal text). + // Macro invoked before each entity and at the end of `value`. + // Does nothing when `queue` is empty. + function flush() { + if (queue) { + result.push(queue); + + if (handleText) { + handleText.call(textContext, queue, {start: prev, end: now()}); + } + + queue = ''; + } + } +} + +// Check if `character` is outside the permissible unicode range. +function prohibited(code) { + return (code >= 0xd800 && code <= 0xdfff) || code > 0x10ffff +} + +// Check if `character` is disallowed. +function disallowed(code) { + return ( + (code >= 0x0001 && code <= 0x0008) || + code === 0x000b || + (code >= 0x000d && code <= 0x001f) || + (code >= 0x007f && code <= 0x009f) || + (code >= 0xfdd0 && code <= 0xfdef) || + (code & 0xffff) === 0xffff || + (code & 0xffff) === 0xfffe + ) +} + +var decode = factory$4; + +// Factory to create an entity decoder. +function factory$4(ctx) { + decoder.raw = decodeRaw; + + return decoder + + // Normalize `position` to add an `indent`. + function normalize(position) { + var offsets = ctx.offset; + var line = position.line; + var result = []; + + while (++line) { + if (!(line in offsets)) { + break + } + + result.push((offsets[line] || 0) + 1); + } + + return {start: position, indent: result} + } + + // Decode `value` (at `position`) into text-nodes. + function decoder(value, position, handler) { + parseEntities_1(value, { + position: normalize(position), + warning: handleWarning, + text: handler, + reference: handler, + textContext: ctx, + referenceContext: ctx + }); + } + + // Decode `value` (at `position`) into a string. + function decodeRaw(value, position, options) { + return parseEntities_1( + value, + immutable(options, {position: normalize(position), warning: handleWarning}) + ) + } + + // Handle a warning. + // See for the warnings. + function handleWarning(reason, position, code) { + if (code !== 3) { + ctx.file.message(reason, position); + } + } +} + +var tokenizer = factory$5; + +// Construct a tokenizer. This creates both `tokenizeInline` and `tokenizeBlock`. +function factory$5(type) { + return tokenize + + // Tokenizer for a bound `type`. + function tokenize(value, location) { + var self = this; + var offset = self.offset; + var tokens = []; + var methods = self[type + 'Methods']; + var tokenizers = self[type + 'Tokenizers']; + var line = location.line; + var column = location.column; + var index; + var length; + var method; + var name; + var matched; + var valueLength; + + // Trim white space only lines. + if (!value) { + return tokens + } + + // Expose on `eat`. + eat.now = now; + eat.file = self.file; + + // Sync initial offset. + updatePosition(''); + + // Iterate over `value`, and iterate over all tokenizers. When one eats + // something, re-iterate with the remaining value. If no tokenizer eats, + // something failed (should not happen) and an exception is thrown. + while (value) { + index = -1; + length = methods.length; + matched = false; + + while (++index < length) { + name = methods[index]; + method = tokenizers[name]; + + if ( + method && + /* istanbul ignore next */ (!method.onlyAtStart || self.atStart) && + (!method.notInList || !self.inList) && + (!method.notInBlock || !self.inBlock) && + (!method.notInLink || !self.inLink) + ) { + valueLength = value.length; + + method.apply(self, [eat, value]); + + matched = valueLength !== value.length; + + if (matched) { + break + } + } + } + + /* istanbul ignore if */ + if (!matched) { + self.file.fail(new Error('Infinite loop'), eat.now()); + } + } + + self.eof = now(); + + return tokens + + // Update line, column, and offset based on `value`. + function updatePosition(subvalue) { + var lastIndex = -1; + var index = subvalue.indexOf('\n'); + + while (index !== -1) { + line++; + lastIndex = index; + index = subvalue.indexOf('\n', index + 1); + } + + if (lastIndex === -1) { + column += subvalue.length; + } else { + column = subvalue.length - lastIndex; + } + + if (line in offset) { + if (lastIndex !== -1) { + column += offset[line]; + } else if (column <= offset[line]) { + column = offset[line] + 1; + } + } + } + + // Get offset. Called before the first character is eaten to retrieve the + // range’s offsets. + function getOffset() { + var indentation = []; + var pos = line + 1; + + // Done. Called when the last character is eaten to retrieve the range’s + // offsets. + return function() { + var last = line + 1; + + while (pos < last) { + indentation.push((offset[pos] || 0) + 1); + + pos++; + } + + return indentation + } + } + + // Get the current position. + function now() { + var pos = {line: line, column: column}; + + pos.offset = self.toOffset(pos); + + return pos + } + + // Store position information for a node. + function Position(start) { + this.start = start; + this.end = now(); + } + + // Throw when a value is incorrectly eaten. This shouldn’t happen but will + // throw on new, incorrect rules. + function validateEat(subvalue) { + /* istanbul ignore if */ + if (value.slice(0, subvalue.length) !== subvalue) { + // Capture stack-trace. + self.file.fail( + new Error( + 'Incorrectly eaten value: please report this warning on https://git.io/vg5Ft' + ), + now() + ); + } + } + + // Mark position and patch `node.position`. + function position() { + var before = now(); + + return update + + // Add the position to a node. + function update(node, indent) { + var prev = node.position; + var start = prev ? prev.start : before; + var combined = []; + var n = prev && prev.end.line; + var l = before.line; + + node.position = new Position(start); + + // If there was already a `position`, this node was merged. Fixing + // `start` wasn’t hard, but the indent is different. Especially + // because some information, the indent between `n` and `l` wasn’t + // tracked. Luckily, that space is (should be?) empty, so we can + // safely check for it now. + if (prev && indent && prev.indent) { + combined = prev.indent; + + if (n < l) { + while (++n < l) { + combined.push((offset[n] || 0) + 1); + } + + combined.push(before.column); + } + + indent = combined.concat(indent); + } + + node.position.indent = indent || []; + + return node + } + } + + // Add `node` to `parent`s children or to `tokens`. Performs merges where + // possible. + function add(node, parent) { + var children = parent ? parent.children : tokens; + var prev = children[children.length - 1]; + var fn; + + if ( + prev && + node.type === prev.type && + (node.type === 'text' || node.type === 'blockquote') && + mergeable(prev) && + mergeable(node) + ) { + fn = node.type === 'text' ? mergeText : mergeBlockquote; + node = fn.call(self, prev, node); + } + + if (node !== prev) { + children.push(node); + } + + if (self.atStart && tokens.length !== 0) { + self.exitStart(); + } + + return node + } + + // Remove `subvalue` from `value`. `subvalue` must be at the start of + // `value`. + function eat(subvalue) { + var indent = getOffset(); + var pos = position(); + var current = now(); + + validateEat(subvalue); + + apply.reset = reset; + reset.test = test; + apply.test = test; + + value = value.slice(subvalue.length); + + updatePosition(subvalue); + + indent = indent(); + + return apply + + // Add the given arguments, add `position` to the returned node, and + // return the node. + function apply(node, parent) { + return pos(add(pos(node), parent), indent) + } + + // Functions just like apply, but resets the content: the line and + // column are reversed, and the eaten value is re-added. This is + // useful for nodes with a single type of content, such as lists and + // tables. See `apply` above for what parameters are expected. + function reset() { + var node = apply.apply(null, arguments); + + line = current.line; + column = current.column; + value = subvalue + value; + + return node + } + + // Test the position, after eating, and reverse to a not-eaten state. + function test() { + var result = pos({}); + + line = current.line; + column = current.column; + value = subvalue + value; + + return result.position + } + } + } +} + +// Check whether a node is mergeable with adjacent nodes. +function mergeable(node) { + var start; + var end; + + if (node.type !== 'text' || !node.position) { + return true + } + + start = node.position.start; + end = node.position.end; + + // Only merge nodes which occupy the same size as their `value`. + return ( + start.line !== end.line || end.column - start.column === node.value.length + ) +} + +// Merge two text nodes: `node` into `prev`. +function mergeText(prev, node) { + prev.value += node.value; + + return prev +} + +// Merge two blockquotes: `node` into `prev`, unless in CommonMark or gfm modes. +function mergeBlockquote(prev, node) { + if (this.options.commonmark || this.options.gfm) { + return node + } + + prev.children = prev.children.concat(node.children); + + return prev +} + +var markdownEscapes = escapes; + +var defaults$1 = [ + '\\', + '`', + '*', + '{', + '}', + '[', + ']', + '(', + ')', + '#', + '+', + '-', + '.', + '!', + '_', + '>' +]; + +var gfm = defaults$1.concat(['~', '|']); + +var commonmark = gfm.concat([ + '\n', + '"', + '$', + '%', + '&', + "'", + ',', + '/', + ':', + ';', + '<', + '=', + '?', + '@', + '^' +]); + +escapes.default = defaults$1; +escapes.gfm = gfm; +escapes.commonmark = commonmark; + +// Get markdown escapes. +function escapes(options) { + var settings = options || {}; + + if (settings.commonmark) { + return commonmark + } + + return settings.gfm ? gfm : defaults$1 +} + +var blockElements = [ + 'address', + 'article', + 'aside', + 'base', + 'basefont', + 'blockquote', + 'body', + 'caption', + 'center', + 'col', + 'colgroup', + 'dd', + 'details', + 'dialog', + 'dir', + 'div', + 'dl', + 'dt', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'frame', + 'frameset', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'header', + 'hgroup', + 'hr', + 'html', + 'iframe', + 'legend', + 'li', + 'link', + 'main', + 'menu', + 'menuitem', + 'meta', + 'nav', + 'noframes', + 'ol', + 'optgroup', + 'option', + 'p', + 'param', + 'pre', + 'section', + 'source', + 'title', + 'summary', + 'table', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'title', + 'tr', + 'track', + 'ul' +]; + +var defaults$2 = { + position: true, + gfm: true, + commonmark: false, + footnotes: false, + pedantic: false, + blocks: blockElements +}; + +var setOptions_1 = setOptions; + +function setOptions(options) { + var self = this; + var current = self.options; + var key; + var value; + + if (options == null) { + options = {}; + } else if (typeof options === 'object') { + options = immutable(options); + } else { + throw new Error('Invalid value `' + options + '` for setting `options`') + } + + for (key in defaults$2) { + value = options[key]; + + if (value == null) { + value = current[key]; + } + + if ( + (key !== 'blocks' && typeof value !== 'boolean') || + (key === 'blocks' && typeof value !== 'object') + ) { + throw new Error( + 'Invalid value `' + value + '` for setting `options.' + key + '`' + ) + } + + options[key] = value; + } + + self.options = options; + self.escape = markdownEscapes(options); + + return self +} + +var convert_1 = convert$1; + +function convert$1(test) { + if (typeof test === 'string') { + return typeFactory(test) + } + + if (test === null || test === undefined) { + return ok$1 + } + + if (typeof test === 'object') { + return ('length' in test ? anyFactory : matchesFactory)(test) + } + + if (typeof test === 'function') { + return test + } + + throw new Error('Expected function, string, or object as test') +} + +function convertAll(tests) { + var results = []; + var length = tests.length; + var index = -1; + + while (++index < length) { + results[index] = convert$1(tests[index]); + } + + return results +} + +// Utility assert each property in `test` is represented in `node`, and each +// values are strictly equal. +function matchesFactory(test) { + return matches + + function matches(node) { + var key; + + for (key in test) { + if (node[key] !== test[key]) { + return false + } + } + + return true + } +} + +function anyFactory(tests) { + var checks = convertAll(tests); + var length = checks.length; + + return matches + + function matches() { + var index = -1; + + while (++index < length) { + if (checks[index].apply(this, arguments)) { + return true + } + } + + return false + } +} + +// Utility to convert a string into a function which checks a given node’s type +// for said string. +function typeFactory(test) { + return type + + function type(node) { + return Boolean(node && node.type === test) + } +} + +// Utility to return true. +function ok$1() { + return true +} + +var unistUtilVisitParents = visitParents; + + + +var CONTINUE = true; +var SKIP = 'skip'; +var EXIT = false; + +visitParents.CONTINUE = CONTINUE; +visitParents.SKIP = SKIP; +visitParents.EXIT = EXIT; + +function visitParents(tree, test, visitor, reverse) { + var is; + + if (typeof test === 'function' && typeof visitor !== 'function') { + reverse = visitor; + visitor = test; + test = null; + } + + is = convert_1(test); + + one(tree, null, []); + + // Visit a single node. + function one(node, index, parents) { + var result = []; + var subresult; + + if (!test || is(node, index, parents[parents.length - 1] || null)) { + result = toResult(visitor(node, parents)); + + if (result[0] === EXIT) { + return result + } + } + + if (node.children && result[0] !== SKIP) { + subresult = toResult(all(node.children, parents.concat(node))); + return subresult[0] === EXIT ? subresult : result + } + + return result + } + + // Visit children in `parent`. + function all(children, parents) { + var min = -1; + var step = reverse ? -1 : 1; + var index = (reverse ? children.length : min) + step; + var result; + + while (index > min && index < children.length) { + result = one(children[index], index, parents); + + if (result[0] === EXIT) { + return result + } + + index = typeof result[1] === 'number' ? result[1] : index + step; + } + } +} + +function toResult(value) { + if (value !== null && typeof value === 'object' && 'length' in value) { + return value + } + + if (typeof value === 'number') { + return [CONTINUE, value] + } + + return [value] +} + +var unistUtilVisit = visit; + + + +var CONTINUE$1 = unistUtilVisitParents.CONTINUE; +var SKIP$1 = unistUtilVisitParents.SKIP; +var EXIT$1 = unistUtilVisitParents.EXIT; + +visit.CONTINUE = CONTINUE$1; +visit.SKIP = SKIP$1; +visit.EXIT = EXIT$1; + +function visit(tree, test, visitor, reverse) { + if (typeof test === 'function' && typeof visitor !== 'function') { + reverse = visitor; + visitor = test; + test = null; + } + + unistUtilVisitParents(tree, test, overload, reverse); + + function overload(node, parents) { + var parent = parents[parents.length - 1]; + var index = parent ? parent.children.indexOf(node) : null; + return visitor(node, index, parent) + } +} + +var unistUtilRemovePosition = removePosition; + +function removePosition(node, force) { + unistUtilVisit(node, force ? hard : soft); + return node +} + +function hard(node) { + delete node.position; +} + +function soft(node) { + node.position = undefined; +} + +var parse_1$3 = parse$9; + +var lineFeed$1 = '\n'; +var lineBreaksExpression = /\r\n|\r/g; + +// Parse the bound file. +function parse$9() { + var self = this; + var value = String(self.file); + var start = {line: 1, column: 1, offset: 0}; + var content = immutable(start); + var node; + + // Clean non-unix newlines: `\r\n` and `\r` are all changed to `\n`. + // This should not affect positional information. + value = value.replace(lineBreaksExpression, lineFeed$1); + + // BOM. + if (value.charCodeAt(0) === 0xfeff) { + value = value.slice(1); + + content.column++; + content.offset++; + } + + node = { + type: 'root', + children: self.tokenizeBlock(value, content), + position: {start: start, end: self.eof || immutable(start)} + }; + + if (!self.options.position) { + unistUtilRemovePosition(node, true); + } + + return node +} + +var isWhitespaceCharacter = whitespace; + +var fromCode = String.fromCharCode; +var re$1 = /\s/; + +// Check if the given character code, or the character code at the first +// character, is a whitespace character. +function whitespace(character) { + return re$1.test( + typeof character === 'number' ? fromCode(character) : character.charAt(0) + ) +} + +var newline_1 = newline; + +var lineFeed$2 = '\n'; + +function newline(eat, value, silent) { + var character = value.charAt(0); + var length; + var subvalue; + var queue; + var index; + + if (character !== lineFeed$2) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + index = 1; + length = value.length; + subvalue = character; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + + if (character === lineFeed$2) { + subvalue += queue; + queue = ''; + } + + index++; + } + + eat(subvalue); +} + +var trimTrailingLines_1 = trimTrailingLines; + +var line$1 = '\n'; + +// Remove final newline characters from `value`. +function trimTrailingLines(value) { + var val = String(value); + var index = val.length; + + while (val.charAt(--index) === line$1) { + // Empty + } + + return val.slice(0, index + 1) +} + +var codeIndented = indentedCode; + +var lineFeed$3 = '\n'; +var tab$1 = '\t'; +var space$1 = ' '; + +var tabSize = 4; +var codeIndent = repeatString(space$1, tabSize); + +function indentedCode(eat, value, silent) { + var index = -1; + var length = value.length; + var subvalue = ''; + var content = ''; + var subvalueQueue = ''; + var contentQueue = ''; + var character; + var blankQueue; + var indent; + + while (++index < length) { + character = value.charAt(index); + + if (indent) { + indent = false; + + subvalue += subvalueQueue; + content += contentQueue; + subvalueQueue = ''; + contentQueue = ''; + + if (character === lineFeed$3) { + subvalueQueue = character; + contentQueue = character; + } else { + subvalue += character; + content += character; + + while (++index < length) { + character = value.charAt(index); + + if (!character || character === lineFeed$3) { + contentQueue = character; + subvalueQueue = character; + break + } + + subvalue += character; + content += character; + } + } + } else if ( + character === space$1 && + value.charAt(index + 1) === character && + value.charAt(index + 2) === character && + value.charAt(index + 3) === character + ) { + subvalueQueue += codeIndent; + index += 3; + indent = true; + } else if (character === tab$1) { + subvalueQueue += character; + indent = true; + } else { + blankQueue = ''; + + while (character === tab$1 || character === space$1) { + blankQueue += character; + character = value.charAt(++index); + } + + if (character !== lineFeed$3) { + break + } + + subvalueQueue += blankQueue + character; + contentQueue += character; + } + } + + if (content) { + if (silent) { + return true + } + + return eat(subvalue)({ + type: 'code', + lang: null, + meta: null, + value: trimTrailingLines_1(content) + }) + } +} + +var codeFenced = fencedCode; + +var lineFeed$4 = '\n'; +var tab$2 = '\t'; +var space$2 = ' '; +var tilde$1 = '~'; +var graveAccent = '`'; + +var minFenceCount = 3; +var tabSize$1 = 4; + +function fencedCode(eat, value, silent) { + var self = this; + var gfm = self.options.gfm; + var length = value.length + 1; + var index = 0; + var subvalue = ''; + var fenceCount; + var marker; + var character; + var flag; + var lang; + var meta; + var queue; + var content; + var exdentedContent; + var closing; + var exdentedClosing; + var indent; + var now; + + if (!gfm) { + return + } + + // Eat initial spacing. + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + subvalue += character; + index++; + } + + indent = index; + + // Eat the fence. + character = value.charAt(index); + + if (character !== tilde$1 && character !== graveAccent) { + return + } + + index++; + marker = character; + fenceCount = 1; + subvalue += character; + + while (index < length) { + character = value.charAt(index); + + if (character !== marker) { + break + } + + subvalue += character; + fenceCount++; + index++; + } + + if (fenceCount < minFenceCount) { + return + } + + // Eat spacing before flag. + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + subvalue += character; + index++; + } + + // Eat flag. + flag = ''; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if ( + character === lineFeed$4 || + (marker === graveAccent && character === marker) + ) { + break + } + + if (character === space$2 || character === tab$2) { + queue += character; + } else { + flag += queue + character; + queue = ''; + } + + index++; + } + + character = value.charAt(index); + + if (character && character !== lineFeed$4) { + return + } + + if (silent) { + return true + } + + now = eat.now(); + now.column += subvalue.length; + now.offset += subvalue.length; + + subvalue += flag; + flag = self.decode.raw(self.unescape(flag), now); + + if (queue) { + subvalue += queue; + } + + queue = ''; + closing = ''; + exdentedClosing = ''; + content = ''; + exdentedContent = ''; + var skip = true; + + // Eat content. + while (index < length) { + character = value.charAt(index); + content += closing; + exdentedContent += exdentedClosing; + closing = ''; + exdentedClosing = ''; + + if (character !== lineFeed$4) { + content += character; + exdentedClosing += character; + index++; + continue + } + + // The first line feed is ignored. Others aren’t. + if (skip) { + subvalue += character; + skip = false; + } else { + closing += character; + exdentedClosing += character; + } + + queue = ''; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$2) { + break + } + + queue += character; + index++; + } + + closing += queue; + exdentedClosing += queue.slice(indent); + + if (queue.length >= tabSize$1) { + continue + } + + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== marker) { + break + } + + queue += character; + index++; + } + + closing += queue; + exdentedClosing += queue; + + if (queue.length < fenceCount) { + continue + } + + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + closing += character; + exdentedClosing += character; + index++; + } + + if (!character || character === lineFeed$4) { + break + } + } + + subvalue += content + closing; + + // Get lang and meta from the flag. + index = -1; + length = flag.length; + + while (++index < length) { + character = flag.charAt(index); + + if (character === space$2 || character === tab$2) { + if (!lang) { + lang = flag.slice(0, index); + } + } else if (lang) { + meta = flag.slice(index); + break + } + } + + return eat(subvalue)({ + type: 'code', + lang: lang || flag || null, + meta: meta || null, + value: exdentedContent + }) +} + +var trim_1 = createCommonjsModule(function (module, exports) { +exports = module.exports = trim; + +function trim(str){ + return str.replace(/^\s*|\s*$/g, ''); +} + +exports.left = function(str){ + return str.replace(/^\s*/, ''); +}; + +exports.right = function(str){ + return str.replace(/\s*$/, ''); +}; +}); +var trim_2 = trim_1.left; +var trim_3 = trim_1.right; + +var interrupt_1 = interrupt; + +function interrupt(interruptors, tokenizers, ctx, params) { + var length = interruptors.length; + var index = -1; + var interruptor; + var config; + + while (++index < length) { + interruptor = interruptors[index]; + config = interruptor[1] || {}; + + if ( + config.pedantic !== undefined && + config.pedantic !== ctx.options.pedantic + ) { + continue + } + + if ( + config.commonmark !== undefined && + config.commonmark !== ctx.options.commonmark + ) { + continue + } + + if (tokenizers[interruptor[0]].apply(ctx, params)) { + return true + } + } + + return false +} + +var blockquote_1 = blockquote; + +var lineFeed$5 = '\n'; +var tab$3 = '\t'; +var space$3 = ' '; +var greaterThan = '>'; + +function blockquote(eat, value, silent) { + var self = this; + var offsets = self.offset; + var tokenizers = self.blockTokenizers; + var interruptors = self.interruptBlockquote; + var now = eat.now(); + var currentLine = now.line; + var length = value.length; + var values = []; + var contents = []; + var indents = []; + var add; + var index = 0; + var character; + var rest; + var nextIndex; + var content; + var line; + var startIndex; + var prefixed; + var exit; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$3 && character !== tab$3) { + break + } + + index++; + } + + if (value.charAt(index) !== greaterThan) { + return + } + + if (silent) { + return true + } + + index = 0; + + while (index < length) { + nextIndex = value.indexOf(lineFeed$5, index); + startIndex = index; + prefixed = false; + + if (nextIndex === -1) { + nextIndex = length; + } + + while (index < length) { + character = value.charAt(index); + + if (character !== space$3 && character !== tab$3) { + break + } + + index++; + } + + if (value.charAt(index) === greaterThan) { + index++; + prefixed = true; + + if (value.charAt(index) === space$3) { + index++; + } + } else { + index = startIndex; + } + + content = value.slice(index, nextIndex); + + if (!prefixed && !trim_1(content)) { + index = startIndex; + break + } + + if (!prefixed) { + rest = value.slice(index); + + // Check if the following code contains a possible block. + if (interrupt_1(interruptors, tokenizers, self, [eat, rest, true])) { + break + } + } + + line = startIndex === index ? content : value.slice(startIndex, nextIndex); + + indents.push(index - startIndex); + values.push(line); + contents.push(content); + + index = nextIndex + 1; + } + + index = -1; + length = indents.length; + add = eat(values.join(lineFeed$5)); + + while (++index < length) { + offsets[currentLine] = (offsets[currentLine] || 0) + indents[index]; + currentLine++; + } + + exit = self.enterBlock(); + contents = self.tokenizeBlock(contents.join(lineFeed$5), now); + exit(); + + return add({type: 'blockquote', children: contents}) +} + +var headingAtx = atxHeading; + +var lineFeed$6 = '\n'; +var tab$4 = '\t'; +var space$4 = ' '; +var numberSign$1 = '#'; + +var maxFenceCount = 6; + +function atxHeading(eat, value, silent) { + var self = this; + var pedantic = self.options.pedantic; + var length = value.length + 1; + var index = -1; + var now = eat.now(); + var subvalue = ''; + var content = ''; + var character; + var queue; + var depth; + + // Eat initial spacing. + while (++index < length) { + character = value.charAt(index); + + if (character !== space$4 && character !== tab$4) { + index--; + break + } + + subvalue += character; + } + + // Eat hashes. + depth = 0; + + while (++index <= length) { + character = value.charAt(index); + + if (character !== numberSign$1) { + index--; + break + } + + subvalue += character; + depth++; + } + + if (depth > maxFenceCount) { + return + } + + if (!depth || (!pedantic && value.charAt(index + 1) === numberSign$1)) { + return + } + + length = value.length + 1; + + // Eat intermediate white-space. + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character !== space$4 && character !== tab$4) { + index--; + break + } + + queue += character; + } + + // Exit when not in pedantic mode without spacing. + if (!pedantic && queue.length === 0 && character && character !== lineFeed$6) { + return + } + + if (silent) { + return true + } + + // Eat content. + subvalue += queue; + queue = ''; + content = ''; + + while (++index < length) { + character = value.charAt(index); + + if (!character || character === lineFeed$6) { + break + } + + if (character !== space$4 && character !== tab$4 && character !== numberSign$1) { + content += queue + character; + queue = ''; + continue + } + + while (character === space$4 || character === tab$4) { + queue += character; + character = value.charAt(++index); + } + + // `#` without a queue is part of the content. + if (!pedantic && content && !queue && character === numberSign$1) { + content += character; + continue + } + + while (character === numberSign$1) { + queue += character; + character = value.charAt(++index); + } + + while (character === space$4 || character === tab$4) { + queue += character; + character = value.charAt(++index); + } + + index--; + } + + now.column += subvalue.length; + now.offset += subvalue.length; + subvalue += content + queue; + + return eat(subvalue)({ + type: 'heading', + depth: depth, + children: self.tokenizeInline(content, now) + }) +} + +var thematicBreak_1 = thematicBreak; + +var tab$5 = '\t'; +var lineFeed$7 = '\n'; +var space$5 = ' '; +var asterisk = '*'; +var dash$1 = '-'; +var underscore = '_'; + +var maxCount = 3; + +function thematicBreak(eat, value, silent) { + var index = -1; + var length = value.length + 1; + var subvalue = ''; + var character; + var marker; + var markerCount; + var queue; + + while (++index < length) { + character = value.charAt(index); + + if (character !== tab$5 && character !== space$5) { + break + } + + subvalue += character; + } + + if ( + character !== asterisk && + character !== dash$1 && + character !== underscore + ) { + return + } + + marker = character; + subvalue += character; + markerCount = 1; + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character === marker) { + markerCount++; + subvalue += queue + marker; + queue = ''; + } else if (character === space$5) { + queue += character; + } else if ( + markerCount >= maxCount && + (!character || character === lineFeed$7) + ) { + subvalue += queue; + + if (silent) { + return true + } + + return eat(subvalue)({type: 'thematicBreak'}) + } else { + return + } + } +} + +var getIndentation = indentation; + +var tab$6 = '\t'; +var space$6 = ' '; + +var spaceSize = 1; +var tabSize$2 = 4; + +// Gets indentation information for a line. +function indentation(value) { + var index = 0; + var indent = 0; + var character = value.charAt(index); + var stops = {}; + var size; + + while (character === tab$6 || character === space$6) { + size = character === tab$6 ? tabSize$2 : spaceSize; + + indent += size; + + if (size > 1) { + indent = Math.floor(indent / size) * size; + } + + stops[indent] = index; + character = value.charAt(++index); + } + + return {indent: indent, stops: stops} +} + +var removeIndentation = indentation$1; + +var tab$7 = '\t'; +var lineFeed$8 = '\n'; +var space$7 = ' '; +var exclamationMark = '!'; + +// Remove the minimum indent from every line in `value`. Supports both tab, +// spaced, and mixed indentation (as well as possible). +function indentation$1(value, maximum) { + var values = value.split(lineFeed$8); + var position = values.length + 1; + var minIndent = Infinity; + var matrix = []; + var index; + var indentation; + var stops; + var padding; + + values.unshift(repeatString(space$7, maximum) + exclamationMark); + + while (position--) { + indentation = getIndentation(values[position]); + + matrix[position] = indentation.stops; + + if (trim_1(values[position]).length === 0) { + continue + } + + if (indentation.indent) { + if (indentation.indent > 0 && indentation.indent < minIndent) { + minIndent = indentation.indent; + } + } else { + minIndent = Infinity; + + break + } + } + + if (minIndent !== Infinity) { + position = values.length; + + while (position--) { + stops = matrix[position]; + index = minIndent; + + while (index && !(index in stops)) { + index--; + } + + if ( + trim_1(values[position]).length !== 0 && + minIndent && + index !== minIndent + ) { + padding = tab$7; + } else { + padding = ''; + } + + values[position] = + padding + values[position].slice(index in stops ? stops[index] + 1 : 0); + } + } + + values.shift(); + + return values.join(lineFeed$8) +} + +var list_1 = list; + +var asterisk$1 = '*'; +var underscore$1 = '_'; +var plusSign = '+'; +var dash$2 = '-'; +var dot$1 = '.'; +var space$8 = ' '; +var lineFeed$9 = '\n'; +var tab$8 = '\t'; +var rightParenthesis = ')'; +var lowercaseX$1 = 'x'; + +var tabSize$3 = 4; +var looseListItemExpression = /\n\n(?!\s*$)/; +var taskItemExpression = /^\[([ \t]|x|X)][ \t]/; +var bulletExpression = /^([ \t]*)([*+-]|\d+[.)])( {1,4}(?! )| |\t|$|(?=\n))([^\n]*)/; +var pedanticBulletExpression = /^([ \t]*)([*+-]|\d+[.)])([ \t]+)/; +var initialIndentExpression = /^( {1,4}|\t)?/gm; + +function list(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var pedantic = self.options.pedantic; + var tokenizers = self.blockTokenizers; + var interuptors = self.interruptList; + var index = 0; + var length = value.length; + var start = null; + var size = 0; + var queue; + var ordered; + var character; + var marker; + var nextIndex; + var startIndex; + var prefixed; + var currentMarker; + var content; + var line; + var prevEmpty; + var empty; + var items; + var allLines; + var emptyLines; + var item; + var enterTop; + var exitBlockquote; + var spread = false; + var node; + var now; + var end; + var indented; + + while (index < length) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + } else if (character === space$8) { + size++; + } else { + break + } + + index++; + } + + if (size >= tabSize$3) { + return + } + + character = value.charAt(index); + + if (character === asterisk$1 || character === plusSign || character === dash$2) { + marker = character; + ordered = false; + } else { + ordered = true; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isDecimal(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if ( + !queue || + !(character === dot$1 || (commonmark && character === rightParenthesis)) + ) { + return + } + + start = parseInt(queue, 10); + marker = character; + } + + character = value.charAt(++index); + + if ( + character !== space$8 && + character !== tab$8 && + (pedantic || (character !== lineFeed$9 && character !== '')) + ) { + return + } + + if (silent) { + return true + } + + index = 0; + items = []; + allLines = []; + emptyLines = []; + + while (index < length) { + nextIndex = value.indexOf(lineFeed$9, index); + startIndex = index; + prefixed = false; + indented = false; + + if (nextIndex === -1) { + nextIndex = length; + } + + end = index + tabSize$3; + size = 0; + + while (index < length) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + } else if (character === space$8) { + size++; + } else { + break + } + + index++; + } + + if (size >= tabSize$3) { + indented = true; + } + + if (item && size >= item.indent) { + indented = true; + } + + character = value.charAt(index); + currentMarker = null; + + if (!indented) { + if ( + character === asterisk$1 || + character === plusSign || + character === dash$2 + ) { + currentMarker = character; + index++; + size++; + } else { + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isDecimal(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + index++; + + if ( + queue && + (character === dot$1 || (commonmark && character === rightParenthesis)) + ) { + currentMarker = character; + size += queue.length + 1; + } + } + + if (currentMarker) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + index++; + } else if (character === space$8) { + end = index + tabSize$3; + + while (index < end) { + if (value.charAt(index) !== space$8) { + break + } + + index++; + size++; + } + + if (index === end && value.charAt(index) === space$8) { + index -= tabSize$3 - 1; + size -= tabSize$3 - 1; + } + } else if (character !== lineFeed$9 && character !== '') { + currentMarker = null; + } + } + } + + if (currentMarker) { + if (!pedantic && marker !== currentMarker) { + break + } + + prefixed = true; + } else { + if (!commonmark && !indented && value.charAt(startIndex) === space$8) { + indented = true; + } else if (commonmark && item) { + indented = size >= item.indent || size > tabSize$3; + } + + prefixed = false; + index = startIndex; + } + + line = value.slice(startIndex, nextIndex); + content = startIndex === index ? line : value.slice(index, nextIndex); + + if ( + currentMarker === asterisk$1 || + currentMarker === underscore$1 || + currentMarker === dash$2 + ) { + if (tokenizers.thematicBreak.call(self, eat, line, true)) { + break + } + } + + prevEmpty = empty; + empty = !prefixed && !trim_1(content).length; + + if (indented && item) { + item.value = item.value.concat(emptyLines, line); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } else if (prefixed) { + if (emptyLines.length !== 0) { + spread = true; + item.value.push(''); + item.trail = emptyLines.concat(); + } + + item = { + value: [line], + indent: size, + trail: [] + }; + + items.push(item); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } else if (empty) { + if (prevEmpty && !commonmark) { + break + } + + emptyLines.push(line); + } else { + if (prevEmpty) { + break + } + + if (interrupt_1(interuptors, tokenizers, self, [eat, line, true])) { + break + } + + item.value = item.value.concat(emptyLines, line); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } + + index = nextIndex + 1; + } + + node = eat(allLines.join(lineFeed$9)).reset({ + type: 'list', + ordered: ordered, + start: start, + spread: spread, + children: [] + }); + + enterTop = self.enterList(); + exitBlockquote = self.enterBlock(); + index = -1; + length = items.length; + + while (++index < length) { + item = items[index].value.join(lineFeed$9); + now = eat.now(); + + eat(item)(listItem(self, item, now), node); + + item = items[index].trail.join(lineFeed$9); + + if (index !== length - 1) { + item += lineFeed$9; + } + + eat(item); + } + + enterTop(); + exitBlockquote(); + + return node +} + +function listItem(ctx, value, position) { + var offsets = ctx.offset; + var fn = ctx.options.pedantic ? pedanticListItem : normalListItem; + var checked = null; + var task; + var indent; + + value = fn.apply(null, arguments); + + if (ctx.options.gfm) { + task = value.match(taskItemExpression); + + if (task) { + indent = task[0].length; + checked = task[1].toLowerCase() === lowercaseX$1; + offsets[position.line] += indent; + value = value.slice(indent); + } + } + + return { + type: 'listItem', + spread: looseListItemExpression.test(value), + checked: checked, + children: ctx.tokenizeBlock(value, position) + } +} + +// Create a list-item using overly simple mechanics. +function pedanticListItem(ctx, value, position) { + var offsets = ctx.offset; + var line = position.line; + + // Remove the list-item’s bullet. + value = value.replace(pedanticBulletExpression, replacer); + + // The initial line was also matched by the below, so we reset the `line`. + line = position.line; + + return value.replace(initialIndentExpression, replacer) + + // A simple replacer which removed all matches, and adds their length to + // `offset`. + function replacer($0) { + offsets[line] = (offsets[line] || 0) + $0.length; + line++; + + return '' + } +} + +// Create a list-item using sane mechanics. +function normalListItem(ctx, value, position) { + var offsets = ctx.offset; + var line = position.line; + var max; + var bullet; + var rest; + var lines; + var trimmedLines; + var index; + var length; + + // Remove the list-item’s bullet. + value = value.replace(bulletExpression, replacer); + + lines = value.split(lineFeed$9); + + trimmedLines = removeIndentation(value, getIndentation(max).indent).split(lineFeed$9); + + // We replaced the initial bullet with something else above, which was used + // to trick `removeIndentation` into removing some more characters when + // possible. However, that could result in the initial line to be stripped + // more than it should be. + trimmedLines[0] = rest; + + offsets[line] = (offsets[line] || 0) + bullet.length; + line++; + + index = 0; + length = lines.length; + + while (++index < length) { + offsets[line] = + (offsets[line] || 0) + lines[index].length - trimmedLines[index].length; + line++; + } + + return trimmedLines.join(lineFeed$9) + + /* eslint-disable-next-line max-params */ + function replacer($0, $1, $2, $3, $4) { + bullet = $1 + $2 + $3; + rest = $4; + + // Make sure that the first nine numbered list items can indent with an + // extra space. That is, when the bullet did not receive an extra final + // space. + if (Number($2) < 10 && bullet.length % 2 === 1) { + $2 = space$8 + $2; + } + + max = $1 + repeatString(space$8, $2.length) + $3; + + return max + rest + } +} + +var headingSetext = setextHeading; + +var lineFeed$a = '\n'; +var tab$9 = '\t'; +var space$9 = ' '; +var equalsTo$1 = '='; +var dash$3 = '-'; + +var maxIndent = 3; + +var equalsToDepth = 1; +var dashDepth = 2; + +function setextHeading(eat, value, silent) { + var self = this; + var now = eat.now(); + var length = value.length; + var index = -1; + var subvalue = ''; + var content; + var queue; + var character; + var marker; + var depth; + + // Eat initial indentation. + while (++index < length) { + character = value.charAt(index); + + if (character !== space$9 || index >= maxIndent) { + index--; + break + } + + subvalue += character; + } + + // Eat content. + content = ''; + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character === lineFeed$a) { + index--; + break + } + + if (character === space$9 || character === tab$9) { + queue += character; + } else { + content += queue + character; + queue = ''; + } + } + + now.column += subvalue.length; + now.offset += subvalue.length; + subvalue += content + queue; + + // Ensure the content is followed by a newline and a valid marker. + character = value.charAt(++index); + marker = value.charAt(++index); + + if (character !== lineFeed$a || (marker !== equalsTo$1 && marker !== dash$3)) { + return + } + + subvalue += character; + + // Eat Setext-line. + queue = marker; + depth = marker === equalsTo$1 ? equalsToDepth : dashDepth; + + while (++index < length) { + character = value.charAt(index); + + if (character !== marker) { + if (character !== lineFeed$a) { + return + } + + index--; + break + } + + queue += character; + } + + if (silent) { + return true + } + + return eat(subvalue + queue)({ + type: 'heading', + depth: depth, + children: self.tokenizeInline(content, now) + }) +} + +var attributeName = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; +var unquoted = '[^"\'=<>`\\u0000-\\u0020]+'; +var singleQuoted = "'[^']*'"; +var doubleQuoted = '"[^"]*"'; +var attributeValue = + '(?:' + unquoted + '|' + singleQuoted + '|' + doubleQuoted + ')'; +var attribute = + '(?:\\s+' + attributeName + '(?:\\s*=\\s*' + attributeValue + ')?)'; +var openTag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; +var closeTag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; +var comment = '|'; +var processing = '<[?].*?[?]>'; +var declaration = ']*>'; +var cdata = ''; + +var openCloseTag = new RegExp('^(?:' + openTag + '|' + closeTag + ')'); + +var tag = new RegExp( + '^(?:' + + openTag + + '|' + + closeTag + + '|' + + comment + + '|' + + processing + + '|' + + declaration + + '|' + + cdata + + ')' +); + +var html = { + openCloseTag: openCloseTag, + tag: tag +}; + +var openCloseTag$1 = html.openCloseTag; + +var htmlBlock = blockHtml; + +var tab$a = '\t'; +var space$a = ' '; +var lineFeed$b = '\n'; +var lessThan$1 = '<'; + +var rawOpenExpression = /^<(script|pre|style)(?=(\s|>|$))/i; +var rawCloseExpression = /<\/(script|pre|style)>/i; +var commentOpenExpression = /^/; +var instructionOpenExpression = /^<\?/; +var instructionCloseExpression = /\?>/; +var directiveOpenExpression = /^/; +var cdataOpenExpression = /^/; +var elementCloseExpression = /^$/; +var otherElementOpenExpression = new RegExp(openCloseTag$1.source + '\\s*$'); + +function blockHtml(eat, value, silent) { + var self = this; + var blocks = self.options.blocks.join('|'); + var elementOpenExpression = new RegExp( + '^|$))', + 'i' + ); + var length = value.length; + var index = 0; + var next; + var line; + var offset; + var character; + var count; + var sequence; + var subvalue; + + var sequences = [ + [rawOpenExpression, rawCloseExpression, true], + [commentOpenExpression, commentCloseExpression, true], + [instructionOpenExpression, instructionCloseExpression, true], + [directiveOpenExpression, directiveCloseExpression, true], + [cdataOpenExpression, cdataCloseExpression, true], + [elementOpenExpression, elementCloseExpression, true], + [otherElementOpenExpression, elementCloseExpression, false] + ]; + + // Eat initial spacing. + while (index < length) { + character = value.charAt(index); + + if (character !== tab$a && character !== space$a) { + break + } + + index++; + } + + if (value.charAt(index) !== lessThan$1) { + return + } + + next = value.indexOf(lineFeed$b, index + 1); + next = next === -1 ? length : next; + line = value.slice(index, next); + offset = -1; + count = sequences.length; + + while (++offset < count) { + if (sequences[offset][0].test(line)) { + sequence = sequences[offset]; + break + } + } + + if (!sequence) { + return + } + + if (silent) { + return sequence[2] + } + + index = next; + + if (!sequence[1].test(line)) { + while (index < length) { + next = value.indexOf(lineFeed$b, index + 1); + next = next === -1 ? length : next; + line = value.slice(index + 1, next); + + if (sequence[1].test(line)) { + if (line) { + index = next; + } + + break + } + + index = next; + } + } + + subvalue = value.slice(0, index); + + return eat(subvalue)({type: 'html', value: subvalue}) +} + +var collapseWhiteSpace = collapse; + +// `collapse(' \t\nbar \nbaz\t') // ' bar baz '` +function collapse(value) { + return String(value).replace(/\s+/g, ' ') +} + +var normalize_1 = normalize$2; + +// Normalize an identifier. Collapses multiple white space characters into a +// single space, and removes casing. +function normalize$2(value) { + return collapseWhiteSpace(value).toLowerCase() +} + +var footnoteDefinition_1 = footnoteDefinition; +footnoteDefinition.notInList = true; +footnoteDefinition.notInBlock = true; + +var backslash$2 = '\\'; +var lineFeed$c = '\n'; +var tab$b = '\t'; +var space$b = ' '; +var leftSquareBracket = '['; +var rightSquareBracket = ']'; +var caret$1 = '^'; +var colon$1 = ':'; + +var EXPRESSION_INITIAL_TAB = /^( {4}|\t)?/gm; + +function footnoteDefinition(eat, value, silent) { + var self = this; + var offsets = self.offset; + var index; + var length; + var subvalue; + var now; + var currentLine; + var content; + var queue; + var subqueue; + var character; + var identifier; + var add; + var exit; + + if (!self.options.footnotes) { + return + } + + index = 0; + length = value.length; + subvalue = ''; + now = eat.now(); + currentLine = now.line; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + + if ( + value.charAt(index) !== leftSquareBracket || + value.charAt(index + 1) !== caret$1 + ) { + return + } + + subvalue += leftSquareBracket + caret$1; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === rightSquareBracket) { + break + } else if (character === backslash$2) { + queue += character; + index++; + character = value.charAt(index); + } + + queue += character; + index++; + } + + if ( + !queue || + value.charAt(index) !== rightSquareBracket || + value.charAt(index + 1) !== colon$1 + ) { + return + } + + if (silent) { + return true + } + + identifier = queue; + subvalue += queue + rightSquareBracket + colon$1; + index = subvalue.length; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$b && character !== space$b) { + break + } + + subvalue += character; + index++; + } + + now.column += subvalue.length; + now.offset += subvalue.length; + queue = ''; + content = ''; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === lineFeed$c) { + subqueue = character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character !== lineFeed$c) { + break + } + + subqueue += character; + index++; + } + + queue += subqueue; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$b) { + break + } + + subqueue += character; + index++; + } + + if (subqueue.length === 0) { + break + } + + queue += subqueue; + } + + if (queue) { + content += queue; + queue = ''; + } + + content += character; + index++; + } + + subvalue += content; + + content = content.replace(EXPRESSION_INITIAL_TAB, function(line) { + offsets[currentLine] = (offsets[currentLine] || 0) + line.length; + currentLine++; + + return '' + }); + + add = eat(subvalue); + + exit = self.enterBlock(); + content = self.tokenizeBlock(content, now); + exit(); + + return add({ + type: 'footnoteDefinition', + identifier: normalize_1(identifier), + label: identifier, + children: content + }) +} + +var definition_1 = definition; + +var quotationMark = '"'; +var apostrophe = "'"; +var backslash$3 = '\\'; +var lineFeed$d = '\n'; +var tab$c = '\t'; +var space$c = ' '; +var leftSquareBracket$1 = '['; +var rightSquareBracket$1 = ']'; +var leftParenthesis = '('; +var rightParenthesis$1 = ')'; +var colon$2 = ':'; +var lessThan$2 = '<'; +var greaterThan$1 = '>'; + +function definition(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var index = 0; + var length = value.length; + var subvalue = ''; + var beforeURL; + var beforeTitle; + var queue; + var character; + var test; + var identifier; + var url; + var title; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$c && character !== tab$c) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + + if (character !== leftSquareBracket$1) { + return + } + + index++; + subvalue += character; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === rightSquareBracket$1) { + break + } else if (character === backslash$3) { + queue += character; + index++; + character = value.charAt(index); + } + + queue += character; + index++; + } + + if ( + !queue || + value.charAt(index) !== rightSquareBracket$1 || + value.charAt(index + 1) !== colon$2 + ) { + return + } + + identifier = queue; + subvalue += queue + rightSquareBracket$1 + colon$2; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c && character !== lineFeed$d) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + queue = ''; + beforeURL = subvalue; + + if (character === lessThan$2) { + index++; + + while (index < length) { + character = value.charAt(index); + + if (!isEnclosedURLCharacter(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (character === isEnclosedURLCharacter.delimiter) { + subvalue += lessThan$2 + queue + character; + index++; + } else { + if (commonmark) { + return + } + + index -= queue.length + 1; + queue = ''; + } + } + + if (!queue) { + while (index < length) { + character = value.charAt(index); + + if (!isUnclosedURLCharacter(character)) { + break + } + + queue += character; + index++; + } + + subvalue += queue; + } + + if (!queue) { + return + } + + url = queue; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c && character !== lineFeed$d) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + test = null; + + if (character === quotationMark) { + test = quotationMark; + } else if (character === apostrophe) { + test = apostrophe; + } else if (character === leftParenthesis) { + test = rightParenthesis$1; + } + + if (!test) { + queue = ''; + index = subvalue.length; + } else if (queue) { + subvalue += queue + character; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === test) { + break + } + + if (character === lineFeed$d) { + index++; + character = value.charAt(index); + + if (character === lineFeed$d || character === test) { + return + } + + queue += lineFeed$d; + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (character !== test) { + return + } + + beforeTitle = subvalue; + subvalue += queue + character; + index++; + title = queue; + queue = ''; + } else { + return + } + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + + if (!character || character === lineFeed$d) { + if (silent) { + return true + } + + beforeURL = eat(beforeURL).test().end; + url = self.decode.raw(self.unescape(url), beforeURL, {nonTerminated: false}); + + if (title) { + beforeTitle = eat(beforeTitle).test().end; + title = self.decode.raw(self.unescape(title), beforeTitle); + } + + return eat(subvalue)({ + type: 'definition', + identifier: normalize_1(identifier), + label: identifier, + title: title || null, + url: url + }) + } +} + +// Check if `character` can be inside an enclosed URI. +function isEnclosedURLCharacter(character) { + return ( + character !== greaterThan$1 && + character !== leftSquareBracket$1 && + character !== rightSquareBracket$1 + ) +} + +isEnclosedURLCharacter.delimiter = greaterThan$1; + +// Check if `character` can be inside an unclosed URI. +function isUnclosedURLCharacter(character) { + return ( + character !== leftSquareBracket$1 && + character !== rightSquareBracket$1 && + !isWhitespaceCharacter(character) + ) +} + +var table_1 = table; + +var tab$d = '\t'; +var lineFeed$e = '\n'; +var space$d = ' '; +var dash$4 = '-'; +var colon$3 = ':'; +var backslash$4 = '\\'; +var verticalBar = '|'; + +var minColumns = 1; +var minRows = 2; + +var left = 'left'; +var center = 'center'; +var right = 'right'; + +function table(eat, value, silent) { + var self = this; + var index; + var alignments; + var alignment; + var subvalue; + var row; + var length; + var lines; + var queue; + var character; + var hasDash; + var align; + var cell; + var preamble; + var now; + var position; + var lineCount; + var line; + var rows; + var table; + var lineIndex; + var pipeIndex; + var first; + + // Exit when not in gfm-mode. + if (!self.options.gfm) { + return + } + + // Get the rows. + // Detecting tables soon is hard, so there are some checks for performance + // here, such as the minimum number of rows, and allowed characters in the + // alignment row. + index = 0; + lineCount = 0; + length = value.length + 1; + lines = []; + + while (index < length) { + lineIndex = value.indexOf(lineFeed$e, index); + pipeIndex = value.indexOf(verticalBar, index + 1); + + if (lineIndex === -1) { + lineIndex = value.length; + } + + if (pipeIndex === -1 || pipeIndex > lineIndex) { + if (lineCount < minRows) { + return + } + + break + } + + lines.push(value.slice(index, lineIndex)); + lineCount++; + index = lineIndex + 1; + } + + // Parse the alignment row. + subvalue = lines.join(lineFeed$e); + alignments = lines.splice(1, 1)[0] || []; + index = 0; + length = alignments.length; + lineCount--; + alignment = false; + align = []; + + while (index < length) { + character = alignments.charAt(index); + + if (character === verticalBar) { + hasDash = null; + + if (alignment === false) { + if (first === false) { + return + } + } else { + align.push(alignment); + alignment = false; + } + + first = false; + } else if (character === dash$4) { + hasDash = true; + alignment = alignment || null; + } else if (character === colon$3) { + if (alignment === left) { + alignment = center; + } else if (hasDash && alignment === null) { + alignment = right; + } else { + alignment = left; + } + } else if (!isWhitespaceCharacter(character)) { + return + } + + index++; + } + + if (alignment !== false) { + align.push(alignment); + } + + // Exit when without enough columns. + if (align.length < minColumns) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + // Parse the rows. + position = -1; + rows = []; + + table = eat(subvalue).reset({type: 'table', align: align, children: rows}); + + while (++position < lineCount) { + line = lines[position]; + row = {type: 'tableRow', children: []}; + + // Eat a newline character when this is not the first row. + if (position) { + eat(lineFeed$e); + } + + // Eat the row. + eat(line).reset(row, table); + + length = line.length + 1; + index = 0; + queue = ''; + cell = ''; + preamble = true; + + while (index < length) { + character = line.charAt(index); + + if (character === tab$d || character === space$d) { + if (cell) { + queue += character; + } else { + eat(character); + } + + index++; + continue + } + + if (character === '' || character === verticalBar) { + if (preamble) { + eat(character); + } else { + if ((cell || character) && !preamble) { + subvalue = cell; + + if (queue.length > 1) { + if (character) { + subvalue += queue.slice(0, queue.length - 1); + queue = queue.charAt(queue.length - 1); + } else { + subvalue += queue; + queue = ''; + } + } + + now = eat.now(); + + eat(subvalue)( + {type: 'tableCell', children: self.tokenizeInline(cell, now)}, + row + ); + } + + eat(queue + character); + + queue = ''; + cell = ''; + } + } else { + if (queue) { + cell += queue; + queue = ''; + } + + cell += character; + + if (character === backslash$4 && index !== length - 2) { + cell += line.charAt(index + 1); + index++; + } + } + + preamble = false; + index++; + } + + // Eat the alignment row. + if (!position) { + eat(lineFeed$e + alignments); + } + } + + return table +} + +var paragraph_1 = paragraph; + +var tab$e = '\t'; +var lineFeed$f = '\n'; +var space$e = ' '; + +var tabSize$4 = 4; + +// Tokenise paragraph. +function paragraph(eat, value, silent) { + var self = this; + var settings = self.options; + var commonmark = settings.commonmark; + var gfm = settings.gfm; + var tokenizers = self.blockTokenizers; + var interruptors = self.interruptParagraph; + var index = value.indexOf(lineFeed$f); + var length = value.length; + var position; + var subvalue; + var character; + var size; + var now; + + while (index < length) { + // Eat everything if there’s no following newline. + if (index === -1) { + index = length; + break + } + + // Stop if the next character is NEWLINE. + if (value.charAt(index + 1) === lineFeed$f) { + break + } + + // In commonmark-mode, following indented lines are part of the paragraph. + if (commonmark) { + size = 0; + position = index + 1; + + while (position < length) { + character = value.charAt(position); + + if (character === tab$e) { + size = tabSize$4; + break + } else if (character === space$e) { + size++; + } else { + break + } + + position++; + } + + if (size >= tabSize$4 && character !== lineFeed$f) { + index = value.indexOf(lineFeed$f, index + 1); + continue + } + } + + subvalue = value.slice(index + 1); + + // Check if the following code contains a possible block. + if (interrupt_1(interruptors, tokenizers, self, [eat, subvalue, true])) { + break + } + + // Break if the following line starts a list, when already in a list, or + // when in commonmark, or when in gfm mode and the bullet is *not* numeric. + if ( + tokenizers.list.call(self, eat, subvalue, true) && + (self.inList || + commonmark || + (gfm && !isDecimal(trim_1.left(subvalue).charAt(0)))) + ) { + break + } + + position = index; + index = value.indexOf(lineFeed$f, index + 1); + + if (index !== -1 && trim_1(value.slice(position, index)) === '') { + index = position; + break + } + } + + subvalue = value.slice(0, index); + + if (trim_1(subvalue) === '') { + eat(subvalue); + + return null + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + subvalue = trimTrailingLines_1(subvalue); + + return eat(subvalue)({ + type: 'paragraph', + children: self.tokenizeInline(subvalue, now) + }) +} + +var _escape = locate; + +function locate(value, fromIndex) { + return value.indexOf('\\', fromIndex) +} + +var _escape$1 = escape$1; +escape$1.locator = _escape; + +var lineFeed$g = '\n'; +var backslash$5 = '\\'; + +function escape$1(eat, value, silent) { + var self = this; + var character; + var node; + + if (value.charAt(0) === backslash$5) { + character = value.charAt(1); + + if (self.escape.indexOf(character) !== -1) { + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + if (character === lineFeed$g) { + node = {type: 'break'}; + } else { + node = {type: 'text', value: character}; + } + + return eat(backslash$5 + character)(node) + } + } +} + +var tag$1 = locate$1; + +function locate$1(value, fromIndex) { + return value.indexOf('<', fromIndex) +} + +var autoLink_1 = autoLink; +autoLink.locator = tag$1; +autoLink.notInLink = true; + +var lessThan$3 = '<'; +var greaterThan$2 = '>'; +var atSign = '@'; +var slash$1 = '/'; +var mailto = 'mailto:'; +var mailtoLength = mailto.length; + +function autoLink(eat, value, silent) { + var self = this; + var subvalue = ''; + var length = value.length; + var index = 0; + var queue = ''; + var hasAtCharacter = false; + var link = ''; + var character; + var now; + var content; + var tokenizers; + var exit; + + if (value.charAt(0) !== lessThan$3) { + return + } + + index++; + subvalue = lessThan$3; + + while (index < length) { + character = value.charAt(index); + + if ( + isWhitespaceCharacter(character) || + character === greaterThan$2 || + character === atSign || + (character === ':' && value.charAt(index + 1) === slash$1) + ) { + break + } + + queue += character; + index++; + } + + if (!queue) { + return + } + + link += queue; + queue = ''; + + character = value.charAt(index); + link += character; + index++; + + if (character === atSign) { + hasAtCharacter = true; + } else { + if (character !== ':' || value.charAt(index + 1) !== slash$1) { + return + } + + link += slash$1; + index++; + } + + while (index < length) { + character = value.charAt(index); + + if (isWhitespaceCharacter(character) || character === greaterThan$2) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (!queue || character !== greaterThan$2) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + link += queue; + content = link; + subvalue += link + character; + now = eat.now(); + now.column++; + now.offset++; + + if (hasAtCharacter) { + if (link.slice(0, mailtoLength).toLowerCase() === mailto) { + content = content.slice(mailtoLength); + now.column += mailtoLength; + now.offset += mailtoLength; + } else { + link = mailto + link; + } + } + + // Temporarily remove all tokenizers except text in autolinks. + tokenizers = self.inlineTokenizers; + self.inlineTokenizers = {text: tokenizers.text}; + + exit = self.enterLink(); + + content = self.tokenizeInline(content, now); + + self.inlineTokenizers = tokenizers; + exit(); + + return eat(subvalue)({ + type: 'link', + title: null, + url: parseEntities_1(link, {nonTerminated: false}), + children: content + }) +} + +var url = locate$2; + +var protocols = ['https://', 'http://', 'mailto:']; + +function locate$2(value, fromIndex) { + var length = protocols.length; + var index = -1; + var min = -1; + var position; + + if (!this.options.gfm) { + return -1 + } + + while (++index < length) { + position = value.indexOf(protocols[index], fromIndex); + + if (position !== -1 && (position < min || min === -1)) { + min = position; + } + } + + return min +} + +var url_1 = url$1; +url$1.locator = url; +url$1.notInLink = true; + +var quotationMark$1 = '"'; +var apostrophe$1 = "'"; +var leftParenthesis$1 = '('; +var rightParenthesis$2 = ')'; +var comma$1 = ','; +var dot$2 = '.'; +var colon$4 = ':'; +var semicolon$1 = ';'; +var lessThan$4 = '<'; +var atSign$1 = '@'; +var leftSquareBracket$2 = '['; +var rightSquareBracket$2 = ']'; + +var http = 'http://'; +var https = 'https://'; +var mailto$1 = 'mailto:'; + +var protocols$1 = [http, https, mailto$1]; + +var protocolsLength = protocols$1.length; + +function url$1(eat, value, silent) { + var self = this; + var subvalue; + var content; + var character; + var index; + var position; + var protocol; + var match; + var length; + var queue; + var parenCount; + var nextCharacter; + var tokenizers; + var exit; + + if (!self.options.gfm) { + return + } + + subvalue = ''; + index = -1; + + while (++index < protocolsLength) { + protocol = protocols$1[index]; + match = value.slice(0, protocol.length); + + if (match.toLowerCase() === protocol) { + subvalue = match; + break + } + } + + if (!subvalue) { + return + } + + index = subvalue.length; + length = value.length; + queue = ''; + parenCount = 0; + + while (index < length) { + character = value.charAt(index); + + if (isWhitespaceCharacter(character) || character === lessThan$4) { + break + } + + if ( + character === dot$2 || + character === comma$1 || + character === colon$4 || + character === semicolon$1 || + character === quotationMark$1 || + character === apostrophe$1 || + character === rightParenthesis$2 || + character === rightSquareBracket$2 + ) { + nextCharacter = value.charAt(index + 1); + + if (!nextCharacter || isWhitespaceCharacter(nextCharacter)) { + break + } + } + + if (character === leftParenthesis$1 || character === leftSquareBracket$2) { + parenCount++; + } + + if (character === rightParenthesis$2 || character === rightSquareBracket$2) { + parenCount--; + + if (parenCount < 0) { + break + } + } + + queue += character; + index++; + } + + if (!queue) { + return + } + + subvalue += queue; + content = subvalue; + + if (protocol === mailto$1) { + position = queue.indexOf(atSign$1); + + if (position === -1 || position === length - 1) { + return + } + + content = content.slice(mailto$1.length); + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + exit = self.enterLink(); + + // Temporarily remove all tokenizers except text in url. + tokenizers = self.inlineTokenizers; + self.inlineTokenizers = {text: tokenizers.text}; + + content = self.tokenizeInline(content, eat.now()); + + self.inlineTokenizers = tokenizers; + exit(); + + return eat(subvalue)({ + type: 'link', + title: null, + url: parseEntities_1(subvalue, {nonTerminated: false}), + children: content + }) +} + +var tag$2 = html.tag; + +var htmlInline = inlineHTML; +inlineHTML.locator = tag$1; + +var lessThan$5 = '<'; +var questionMark = '?'; +var exclamationMark$1 = '!'; +var slash$2 = '/'; + +var htmlLinkOpenExpression = /^/i; + +function inlineHTML(eat, value, silent) { + var self = this; + var length = value.length; + var character; + var subvalue; + + if (value.charAt(0) !== lessThan$5 || length < 3) { + return + } + + character = value.charAt(1); + + if ( + !isAlphabetical(character) && + character !== questionMark && + character !== exclamationMark$1 && + character !== slash$2 + ) { + return + } + + subvalue = value.match(tag$2); + + if (!subvalue) { + return + } + + /* istanbul ignore if - not used yet. */ + if (silent) { + return true + } + + subvalue = subvalue[0]; + + if (!self.inLink && htmlLinkOpenExpression.test(subvalue)) { + self.inLink = true; + } else if (self.inLink && htmlLinkCloseExpression.test(subvalue)) { + self.inLink = false; + } + + return eat(subvalue)({type: 'html', value: subvalue}) +} + +var link$1 = locate$3; + +function locate$3(value, fromIndex) { + var link = value.indexOf('[', fromIndex); + var image = value.indexOf('![', fromIndex); + + if (image === -1) { + return link + } + + // Link can never be `-1` if an image is found, so we don’t need to check + // for that :) + return link < image ? link : image +} + +var link_1 = link$2; +link$2.locator = link$1; + +var lineFeed$h = '\n'; +var exclamationMark$2 = '!'; +var quotationMark$2 = '"'; +var apostrophe$2 = "'"; +var leftParenthesis$2 = '('; +var rightParenthesis$3 = ')'; +var lessThan$6 = '<'; +var greaterThan$3 = '>'; +var leftSquareBracket$3 = '['; +var backslash$6 = '\\'; +var rightSquareBracket$3 = ']'; +var graveAccent$1 = '`'; + +function link$2(eat, value, silent) { + var self = this; + var subvalue = ''; + var index = 0; + var character = value.charAt(0); + var pedantic = self.options.pedantic; + var commonmark = self.options.commonmark; + var gfm = self.options.gfm; + var closed; + var count; + var opening; + var beforeURL; + var beforeTitle; + var subqueue; + var hasMarker; + var isImage; + var content; + var marker; + var length; + var title; + var depth; + var queue; + var url; + var now; + var exit; + var node; + + // Detect whether this is an image. + if (character === exclamationMark$2) { + isImage = true; + subvalue = character; + character = value.charAt(++index); + } + + // Eat the opening. + if (character !== leftSquareBracket$3) { + return + } + + // Exit when this is a link and we’re already inside a link. + if (!isImage && self.inLink) { + return + } + + subvalue += character; + queue = ''; + index++; + + // Eat the content. + length = value.length; + now = eat.now(); + depth = 0; + + now.column += index; + now.offset += index; + + while (index < length) { + character = value.charAt(index); + subqueue = character; + + if (character === graveAccent$1) { + // Inline-code in link content. + count = 1; + + while (value.charAt(index + 1) === graveAccent$1) { + subqueue += character; + index++; + count++; + } + + if (!opening) { + opening = count; + } else if (count >= opening) { + opening = 0; + } + } else if (character === backslash$6) { + // Allow brackets to be escaped. + index++; + subqueue += value.charAt(index); + } else if ((!opening || gfm) && character === leftSquareBracket$3) { + // In GFM mode, brackets in code still count. In all other modes, + // they don’t. + depth++; + } else if ((!opening || gfm) && character === rightSquareBracket$3) { + if (depth) { + depth--; + } else { + // Allow white-space between content and url in GFM mode. + if (!pedantic) { + while (index < length) { + character = value.charAt(index + 1); + + if (!isWhitespaceCharacter(character)) { + break + } + + subqueue += character; + index++; + } + } + + if (value.charAt(index + 1) !== leftParenthesis$2) { + return + } + + subqueue += leftParenthesis$2; + closed = true; + index++; + + break + } + } + + queue += subqueue; + subqueue = ''; + index++; + } + + // Eat the content closing. + if (!closed) { + return + } + + content = queue; + subvalue += queue + subqueue; + index++; + + // Eat white-space. + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + + // Eat the URL. + character = value.charAt(index); + queue = ''; + beforeURL = subvalue; + + if (character === lessThan$6) { + index++; + beforeURL += lessThan$6; + + while (index < length) { + character = value.charAt(index); + + if (character === greaterThan$3) { + break + } + + if (commonmark && character === lineFeed$h) { + return + } + + queue += character; + index++; + } + + if (value.charAt(index) !== greaterThan$3) { + return + } + + subvalue += lessThan$6 + queue + greaterThan$3; + url = queue; + index++; + } else { + character = null; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if ( + subqueue && + (character === quotationMark$2 || + character === apostrophe$2 || + (commonmark && character === leftParenthesis$2)) + ) { + break + } + + if (isWhitespaceCharacter(character)) { + if (!pedantic) { + break + } + + subqueue += character; + } else { + if (character === leftParenthesis$2) { + depth++; + } else if (character === rightParenthesis$3) { + if (depth === 0) { + break + } + + depth--; + } + + queue += subqueue; + subqueue = ''; + + if (character === backslash$6) { + queue += backslash$6; + character = value.charAt(++index); + } + + queue += character; + } + + index++; + } + + subvalue += queue; + url = queue; + index = subvalue.length; + } + + // Eat white-space. + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + subvalue += queue; + + // Eat the title. + if ( + queue && + (character === quotationMark$2 || + character === apostrophe$2 || + (commonmark && character === leftParenthesis$2)) + ) { + index++; + subvalue += character; + queue = ''; + marker = character === leftParenthesis$2 ? rightParenthesis$3 : character; + beforeTitle = subvalue; + + // In commonmark-mode, things are pretty easy: the marker cannot occur + // inside the title. Non-commonmark does, however, support nested + // delimiters. + if (commonmark) { + while (index < length) { + character = value.charAt(index); + + if (character === marker) { + break + } + + if (character === backslash$6) { + queue += backslash$6; + character = value.charAt(++index); + } + + index++; + queue += character; + } + + character = value.charAt(index); + + if (character !== marker) { + return + } + + title = queue; + subvalue += queue + character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + } else { + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === marker) { + if (hasMarker) { + queue += marker + subqueue; + subqueue = ''; + } + + hasMarker = true; + } else if (!hasMarker) { + queue += character; + } else if (character === rightParenthesis$3) { + subvalue += queue + marker + subqueue; + title = queue; + break + } else if (isWhitespaceCharacter(character)) { + subqueue += character; + } else { + queue += marker + subqueue + character; + subqueue = ''; + hasMarker = false; + } + + index++; + } + } + } + + if (value.charAt(index) !== rightParenthesis$3) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + subvalue += rightParenthesis$3; + + url = self.decode.raw(self.unescape(url), eat(beforeURL).test().end, { + nonTerminated: false + }); + + if (title) { + beforeTitle = eat(beforeTitle).test().end; + title = self.decode.raw(self.unescape(title), beforeTitle); + } + + node = { + type: isImage ? 'image' : 'link', + title: title || null, + url: url + }; + + if (isImage) { + node.alt = self.decode.raw(self.unescape(content), now) || null; + } else { + exit = self.enterLink(); + node.children = self.tokenizeInline(content, now); + exit(); + } + + return eat(subvalue)(node) +} + +var reference_1 = reference; +reference.locator = link$1; + +var link$3 = 'link'; +var image$1 = 'image'; +var footnote = 'footnote'; +var shortcut = 'shortcut'; +var collapsed = 'collapsed'; +var full = 'full'; +var space$f = ' '; +var exclamationMark$3 = '!'; +var leftSquareBracket$4 = '['; +var backslash$7 = '\\'; +var rightSquareBracket$4 = ']'; +var caret$2 = '^'; + +function reference(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var footnotes = self.options.footnotes; + var character = value.charAt(0); + var index = 0; + var length = value.length; + var subvalue = ''; + var intro = ''; + var type = link$3; + var referenceType = shortcut; + var content; + var identifier; + var now; + var node; + var exit; + var queue; + var bracketed; + var depth; + + // Check whether we’re eating an image. + if (character === exclamationMark$3) { + type = image$1; + intro = character; + character = value.charAt(++index); + } + + if (character !== leftSquareBracket$4) { + return + } + + index++; + intro += character; + queue = ''; + + // Check whether we’re eating a footnote. + if (footnotes && value.charAt(index) === caret$2) { + // Exit if `![^` is found, so the `!` will be seen as text after this, + // and we’ll enter this function again when `[^` is found. + if (type === image$1) { + return + } + + intro += caret$2; + index++; + type = footnote; + } + + // Eat the text. + depth = 0; + + while (index < length) { + character = value.charAt(index); + + if (character === leftSquareBracket$4) { + bracketed = true; + depth++; + } else if (character === rightSquareBracket$4) { + if (!depth) { + break + } + + depth--; + } + + if (character === backslash$7) { + queue += backslash$7; + character = value.charAt(++index); + } + + queue += character; + index++; + } + + subvalue = queue; + content = queue; + character = value.charAt(index); + + if (character !== rightSquareBracket$4) { + return + } + + index++; + subvalue += character; + queue = ''; + + if (!commonmark) { + // The original markdown syntax definition explicitly allows for whitespace + // between the link text and link label; commonmark departs from this, in + // part to improve support for shortcut reference links + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + index++; + } + } + + character = value.charAt(index); + + // Inline footnotes cannot have a label. + // If footnotes are enabled, link labels cannot start with a caret. + if ( + type !== footnote && + character === leftSquareBracket$4 && + (!footnotes || value.charAt(index + 1) !== caret$2) + ) { + identifier = ''; + queue += character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character === leftSquareBracket$4 || character === rightSquareBracket$4) { + break + } + + if (character === backslash$7) { + identifier += backslash$7; + character = value.charAt(++index); + } + + identifier += character; + index++; + } + + character = value.charAt(index); + + if (character === rightSquareBracket$4) { + referenceType = identifier ? full : collapsed; + queue += identifier + character; + index++; + } else { + identifier = ''; + } + + subvalue += queue; + queue = ''; + } else { + if (!content) { + return + } + + identifier = content; + } + + // Brackets cannot be inside the identifier. + if (referenceType !== full && bracketed) { + return + } + + subvalue = intro + subvalue; + + if (type === link$3 && self.inLink) { + return null + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + if (type === footnote && content.indexOf(space$f) !== -1) { + return eat(subvalue)({ + type: footnote, + children: this.tokenizeInline(content, eat.now()) + }) + } + + now = eat.now(); + now.column += intro.length; + now.offset += intro.length; + identifier = referenceType === full ? identifier : content; + + node = { + type: type + 'Reference', + identifier: normalize_1(identifier), + label: identifier + }; + + if (type === link$3 || type === image$1) { + node.referenceType = referenceType; + } + + if (type === link$3) { + exit = self.enterLink(); + node.children = self.tokenizeInline(content, now); + exit(); + } else if (type === image$1) { + node.alt = self.decode.raw(self.unescape(content), now) || null; + } + + return eat(subvalue)(node) +} + +var strong = locate$4; + +function locate$4(value, fromIndex) { + var asterisk = value.indexOf('**', fromIndex); + var underscore = value.indexOf('__', fromIndex); + + if (underscore === -1) { + return asterisk + } + + if (asterisk === -1) { + return underscore + } + + return underscore < asterisk ? underscore : asterisk +} + +var strong_1 = strong$1; +strong$1.locator = strong; + +var backslash$8 = '\\'; +var asterisk$2 = '*'; +var underscore$2 = '_'; + +function strong$1(eat, value, silent) { + var self = this; + var index = 0; + var character = value.charAt(index); + var now; + var pedantic; + var marker; + var queue; + var subvalue; + var length; + var prev; + + if ( + (character !== asterisk$2 && character !== underscore$2) || + value.charAt(++index) !== character + ) { + return + } + + pedantic = self.options.pedantic; + marker = character; + subvalue = marker + marker; + length = value.length; + index++; + queue = ''; + character = ''; + + if (pedantic && isWhitespaceCharacter(value.charAt(index))) { + return + } + + while (index < length) { + prev = character; + character = value.charAt(index); + + if ( + character === marker && + value.charAt(index + 1) === marker && + (!pedantic || !isWhitespaceCharacter(prev)) + ) { + character = value.charAt(index + 2); + + if (character !== marker) { + if (!trim_1(queue)) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + now.column += 2; + now.offset += 2; + + return eat(subvalue + queue + subvalue)({ + type: 'strong', + children: self.tokenizeInline(queue, now) + }) + } + } + + if (!pedantic && character === backslash$8) { + queue += character; + character = value.charAt(++index); + } + + queue += character; + index++; + } +} + +var isWordCharacter = wordCharacter; + +var fromCode$1 = String.fromCharCode; +var re$2 = /\w/; + +// Check if the given character code, or the character code at the first +// character, is a word character. +function wordCharacter(character) { + return re$2.test( + typeof character === 'number' ? fromCode$1(character) : character.charAt(0) + ) +} + +var emphasis = locate$5; + +function locate$5(value, fromIndex) { + var asterisk = value.indexOf('*', fromIndex); + var underscore = value.indexOf('_', fromIndex); + + if (underscore === -1) { + return asterisk + } + + if (asterisk === -1) { + return underscore + } + + return underscore < asterisk ? underscore : asterisk +} + +var emphasis_1 = emphasis$1; +emphasis$1.locator = emphasis; + +var asterisk$3 = '*'; +var underscore$3 = '_'; +var backslash$9 = '\\'; + +function emphasis$1(eat, value, silent) { + var self = this; + var index = 0; + var character = value.charAt(index); + var now; + var pedantic; + var marker; + var queue; + var subvalue; + var length; + var prev; + + if (character !== asterisk$3 && character !== underscore$3) { + return + } + + pedantic = self.options.pedantic; + subvalue = character; + marker = character; + length = value.length; + index++; + queue = ''; + character = ''; + + if (pedantic && isWhitespaceCharacter(value.charAt(index))) { + return + } + + while (index < length) { + prev = character; + character = value.charAt(index); + + if (character === marker && (!pedantic || !isWhitespaceCharacter(prev))) { + character = value.charAt(++index); + + if (character !== marker) { + if (!trim_1(queue) || prev === marker) { + return + } + + if (!pedantic && marker === underscore$3 && isWordCharacter(character)) { + queue += marker; + continue + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + now.column++; + now.offset++; + + return eat(subvalue + queue + marker)({ + type: 'emphasis', + children: self.tokenizeInline(queue, now) + }) + } + + queue += marker; + } + + if (!pedantic && character === backslash$9) { + queue += character; + character = value.charAt(++index); + } + + queue += character; + index++; + } +} + +var _delete = locate$6; + +function locate$6(value, fromIndex) { + return value.indexOf('~~', fromIndex) +} + +var _delete$1 = strikethrough; +strikethrough.locator = _delete; + +var tilde$2 = '~'; +var fence = '~~'; + +function strikethrough(eat, value, silent) { + var self = this; + var character = ''; + var previous = ''; + var preceding = ''; + var subvalue = ''; + var index; + var length; + var now; + + if ( + !self.options.gfm || + value.charAt(0) !== tilde$2 || + value.charAt(1) !== tilde$2 || + isWhitespaceCharacter(value.charAt(2)) + ) { + return + } + + index = 1; + length = value.length; + now = eat.now(); + now.column += 2; + now.offset += 2; + + while (++index < length) { + character = value.charAt(index); + + if ( + character === tilde$2 && + previous === tilde$2 && + (!preceding || !isWhitespaceCharacter(preceding)) + ) { + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + return eat(fence + subvalue + fence)({ + type: 'delete', + children: self.tokenizeInline(subvalue, now) + }) + } + + subvalue += previous; + preceding = previous; + previous = character; + } +} + +var codeInline = locate$7; + +function locate$7(value, fromIndex) { + return value.indexOf('`', fromIndex) +} + +var codeInline$1 = inlineCode; +inlineCode.locator = codeInline; + +var lineFeed$i = 10; // '\n' +var space$g = 32; // ' ' +var graveAccent$2 = 96; // '`' + +function inlineCode(eat, value, silent) { + var length = value.length; + var index = 0; + var openingFenceEnd; + var closingFenceStart; + var closingFenceEnd; + var code; + var next; + var found; + + while (index < length) { + if (value.charCodeAt(index) !== graveAccent$2) { + break + } + + index++; + } + + if (index === 0 || index === length) { + return + } + + openingFenceEnd = index; + next = value.charCodeAt(index); + + while (index < length) { + code = next; + next = value.charCodeAt(index + 1); + + if (code === graveAccent$2) { + if (closingFenceStart === undefined) { + closingFenceStart = index; + } + + closingFenceEnd = index + 1; + + if ( + next !== graveAccent$2 && + closingFenceEnd - closingFenceStart === openingFenceEnd + ) { + found = true; + break + } + } else if (closingFenceStart !== undefined) { + closingFenceStart = undefined; + closingFenceEnd = undefined; + } + + index++; + } + + if (!found) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + // Remove the initial and final space (or line feed), iff they exist and there + // are non-space characters in the content. + index = openingFenceEnd; + length = closingFenceStart; + code = value.charCodeAt(index); + next = value.charCodeAt(length - 1); + found = false; + + if ( + length - index > 2 && + (code === space$g || code === lineFeed$i) && + (next === space$g || next === lineFeed$i) + ) { + index++; + length--; + + while (index < length) { + code = value.charCodeAt(index); + + if (code !== space$g && code !== lineFeed$i) { + found = true; + break + } + + index++; + } + + if (found === true) { + openingFenceEnd++; + closingFenceStart--; + } + } + + return eat(value.slice(0, closingFenceEnd))({ + type: 'inlineCode', + value: value.slice(openingFenceEnd, closingFenceStart) + }) +} + +var _break = locate$8; + +function locate$8(value, fromIndex) { + var index = value.indexOf('\n', fromIndex); + + while (index > fromIndex) { + if (value.charAt(index - 1) !== ' ') { + break + } + + index--; + } + + return index +} + +var _break$1 = hardBreak; +hardBreak.locator = _break; + +var space$h = ' '; +var lineFeed$j = '\n'; +var minBreakLength = 2; + +function hardBreak(eat, value, silent) { + var length = value.length; + var index = -1; + var queue = ''; + var character; + + while (++index < length) { + character = value.charAt(index); + + if (character === lineFeed$j) { + if (index < minBreakLength) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + queue += character; + + return eat(queue)({type: 'break'}) + } + + if (character !== space$h) { + return + } + + queue += character; + } +} + +var text_1 = text; + +function text(eat, value, silent) { + var self = this; + var methods; + var tokenizers; + var index; + var length; + var subvalue; + var position; + var tokenizer; + var name; + var min; + var now; + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + methods = self.inlineMethods; + length = methods.length; + tokenizers = self.inlineTokenizers; + index = -1; + min = value.length; + + while (++index < length) { + name = methods[index]; + + if (name === 'text' || !tokenizers[name]) { + continue + } + + tokenizer = tokenizers[name].locator; + + if (!tokenizer) { + eat.file.fail('Missing locator: `' + name + '`'); + } + + position = tokenizer.call(self, value, 1); + + if (position !== -1 && position < min) { + min = position; + } + } + + subvalue = value.slice(0, min); + now = eat.now(); + + self.decode(subvalue, now, handler); + + function handler(content, position, source) { + eat(source || content)({type: 'text', value: content}); + } +} + +var parser = Parser; + +function Parser(doc, file) { + this.file = file; + this.offset = {}; + this.options = immutable(this.options); + this.setOptions({}); + + this.inList = false; + this.inBlock = false; + this.inLink = false; + this.atStart = true; + + this.toOffset = vfileLocation(file).toOffset; + this.unescape = _unescape(this, 'escape'); + this.decode = decode(this); +} + +var proto$3 = Parser.prototype; + +// Expose core. +proto$3.setOptions = setOptions_1; +proto$3.parse = parse_1$3; + +// Expose `defaults`. +proto$3.options = defaults$2; + +// Enter and exit helpers. +proto$3.exitStart = stateToggle('atStart', true); +proto$3.enterList = stateToggle('inList', false); +proto$3.enterLink = stateToggle('inLink', false); +proto$3.enterBlock = stateToggle('inBlock', false); + +// Nodes that can interupt a paragraph: +// +// ```markdown +// A paragraph, followed by a thematic break. +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the paragraph. +proto$3.interruptParagraph = [ + ['thematicBreak'], + ['atxHeading'], + ['fencedCode'], + ['blockquote'], + ['html'], + ['setextHeading', {commonmark: false}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Nodes that can interupt a list: +// +// ```markdown +// - One +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the list. +proto$3.interruptList = [ + ['atxHeading', {pedantic: false}], + ['fencedCode', {pedantic: false}], + ['thematicBreak', {pedantic: false}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Nodes that can interupt a blockquote: +// +// ```markdown +// > A paragraph. +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the blockquote. +proto$3.interruptBlockquote = [ + ['indentedCode', {commonmark: true}], + ['fencedCode', {commonmark: true}], + ['atxHeading', {commonmark: true}], + ['setextHeading', {commonmark: true}], + ['thematicBreak', {commonmark: true}], + ['html', {commonmark: true}], + ['list', {commonmark: true}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Handlers. +proto$3.blockTokenizers = { + newline: newline_1, + indentedCode: codeIndented, + fencedCode: codeFenced, + blockquote: blockquote_1, + atxHeading: headingAtx, + thematicBreak: thematicBreak_1, + list: list_1, + setextHeading: headingSetext, + html: htmlBlock, + footnote: footnoteDefinition_1, + definition: definition_1, + table: table_1, + paragraph: paragraph_1 +}; + +proto$3.inlineTokenizers = { + escape: _escape$1, + autoLink: autoLink_1, + url: url_1, + html: htmlInline, + link: link_1, + reference: reference_1, + strong: strong_1, + emphasis: emphasis_1, + deletion: _delete$1, + code: codeInline$1, + break: _break$1, + text: text_1 +}; + +// Expose precedence. +proto$3.blockMethods = keys$1(proto$3.blockTokenizers); +proto$3.inlineMethods = keys$1(proto$3.inlineTokenizers); + +// Tokenizers. +proto$3.tokenizeBlock = tokenizer('block'); +proto$3.tokenizeInline = tokenizer('inline'); +proto$3.tokenizeFactory = tokenizer; + +// Get all keys in `value`. +function keys$1(value) { + var result = []; + var key; + + for (key in value) { + result.push(key); + } + + return result +} + +var remarkParse = parse$a; +parse$a.Parser = parser; + +function parse$a(options) { + var settings = this.data('settings'); + var Local = unherit_1(parser); + + Local.prototype.options = immutable(Local.prototype.options, settings, options); + + this.Parser = Local; +} + +var identity_1 = identity; + +function identity(value) { + return value +} + +var enterLinkReference = enter; + +// Shortcut and collapsed link references need no escaping and encoding during +// the processing of child nodes (it must be implied from identifier). +// +// This toggler turns encoding and escaping off for shortcut and collapsed +// references. +// +// Implies `enterLink`. +function enter(compiler, node) { + var encode = compiler.encode; + var escape = compiler.escape; + var exitLink = compiler.enterLink(); + + if (node.referenceType !== 'shortcut' && node.referenceType !== 'collapsed') { + return exitLink + } + + compiler.escape = identity_1; + compiler.encode = identity_1; + + return exit + + function exit() { + compiler.encode = encode; + compiler.escape = escape; + exitLink(); + } +} + +var defaults$3 = { + gfm: true, + commonmark: false, + pedantic: false, + entities: 'false', + setext: false, + closeAtx: false, + looseTable: false, + spacedTable: true, + paddedTable: true, + stringLength: stringLength, + incrementListMarker: true, + fences: false, + fence: '`', + bullet: '-', + listItemIndent: 'tab', + rule: '*', + ruleSpaces: true, + ruleRepetition: 3, + strong: '*', + emphasis: '_' +}; + +function stringLength(value) { + return value.length +} + +const nbsp$2 = " "; +const iexcl$2 = "¡"; +const cent$2 = "¢"; +const pound$2 = "£"; +const curren$2 = "¤"; +const yen$2 = "¥"; +const brvbar$2 = "¦"; +const sect$2 = "§"; +const uml$2 = "¨"; +const copy$3 = "©"; +const ordf$2 = "ª"; +const laquo$2 = "«"; +const not$2 = "¬"; +const shy$2 = "­"; +const reg$2 = "®"; +const macr$2 = "¯"; +const deg$2 = "°"; +const plusmn$2 = "±"; +const sup2$2 = "²"; +const sup3$2 = "³"; +const acute$2 = "´"; +const micro$2 = "µ"; +const para$2 = "¶"; +const middot$2 = "·"; +const cedil$2 = "¸"; +const sup1$2 = "¹"; +const ordm$2 = "º"; +const raquo$2 = "»"; +const frac14$2 = "¼"; +const frac12$2 = "½"; +const frac34$2 = "¾"; +const iquest$2 = "¿"; +const Agrave$2 = "À"; +const Aacute$2 = "Á"; +const Acirc$2 = "Â"; +const Atilde$2 = "Ã"; +const Auml$2 = "Ä"; +const Aring$2 = "Å"; +const AElig$2 = "Æ"; +const Ccedil$2 = "Ç"; +const Egrave$2 = "È"; +const Eacute$2 = "É"; +const Ecirc$2 = "Ê"; +const Euml$2 = "Ë"; +const Igrave$2 = "Ì"; +const Iacute$2 = "Í"; +const Icirc$2 = "Î"; +const Iuml$2 = "Ï"; +const ETH$2 = "Ð"; +const Ntilde$2 = "Ñ"; +const Ograve$2 = "Ò"; +const Oacute$2 = "Ó"; +const Ocirc$2 = "Ô"; +const Otilde$2 = "Õ"; +const Ouml$2 = "Ö"; +const times$2 = "×"; +const Oslash$2 = "Ø"; +const Ugrave$2 = "Ù"; +const Uacute$2 = "Ú"; +const Ucirc$2 = "Û"; +const Uuml$2 = "Ü"; +const Yacute$2 = "Ý"; +const THORN$2 = "Þ"; +const szlig$2 = "ß"; +const agrave$2 = "à"; +const aacute$2 = "á"; +const acirc$2 = "â"; +const atilde$2 = "ã"; +const auml$2 = "ä"; +const aring$2 = "å"; +const aelig$2 = "æ"; +const ccedil$2 = "ç"; +const egrave$2 = "è"; +const eacute$2 = "é"; +const ecirc$2 = "ê"; +const euml$2 = "ë"; +const igrave$2 = "ì"; +const iacute$2 = "í"; +const icirc$2 = "î"; +const iuml$2 = "ï"; +const eth$2 = "ð"; +const ntilde$2 = "ñ"; +const ograve$2 = "ò"; +const oacute$2 = "ó"; +const ocirc$2 = "ô"; +const otilde$2 = "õ"; +const ouml$2 = "ö"; +const divide$2 = "÷"; +const oslash$2 = "ø"; +const ugrave$2 = "ù"; +const uacute$2 = "ú"; +const ucirc$2 = "û"; +const uuml$2 = "ü"; +const yacute$2 = "ý"; +const thorn$2 = "þ"; +const yuml$2 = "ÿ"; +const fnof$1 = "ƒ"; +const Alpha$1 = "Α"; +const Beta$1 = "Β"; +const Gamma$1 = "Γ"; +const Delta$1 = "Δ"; +const Epsilon$1 = "Ε"; +const Zeta$1 = "Ζ"; +const Eta$1 = "Η"; +const Theta$1 = "Θ"; +const Iota$1 = "Ι"; +const Kappa$1 = "Κ"; +const Lambda$1 = "Λ"; +const Mu$1 = "Μ"; +const Nu$1 = "Ν"; +const Xi$1 = "Ξ"; +const Omicron$1 = "Ο"; +const Pi$1 = "Π"; +const Rho$1 = "Ρ"; +const Sigma$1 = "Σ"; +const Tau$1 = "Τ"; +const Upsilon$1 = "Υ"; +const Phi$1 = "Φ"; +const Chi$1 = "Χ"; +const Psi$1 = "Ψ"; +const Omega$1 = "Ω"; +const alpha$1 = "α"; +const beta$1 = "β"; +const gamma$1 = "γ"; +const delta$1 = "δ"; +const epsilon$1 = "ε"; +const zeta$1 = "ζ"; +const eta$1 = "η"; +const theta$1 = "θ"; +const iota$1 = "ι"; +const kappa$1 = "κ"; +const lambda$1 = "λ"; +const mu$1 = "μ"; +const nu$1 = "ν"; +const xi$1 = "ξ"; +const omicron$1 = "ο"; +const pi$1 = "π"; +const rho$1 = "ρ"; +const sigmaf$1 = "ς"; +const sigma$1 = "σ"; +const tau$1 = "τ"; +const upsilon$1 = "υ"; +const phi$1 = "φ"; +const chi$1 = "χ"; +const psi$1 = "ψ"; +const omega$1 = "ω"; +const thetasym$1 = "ϑ"; +const upsih$1 = "ϒ"; +const piv$1 = "ϖ"; +const bull$1 = "•"; +const hellip$1 = "…"; +const prime$1 = "′"; +const Prime$1 = "″"; +const oline$1 = "‾"; +const frasl$1 = "⁄"; +const weierp$1 = "℘"; +const image$2 = "ℑ"; +const real$1 = "ℜ"; +const trade$1 = "™"; +const alefsym$1 = "ℵ"; +const larr$1 = "←"; +const uarr$1 = "↑"; +const rarr$1 = "→"; +const darr$1 = "↓"; +const harr$1 = "↔"; +const crarr$1 = "↵"; +const lArr$1 = "⇐"; +const uArr$1 = "⇑"; +const rArr$1 = "⇒"; +const dArr$1 = "⇓"; +const hArr$1 = "⇔"; +const forall$1 = "∀"; +const part$1 = "∂"; +const exist$1 = "∃"; +const empty$1 = "∅"; +const nabla$1 = "∇"; +const isin$1 = "∈"; +const notin$1 = "∉"; +const ni$1 = "∋"; +const prod$1 = "∏"; +const sum$1 = "∑"; +const minus$1 = "−"; +const lowast$1 = "∗"; +const radic$1 = "√"; +const prop$1 = "∝"; +const infin$1 = "∞"; +const ang$1 = "∠"; +const and$1 = "∧"; +const or$1 = "∨"; +const cap$1 = "∩"; +const cup$1 = "∪"; +const int$1 = "∫"; +const there4$1 = "∴"; +const sim$1 = "∼"; +const cong$1 = "≅"; +const asymp$1 = "≈"; +const ne$1 = "≠"; +const equiv$1 = "≡"; +const le$1 = "≤"; +const ge$1 = "≥"; +const sub$1 = "⊂"; +const sup$1 = "⊃"; +const nsub$1 = "⊄"; +const sube$1 = "⊆"; +const supe$1 = "⊇"; +const oplus$1 = "⊕"; +const otimes$1 = "⊗"; +const perp$1 = "⊥"; +const sdot$1 = "⋅"; +const lceil$1 = "⌈"; +const rceil$1 = "⌉"; +const lfloor$1 = "⌊"; +const rfloor$1 = "⌋"; +const lang$1 = "〈"; +const rang$1 = "〉"; +const loz$1 = "◊"; +const spades$1 = "♠"; +const clubs$1 = "♣"; +const hearts$1 = "♥"; +const diams$1 = "♦"; +const quot$2 = "\""; +const amp$2 = "&"; +const lt$2 = "<"; +const gt$2 = ">"; +const OElig$1 = "Œ"; +const oelig$1 = "œ"; +const Scaron$1 = "Š"; +const scaron$1 = "š"; +const Yuml$1 = "Ÿ"; +const circ$1 = "ˆ"; +const tilde$3 = "˜"; +const ensp$1 = " "; +const emsp$1 = " "; +const thinsp$1 = " "; +const zwnj$1 = "‌"; +const zwj$1 = "‍"; +const lrm$1 = "‎"; +const rlm$1 = "‏"; +const ndash$1 = "–"; +const mdash$1 = "—"; +const lsquo$1 = "‘"; +const rsquo$1 = "’"; +const sbquo$1 = "‚"; +const ldquo$1 = "“"; +const rdquo$1 = "”"; +const bdquo$1 = "„"; +const dagger$1 = "†"; +const Dagger$1 = "‡"; +const permil$1 = "‰"; +const lsaquo$1 = "‹"; +const rsaquo$1 = "›"; +const euro$1 = "€"; +var index$4 = { + nbsp: nbsp$2, + iexcl: iexcl$2, + cent: cent$2, + pound: pound$2, + curren: curren$2, + yen: yen$2, + brvbar: brvbar$2, + sect: sect$2, + uml: uml$2, + copy: copy$3, + ordf: ordf$2, + laquo: laquo$2, + not: not$2, + shy: shy$2, + reg: reg$2, + macr: macr$2, + deg: deg$2, + plusmn: plusmn$2, + sup2: sup2$2, + sup3: sup3$2, + acute: acute$2, + micro: micro$2, + para: para$2, + middot: middot$2, + cedil: cedil$2, + sup1: sup1$2, + ordm: ordm$2, + raquo: raquo$2, + frac14: frac14$2, + frac12: frac12$2, + frac34: frac34$2, + iquest: iquest$2, + Agrave: Agrave$2, + Aacute: Aacute$2, + Acirc: Acirc$2, + Atilde: Atilde$2, + Auml: Auml$2, + Aring: Aring$2, + AElig: AElig$2, + Ccedil: Ccedil$2, + Egrave: Egrave$2, + Eacute: Eacute$2, + Ecirc: Ecirc$2, + Euml: Euml$2, + Igrave: Igrave$2, + Iacute: Iacute$2, + Icirc: Icirc$2, + Iuml: Iuml$2, + ETH: ETH$2, + Ntilde: Ntilde$2, + Ograve: Ograve$2, + Oacute: Oacute$2, + Ocirc: Ocirc$2, + Otilde: Otilde$2, + Ouml: Ouml$2, + times: times$2, + Oslash: Oslash$2, + Ugrave: Ugrave$2, + Uacute: Uacute$2, + Ucirc: Ucirc$2, + Uuml: Uuml$2, + Yacute: Yacute$2, + THORN: THORN$2, + szlig: szlig$2, + agrave: agrave$2, + aacute: aacute$2, + acirc: acirc$2, + atilde: atilde$2, + auml: auml$2, + aring: aring$2, + aelig: aelig$2, + ccedil: ccedil$2, + egrave: egrave$2, + eacute: eacute$2, + ecirc: ecirc$2, + euml: euml$2, + igrave: igrave$2, + iacute: iacute$2, + icirc: icirc$2, + iuml: iuml$2, + eth: eth$2, + ntilde: ntilde$2, + ograve: ograve$2, + oacute: oacute$2, + ocirc: ocirc$2, + otilde: otilde$2, + ouml: ouml$2, + divide: divide$2, + oslash: oslash$2, + ugrave: ugrave$2, + uacute: uacute$2, + ucirc: ucirc$2, + uuml: uuml$2, + yacute: yacute$2, + thorn: thorn$2, + yuml: yuml$2, + fnof: fnof$1, + Alpha: Alpha$1, + Beta: Beta$1, + Gamma: Gamma$1, + Delta: Delta$1, + Epsilon: Epsilon$1, + Zeta: Zeta$1, + Eta: Eta$1, + Theta: Theta$1, + Iota: Iota$1, + Kappa: Kappa$1, + Lambda: Lambda$1, + Mu: Mu$1, + Nu: Nu$1, + Xi: Xi$1, + Omicron: Omicron$1, + Pi: Pi$1, + Rho: Rho$1, + Sigma: Sigma$1, + Tau: Tau$1, + Upsilon: Upsilon$1, + Phi: Phi$1, + Chi: Chi$1, + Psi: Psi$1, + Omega: Omega$1, + alpha: alpha$1, + beta: beta$1, + gamma: gamma$1, + delta: delta$1, + epsilon: epsilon$1, + zeta: zeta$1, + eta: eta$1, + theta: theta$1, + iota: iota$1, + kappa: kappa$1, + lambda: lambda$1, + mu: mu$1, + nu: nu$1, + xi: xi$1, + omicron: omicron$1, + pi: pi$1, + rho: rho$1, + sigmaf: sigmaf$1, + sigma: sigma$1, + tau: tau$1, + upsilon: upsilon$1, + phi: phi$1, + chi: chi$1, + psi: psi$1, + omega: omega$1, + thetasym: thetasym$1, + upsih: upsih$1, + piv: piv$1, + bull: bull$1, + hellip: hellip$1, + prime: prime$1, + Prime: Prime$1, + oline: oline$1, + frasl: frasl$1, + weierp: weierp$1, + image: image$2, + real: real$1, + trade: trade$1, + alefsym: alefsym$1, + larr: larr$1, + uarr: uarr$1, + rarr: rarr$1, + darr: darr$1, + harr: harr$1, + crarr: crarr$1, + lArr: lArr$1, + uArr: uArr$1, + rArr: rArr$1, + dArr: dArr$1, + hArr: hArr$1, + forall: forall$1, + part: part$1, + exist: exist$1, + empty: empty$1, + nabla: nabla$1, + isin: isin$1, + notin: notin$1, + ni: ni$1, + prod: prod$1, + sum: sum$1, + minus: minus$1, + lowast: lowast$1, + radic: radic$1, + prop: prop$1, + infin: infin$1, + ang: ang$1, + and: and$1, + or: or$1, + cap: cap$1, + cup: cup$1, + int: int$1, + there4: there4$1, + sim: sim$1, + cong: cong$1, + asymp: asymp$1, + ne: ne$1, + equiv: equiv$1, + le: le$1, + ge: ge$1, + sub: sub$1, + sup: sup$1, + nsub: nsub$1, + sube: sube$1, + supe: supe$1, + oplus: oplus$1, + otimes: otimes$1, + perp: perp$1, + sdot: sdot$1, + lceil: lceil$1, + rceil: rceil$1, + lfloor: lfloor$1, + rfloor: rfloor$1, + lang: lang$1, + rang: rang$1, + loz: loz$1, + spades: spades$1, + clubs: clubs$1, + hearts: hearts$1, + diams: diams$1, + quot: quot$2, + amp: amp$2, + lt: lt$2, + gt: gt$2, + OElig: OElig$1, + oelig: oelig$1, + Scaron: Scaron$1, + scaron: scaron$1, + Yuml: Yuml$1, + circ: circ$1, + tilde: tilde$3, + ensp: ensp$1, + emsp: emsp$1, + thinsp: thinsp$1, + zwnj: zwnj$1, + zwj: zwj$1, + lrm: lrm$1, + rlm: rlm$1, + ndash: ndash$1, + mdash: mdash$1, + lsquo: lsquo$1, + rsquo: rsquo$1, + sbquo: sbquo$1, + ldquo: ldquo$1, + rdquo: rdquo$1, + bdquo: bdquo$1, + dagger: dagger$1, + Dagger: Dagger$1, + permil: permil$1, + lsaquo: lsaquo$1, + rsaquo: rsaquo$1, + euro: euro$1 +}; + +var characterEntitiesHtml4 = /*#__PURE__*/Object.freeze({ + __proto__: null, + nbsp: nbsp$2, + iexcl: iexcl$2, + cent: cent$2, + pound: pound$2, + curren: curren$2, + yen: yen$2, + brvbar: brvbar$2, + sect: sect$2, + uml: uml$2, + copy: copy$3, + ordf: ordf$2, + laquo: laquo$2, + not: not$2, + shy: shy$2, + reg: reg$2, + macr: macr$2, + deg: deg$2, + plusmn: plusmn$2, + sup2: sup2$2, + sup3: sup3$2, + acute: acute$2, + micro: micro$2, + para: para$2, + middot: middot$2, + cedil: cedil$2, + sup1: sup1$2, + ordm: ordm$2, + raquo: raquo$2, + frac14: frac14$2, + frac12: frac12$2, + frac34: frac34$2, + iquest: iquest$2, + Agrave: Agrave$2, + Aacute: Aacute$2, + Acirc: Acirc$2, + Atilde: Atilde$2, + Auml: Auml$2, + Aring: Aring$2, + AElig: AElig$2, + Ccedil: Ccedil$2, + Egrave: Egrave$2, + Eacute: Eacute$2, + Ecirc: Ecirc$2, + Euml: Euml$2, + Igrave: Igrave$2, + Iacute: Iacute$2, + Icirc: Icirc$2, + Iuml: Iuml$2, + ETH: ETH$2, + Ntilde: Ntilde$2, + Ograve: Ograve$2, + Oacute: Oacute$2, + Ocirc: Ocirc$2, + Otilde: Otilde$2, + Ouml: Ouml$2, + times: times$2, + Oslash: Oslash$2, + Ugrave: Ugrave$2, + Uacute: Uacute$2, + Ucirc: Ucirc$2, + Uuml: Uuml$2, + Yacute: Yacute$2, + THORN: THORN$2, + szlig: szlig$2, + agrave: agrave$2, + aacute: aacute$2, + acirc: acirc$2, + atilde: atilde$2, + auml: auml$2, + aring: aring$2, + aelig: aelig$2, + ccedil: ccedil$2, + egrave: egrave$2, + eacute: eacute$2, + ecirc: ecirc$2, + euml: euml$2, + igrave: igrave$2, + iacute: iacute$2, + icirc: icirc$2, + iuml: iuml$2, + eth: eth$2, + ntilde: ntilde$2, + ograve: ograve$2, + oacute: oacute$2, + ocirc: ocirc$2, + otilde: otilde$2, + ouml: ouml$2, + divide: divide$2, + oslash: oslash$2, + ugrave: ugrave$2, + uacute: uacute$2, + ucirc: ucirc$2, + uuml: uuml$2, + yacute: yacute$2, + thorn: thorn$2, + yuml: yuml$2, + fnof: fnof$1, + Alpha: Alpha$1, + Beta: Beta$1, + Gamma: Gamma$1, + Delta: Delta$1, + Epsilon: Epsilon$1, + Zeta: Zeta$1, + Eta: Eta$1, + Theta: Theta$1, + Iota: Iota$1, + Kappa: Kappa$1, + Lambda: Lambda$1, + Mu: Mu$1, + Nu: Nu$1, + Xi: Xi$1, + Omicron: Omicron$1, + Pi: Pi$1, + Rho: Rho$1, + Sigma: Sigma$1, + Tau: Tau$1, + Upsilon: Upsilon$1, + Phi: Phi$1, + Chi: Chi$1, + Psi: Psi$1, + Omega: Omega$1, + alpha: alpha$1, + beta: beta$1, + gamma: gamma$1, + delta: delta$1, + epsilon: epsilon$1, + zeta: zeta$1, + eta: eta$1, + theta: theta$1, + iota: iota$1, + kappa: kappa$1, + lambda: lambda$1, + mu: mu$1, + nu: nu$1, + xi: xi$1, + omicron: omicron$1, + pi: pi$1, + rho: rho$1, + sigmaf: sigmaf$1, + sigma: sigma$1, + tau: tau$1, + upsilon: upsilon$1, + phi: phi$1, + chi: chi$1, + psi: psi$1, + omega: omega$1, + thetasym: thetasym$1, + upsih: upsih$1, + piv: piv$1, + bull: bull$1, + hellip: hellip$1, + prime: prime$1, + Prime: Prime$1, + oline: oline$1, + frasl: frasl$1, + weierp: weierp$1, + image: image$2, + real: real$1, + trade: trade$1, + alefsym: alefsym$1, + larr: larr$1, + uarr: uarr$1, + rarr: rarr$1, + darr: darr$1, + harr: harr$1, + crarr: crarr$1, + lArr: lArr$1, + uArr: uArr$1, + rArr: rArr$1, + dArr: dArr$1, + hArr: hArr$1, + forall: forall$1, + part: part$1, + exist: exist$1, + empty: empty$1, + nabla: nabla$1, + isin: isin$1, + notin: notin$1, + ni: ni$1, + prod: prod$1, + sum: sum$1, + minus: minus$1, + lowast: lowast$1, + radic: radic$1, + prop: prop$1, + infin: infin$1, + ang: ang$1, + and: and$1, + or: or$1, + cap: cap$1, + cup: cup$1, + int: int$1, + there4: there4$1, + sim: sim$1, + cong: cong$1, + asymp: asymp$1, + ne: ne$1, + equiv: equiv$1, + le: le$1, + ge: ge$1, + sub: sub$1, + sup: sup$1, + nsub: nsub$1, + sube: sube$1, + supe: supe$1, + oplus: oplus$1, + otimes: otimes$1, + perp: perp$1, + sdot: sdot$1, + lceil: lceil$1, + rceil: rceil$1, + lfloor: lfloor$1, + rfloor: rfloor$1, + lang: lang$1, + rang: rang$1, + loz: loz$1, + spades: spades$1, + clubs: clubs$1, + hearts: hearts$1, + diams: diams$1, + quot: quot$2, + amp: amp$2, + lt: lt$2, + gt: gt$2, + OElig: OElig$1, + oelig: oelig$1, + Scaron: Scaron$1, + scaron: scaron$1, + Yuml: Yuml$1, + circ: circ$1, + tilde: tilde$3, + ensp: ensp$1, + emsp: emsp$1, + thinsp: thinsp$1, + zwnj: zwnj$1, + zwj: zwj$1, + lrm: lrm$1, + rlm: rlm$1, + ndash: ndash$1, + mdash: mdash$1, + lsquo: lsquo$1, + rsquo: rsquo$1, + sbquo: sbquo$1, + ldquo: ldquo$1, + rdquo: rdquo$1, + bdquo: bdquo$1, + dagger: dagger$1, + Dagger: Dagger$1, + permil: permil$1, + lsaquo: lsaquo$1, + rsaquo: rsaquo$1, + euro: euro$1, + 'default': index$4 +}); + +var dangerous = [ + "cent", + "copy", + "divide", + "gt", + "lt", + "not", + "para", + "times" +]; + +var dangerous$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': dangerous +}); + +var entities = getCjsExportFromNamespace(characterEntitiesHtml4); + +var dangerous$2 = getCjsExportFromNamespace(dangerous$1); + +var decimal$1 = isDecimal; + + + +var stringifyEntities = encode; +encode.escape = escape$2; + +var own$5 = {}.hasOwnProperty; + +// List of enforced escapes. +var escapes$1 = ['"', "'", '<', '>', '&', '`']; + +// Map of characters to names. +var characters = construct(); + +// Default escapes. +var defaultEscapes = toExpression(escapes$1); + +// Surrogate pairs. +var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +// Non-ASCII characters. +// eslint-disable-next-line no-control-regex, unicorn/no-hex-escape +var bmp = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; + +// Encode special characters in `value`. +function encode(value, options) { + var settings = options || {}; + var subset = settings.subset; + var set = subset ? toExpression(subset) : defaultEscapes; + var escapeOnly = settings.escapeOnly; + var omit = settings.omitOptionalSemicolons; + + value = value.replace(set, replace); + + if (subset || escapeOnly) { + return value + } + + return value + .replace(surrogatePair, replaceSurrogatePair) + .replace(bmp, replace) + + function replaceSurrogatePair(pair, pos, val) { + return toHexReference( + (pair.charCodeAt(0) - 0xd800) * 0x400 + + pair.charCodeAt(1) - + 0xdc00 + + 0x10000, + val.charAt(pos + 2), + omit + ) + } + + function replace(char, pos, val) { + return one$1(char, val.charAt(pos + 1), settings) + } +} + +// Shortcut to escape special characters in HTML. +function escape$2(value) { + return encode(value, {escapeOnly: true, useNamedReferences: true}) +} + +// Encode `char` according to `options`. +function one$1(char, next, options) { + var shortest = options.useShortestReferences; + var omit = options.omitOptionalSemicolons; + var named; + var code; + var numeric; + var decimal; + + if ((shortest || options.useNamedReferences) && own$5.call(characters, char)) { + named = toNamed(characters[char], next, omit, options.attribute); + } + + if (shortest || !named) { + code = char.charCodeAt(0); + numeric = toHexReference(code, next, omit); + + // Use the shortest numeric reference when requested. + // A simple algorithm would use decimal for all code points under 100, as + // those are shorter than hexadecimal: + // + // * `c` vs `c` (decimal shorter) + // * `d` vs `d` (equal) + // + // However, because we take `next` into consideration when `omit` is used, + // And it would be possible that decimals are shorter on bigger values as + // well if `next` is hexadecimal but not decimal, we instead compare both. + if (shortest) { + decimal = toDecimalReference(code, next, omit); + + if (decimal.length < numeric.length) { + numeric = decimal; + } + } + } + + if (named && (!shortest || named.length < numeric.length)) { + return named + } + + return numeric +} + +// Transform `code` into an entity. +function toNamed(name, next, omit, attribute) { + var value = '&' + name; + + if ( + omit && + own$5.call(legacy, name) && + dangerous$2.indexOf(name) === -1 && + (!attribute || (next && next !== '=' && !isAlphanumerical(next))) + ) { + return value + } + + return value + ';' +} + +// Transform `code` into a hexadecimal character reference. +function toHexReference(code, next, omit) { + var value = '&#x' + code.toString(16).toUpperCase(); + return omit && next && !isHexadecimal(next) ? value : value + ';' +} + +// Transform `code` into a decimal character reference. +function toDecimalReference(code, next, omit) { + var value = '&#' + String(code); + return omit && next && !decimal$1(next) ? value : value + ';' +} + +// Create an expression for `characters`. +function toExpression(characters) { + return new RegExp('[' + characters.join('') + ']', 'g') +} + +// Construct the map. +function construct() { + var chars = {}; + var name; + + for (name in entities) { + chars[entities[name]] = name; + } + + return chars +} + +var isAlphanumeric = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return !/[^0-9a-z\xDF-\xFF]/.test(str.toLowerCase()); +}; + +var entityPrefixLength = length; + +var ampersand$1 = '&'; + +// Returns the length of HTML entity that is a prefix of the given string +// (excluding the ampersand), 0 if it does not start with an entity. +function length(value) { + var prefix; + + /* istanbul ignore if - Currently also tested for at implemention, but we + * keep it here because that’s proper. */ + if (value.charAt(0) !== ampersand$1) { + return 0 + } + + prefix = value.split(ampersand$1, 2).join(ampersand$1); + + return prefix.length - parseEntities_1(prefix).length +} + +var _escape$2 = factory$6; + +var tab$f = '\t'; +var lineFeed$k = '\n'; +var space$i = ' '; +var numberSign$2 = '#'; +var ampersand$2 = '&'; +var leftParenthesis$3 = '('; +var rightParenthesis$4 = ')'; +var asterisk$4 = '*'; +var plusSign$1 = '+'; +var dash$5 = '-'; +var dot$3 = '.'; +var colon$5 = ':'; +var lessThan$7 = '<'; +var greaterThan$4 = '>'; +var leftSquareBracket$5 = '['; +var backslash$a = '\\'; +var rightSquareBracket$5 = ']'; +var underscore$4 = '_'; +var graveAccent$3 = '`'; +var verticalBar$1 = '|'; +var tilde$4 = '~'; +var exclamationMark$4 = '!'; + +var entities$1 = { + '<': '<', + ':': ':', + '&': '&', + '|': '|', + '~': '~' +}; + +var shortcut$1 = 'shortcut'; +var mailto$2 = 'mailto'; +var https$1 = 'https'; +var http$1 = 'http'; + +var blankExpression = /\n\s*$/; + +// Factory to escape characters. +function factory$6(options) { + return escape + + // Escape punctuation characters in a node’s value. + function escape(value, node, parent) { + var self = this; + var gfm = options.gfm; + var commonmark = options.commonmark; + var pedantic = options.pedantic; + var markers = commonmark ? [dot$3, rightParenthesis$4] : [dot$3]; + var siblings = parent && parent.children; + var index = siblings && siblings.indexOf(node); + var prev = siblings && siblings[index - 1]; + var next = siblings && siblings[index + 1]; + var length = value.length; + var escapable = markdownEscapes(options); + var position = -1; + var queue = []; + var escaped = queue; + var afterNewLine; + var character; + var wordCharBefore; + var wordCharAfter; + var offset; + var replace; + + if (prev) { + afterNewLine = text$1(prev) && blankExpression.test(prev.value); + } else { + afterNewLine = + !parent || parent.type === 'root' || parent.type === 'paragraph'; + } + + while (++position < length) { + character = value.charAt(position); + replace = false; + + if (character === '\n') { + afterNewLine = true; + } else if ( + character === backslash$a || + character === graveAccent$3 || + character === asterisk$4 || + character === leftSquareBracket$5 || + character === lessThan$7 || + (character === ampersand$2 && entityPrefixLength(value.slice(position)) > 0) || + (character === rightSquareBracket$5 && self.inLink) || + (gfm && character === tilde$4 && value.charAt(position + 1) === tilde$4) || + (gfm && + character === verticalBar$1 && + (self.inTable || alignment(value, position))) || + (character === underscore$4 && + // Delegate leading/trailing underscores to the multinode version below. + position > 0 && + position < length - 1 && + (pedantic || + !isAlphanumeric(value.charAt(position - 1)) || + !isAlphanumeric(value.charAt(position + 1)))) || + (gfm && !self.inLink && character === colon$5 && protocol(queue.join(''))) + ) { + replace = true; + } else if (afterNewLine) { + if ( + character === greaterThan$4 || + character === numberSign$2 || + character === asterisk$4 || + character === dash$5 || + character === plusSign$1 + ) { + replace = true; + } else if (isDecimal(character)) { + offset = position + 1; + + while (offset < length) { + if (!isDecimal(value.charAt(offset))) { + break + } + + offset++; + } + + if (markers.indexOf(value.charAt(offset)) !== -1) { + next = value.charAt(offset + 1); + + if (!next || next === space$i || next === tab$f || next === lineFeed$k) { + queue.push(value.slice(position, offset)); + position = offset; + character = value.charAt(position); + replace = true; + } + } + } + } + + if (afterNewLine && !isWhitespaceCharacter(character)) { + afterNewLine = false; + } + + queue.push(replace ? one(character) : character); + } + + // Multi-node versions. + if (siblings && text$1(node)) { + // Check for an opening parentheses after a link-reference (which can be + // joined by white-space). + if (prev && prev.referenceType === shortcut$1) { + position = -1; + length = escaped.length; + + while (++position < length) { + character = escaped[position]; + + if (character === space$i || character === tab$f) { + continue + } + + if (character === leftParenthesis$3 || character === colon$5) { + escaped[position] = one(character); + } + + break + } + + // If the current node is all spaces / tabs, preceded by a shortcut, + // and followed by a text starting with `(`, escape it. + if ( + text$1(next) && + position === length && + next.value.charAt(0) === leftParenthesis$3 + ) { + escaped.push(backslash$a); + } + } + + // Ensure non-auto-links are not seen as links. This pattern needs to + // check the preceding nodes too. + if ( + gfm && + !self.inLink && + text$1(prev) && + value.charAt(0) === colon$5 && + protocol(prev.value.slice(-6)) + ) { + escaped[0] = one(colon$5); + } + + // Escape ampersand if it would otherwise start an entity. + if ( + text$1(next) && + value.charAt(length - 1) === ampersand$2 && + entityPrefixLength(ampersand$2 + next.value) !== 0 + ) { + escaped[escaped.length - 1] = one(ampersand$2); + } + + // Escape exclamation marks immediately followed by links. + if ( + next && + next.type === 'link' && + value.charAt(length - 1) === exclamationMark$4 + ) { + escaped[escaped.length - 1] = one(exclamationMark$4); + } + + // Escape double tildes in GFM. + if ( + gfm && + text$1(next) && + value.charAt(length - 1) === tilde$4 && + next.value.charAt(0) === tilde$4 + ) { + escaped.splice(escaped.length - 1, 0, backslash$a); + } + + // Escape underscores, but not mid-word (unless in pedantic mode). + wordCharBefore = text$1(prev) && isAlphanumeric(prev.value.slice(-1)); + wordCharAfter = text$1(next) && isAlphanumeric(next.value.charAt(0)); + + if (length === 1) { + if ( + value === underscore$4 && + (pedantic || !wordCharBefore || !wordCharAfter) + ) { + escaped.unshift(backslash$a); + } + } else { + if ( + value.charAt(0) === underscore$4 && + (pedantic || !wordCharBefore || !isAlphanumeric(value.charAt(1))) + ) { + escaped.unshift(backslash$a); + } + + if ( + value.charAt(length - 1) === underscore$4 && + (pedantic || + !wordCharAfter || + !isAlphanumeric(value.charAt(length - 2))) + ) { + escaped.splice(escaped.length - 1, 0, backslash$a); + } + } + } + + return escaped.join('') + + function one(character) { + return escapable.indexOf(character) === -1 + ? entities$1[character] + : backslash$a + character + } + } +} + +// Check if `index` in `value` is inside an alignment row. +function alignment(value, index) { + var start = value.lastIndexOf(lineFeed$k, index); + var end = value.indexOf(lineFeed$k, index); + var char; + + end = end === -1 ? value.length : end; + + while (++start < end) { + char = value.charAt(start); + + if ( + char !== colon$5 && + char !== dash$5 && + char !== space$i && + char !== verticalBar$1 + ) { + return false + } + } + + return true +} + +// Check if `node` is a text node. +function text$1(node) { + return node && node.type === 'text' +} + +// Check if `value` ends in a protocol. +function protocol(value) { + var val = value.slice(-6).toLowerCase(); + return val === mailto$2 || val.slice(-5) === https$1 || val.slice(-4) === http$1 +} + +var setOptions_1$1 = setOptions$1; + +// Map of applicable enums. +var maps = { + entities: {true: true, false: true, numbers: true, escape: true}, + bullet: {'*': true, '-': true, '+': true}, + rule: {'-': true, _: true, '*': true}, + listItemIndent: {tab: true, mixed: true, 1: true}, + emphasis: {_: true, '*': true}, + strong: {_: true, '*': true}, + fence: {'`': true, '~': true} +}; + +// Expose `validate`. +var validate = { + boolean: validateBoolean, + string: validateString, + number: validateNumber, + function: validateFunction +}; + +// Set options. Does not overwrite previously set options. +function setOptions$1(options) { + var self = this; + var current = self.options; + var ruleRepetition; + var key; + + if (options == null) { + options = {}; + } else if (typeof options === 'object') { + options = immutable(options); + } else { + throw new Error('Invalid value `' + options + '` for setting `options`') + } + + for (key in defaults$3) { + validate[typeof defaults$3[key]](options, key, current[key], maps[key]); + } + + ruleRepetition = options.ruleRepetition; + + if (ruleRepetition && ruleRepetition < 3) { + raise(ruleRepetition, 'options.ruleRepetition'); + } + + self.encode = encodeFactory(String(options.entities)); + self.escape = _escape$2(options); + + self.options = options; + + return self +} + +// Validate a value to be boolean. Defaults to `def`. Raises an exception with +// `context[name]` when not a boolean. +function validateBoolean(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (typeof value !== 'boolean') { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be boolean. Defaults to `def`. Raises an exception with +// `context[name]` when not a boolean. +function validateNumber(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (isNaN(value)) { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be in `map`. Defaults to `def`. Raises an exception +// with `context[name]` when not in `map`. +function validateString(context, name, def, map) { + var value = context[name]; + + if (value == null) { + value = def; + } + + value = String(value); + + if (!(value in map)) { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be function. Defaults to `def`. Raises an exception +// with `context[name]` when not a function. +function validateFunction(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (typeof value !== 'function') { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Factory to encode HTML entities. Creates a no-operation function when +// `type` is `'false'`, a function which encodes using named references when +// `type` is `'true'`, and a function which encodes using numbered references +// when `type` is `'numbers'`. +function encodeFactory(type) { + var options = {}; + + if (type === 'false') { + return identity_1 + } + + if (type === 'true') { + options.useNamedReferences = true; + } + + if (type === 'escape') { + options.escapeOnly = true; + options.useNamedReferences = true; + } + + return wrapped + + // Encode HTML entities using the bound options. + function wrapped(value) { + return stringifyEntities(value, options) + } +} + +// Throw an exception with in its `message` `value` and `name`. +function raise(value, name) { + throw new Error('Invalid value `' + value + '` for setting `' + name + '`') +} + +var mdastUtilCompact = compact; + +// Make an mdast tree compact by merging adjacent text nodes. +function compact(tree, commonmark) { + unistUtilVisit(tree, visitor); + + return tree + + function visitor(child, index, parent) { + var siblings = parent ? parent.children : []; + var prev = index && siblings[index - 1]; + + if ( + prev && + child.type === prev.type && + mergeable$1(prev, commonmark) && + mergeable$1(child, commonmark) + ) { + if (child.value) { + prev.value += child.value; + } + + if (child.children) { + prev.children = prev.children.concat(child.children); + } + + siblings.splice(index, 1); + + if (prev.position && child.position) { + prev.position.end = child.position.end; + } + + return index + } + } +} + +function mergeable$1(node, commonmark) { + var start; + var end; + + if (node.type === 'text') { + if (!node.position) { + return true + } + + start = node.position.start; + end = node.position.end; + + // Only merge nodes which occupy the same size as their `value`. + return ( + start.line !== end.line || end.column - start.column === node.value.length + ) + } + + return commonmark && node.type === 'blockquote' +} + +var compile_1$1 = compile$3; + +// Stringify the given tree. +function compile$3() { + return this.visit(mdastUtilCompact(this.tree, this.options.commonmark)) +} + +var one_1 = one$2; + +function one$2(node, parent) { + var self = this; + var visitors = self.visitors; + + // Fail on unknown nodes. + if (typeof visitors[node.type] !== 'function') { + self.file.fail( + new Error( + 'Missing compiler for node of type `' + node.type + '`: `' + node + '`' + ), + node + ); + } + + return visitors[node.type].call(self, node, parent) +} + +var all_1 = all; + +// Visit all children of `parent`. +function all(parent) { + var self = this; + var children = parent.children; + var length = children.length; + var results = []; + var index = -1; + + while (++index < length) { + results[index] = self.visit(children[index], parent); + } + + return results +} + +var block_1 = block$1; + +var lineFeed$l = '\n'; + +var blank$1 = lineFeed$l + lineFeed$l; +var triple = blank$1 + lineFeed$l; +var comment$1 = blank$1 + '' + blank$1; + +// Stringify a block node with block children (e.g., `root` or `blockquote`). +// Knows about code following a list, or adjacent lists with similar bullets, +// and places an extra line feed between them. +function block$1(node) { + var self = this; + var options = self.options; + var fences = options.fences; + var gap = options.commonmark ? comment$1 : triple; + var values = []; + var children = node.children; + var length = children.length; + var index = -1; + var prev; + var child; + + while (++index < length) { + prev = child; + child = children[index]; + + if (prev) { + // A list preceding another list that are equally ordered, or a + // list preceding an indented code block, need a gap between them, + // so as not to see them as one list, or content of the list, + // respectively. + // + // In commonmark, only something that breaks both up can do that, + // so we opt for an empty, invisible comment. In other flavours, + // two blank lines are fine. + if ( + prev.type === 'list' && + ((child.type === 'list' && prev.ordered === child.ordered) || + (child.type === 'code' && !child.lang && !fences)) + ) { + values.push(gap); + } else { + values.push(blank$1); + } + } + + values.push(self.visit(child, node)); + } + + return values.join('') +} + +var orderedItems_1 = orderedItems; + +var lineFeed$m = '\n'; +var dot$4 = '.'; + +var blank$2 = lineFeed$m + lineFeed$m; + +// Visit ordered list items. +// +// Starts the list with +// `node.start` and increments each following list item +// bullet by one: +// +// 2. foo +// 3. bar +// +// In `incrementListMarker: false` mode, does not increment +// each marker and stays on `node.start`: +// +// 1. foo +// 1. bar +function orderedItems(node) { + var self = this; + var fn = self.visitors.listItem; + var increment = self.options.incrementListMarker; + var values = []; + var start = node.start; + var children = node.children; + var length = children.length; + var index = -1; + var bullet; + + start = start == null ? 1 : start; + + while (++index < length) { + bullet = (increment ? start + index : start) + dot$4; + values[index] = fn.call(self, children[index], node, index, bullet); + } + + return values.join(node.spread ? blank$2 : lineFeed$m) +} + +var unorderedItems_1 = unorderedItems; + +var lineFeed$n = '\n'; + +var blank$3 = lineFeed$n + lineFeed$n; + +// Visit unordered list items. Uses `options.bullet` as each item’s bullet. +function unorderedItems(node) { + var self = this; + var bullet = self.options.bullet; + var fn = self.visitors.listItem; + var children = node.children; + var length = children.length; + var index = -1; + var values = []; + + while (++index < length) { + values[index] = fn.call(self, children[index], node, index, bullet); + } + + return values.join(node.spread ? blank$3 : lineFeed$n) +} + +var root_1 = root$1; + +var lineFeed$o = '\n'; + +// Stringify a root. +// Adds a final newline to ensure valid POSIX files. */ +function root$1(node) { + var doc = this.block(node); + + if (doc.charAt(doc.length - 1) !== lineFeed$o) { + doc += lineFeed$o; + } + + return doc +} + +var text_1$1 = text$2; + +// Stringify text. +// Supports named entities in `settings.encode: true` mode: +// +// ```markdown +// AT&T +// ``` +// +// Supports numbered entities in `settings.encode: numbers` mode: +// +// ```markdown +// AT&T +// ``` +function text$2(node, parent) { + return this.encode(this.escape(node.value, node, parent), node) +} + +var heading_1 = heading; + +var lineFeed$p = '\n'; +var space$j = ' '; +var numberSign$3 = '#'; +var dash$6 = '-'; +var equalsTo$2 = '='; + +// Stringify a heading. +// +// In `setext: true` mode and when `depth` is smaller than three, creates a +// setext header: +// +// ```markdown +// Foo +// === +// ``` +// +// Otherwise, an ATX header is generated: +// +// ```markdown +// ### Foo +// ``` +// +// In `closeAtx: true` mode, the header is closed with hashes: +// +// ```markdown +// ### Foo ### +// ``` +function heading(node) { + var self = this; + var depth = node.depth; + var setext = self.options.setext; + var closeAtx = self.options.closeAtx; + var content = self.all(node).join(''); + var prefix; + + if (setext && depth < 3) { + return ( + content + lineFeed$p + repeatString(depth === 1 ? equalsTo$2 : dash$6, content.length) + ) + } + + prefix = repeatString(numberSign$3, node.depth); + + return prefix + space$j + content + (closeAtx ? space$j + prefix : '') +} + +var paragraph_1$1 = paragraph$1; + +function paragraph$1(node) { + return this.all(node).join('') +} + +var blockquote_1$1 = blockquote$1; + +var lineFeed$q = '\n'; +var space$k = ' '; +var greaterThan$5 = '>'; + +function blockquote$1(node) { + var values = this.block(node).split(lineFeed$q); + var result = []; + var length = values.length; + var index = -1; + var value; + + while (++index < length) { + value = values[index]; + result[index] = (value ? space$k : '') + value; + } + + return greaterThan$5 + result.join(lineFeed$q + greaterThan$5) +} + +var list_1$1 = list$1; + +function list$1(node) { + var fn = node.ordered ? this.visitOrderedItems : this.visitUnorderedItems; + return fn.call(this, node) +} + +var pad_1 = pad$1; + +var lineFeed$r = '\n'; +var space$l = ' '; + +var tabSize$5 = 4; + +// Pad `value` with `level * tabSize` spaces. Respects lines. Ignores empty +// lines. +function pad$1(value, level) { + var values = value.split(lineFeed$r); + var index = values.length; + var padding = repeatString(space$l, level * tabSize$5); + + while (index--) { + if (values[index].length !== 0) { + values[index] = padding + values[index]; + } + } + + return values.join(lineFeed$r) +} + +var listItem_1 = listItem$1; + +var lineFeed$s = '\n'; +var space$m = ' '; +var leftSquareBracket$6 = '['; +var rightSquareBracket$6 = ']'; +var lowercaseX$2 = 'x'; + +var ceil = Math.ceil; +var blank$4 = lineFeed$s + lineFeed$s; + +var tabSize$6 = 4; + +// Stringify a list item. +// +// Prefixes the content with a checked checkbox when `checked: true`: +// +// ```markdown +// [x] foo +// ``` +// +// Prefixes the content with an unchecked checkbox when `checked: false`: +// +// ```markdown +// [ ] foo +// ``` +function listItem$1(node, parent, position, bullet) { + var self = this; + var style = self.options.listItemIndent; + var marker = bullet || self.options.bullet; + var spread = node.spread == null ? true : node.spread; + var checked = node.checked; + var children = node.children; + var length = children.length; + var values = []; + var index = -1; + var value; + var indent; + var spacing; + + while (++index < length) { + values[index] = self.visit(children[index], node); + } + + value = values.join(spread ? blank$4 : lineFeed$s); + + if (typeof checked === 'boolean') { + // Note: I’d like to be able to only add the space between the check and + // the value, but unfortunately github does not support empty list-items + // with a checkbox :( + value = + leftSquareBracket$6 + + (checked ? lowercaseX$2 : space$m) + + rightSquareBracket$6 + + space$m + + value; + } + + if (style === '1' || (style === 'mixed' && value.indexOf(lineFeed$s) === -1)) { + indent = marker.length + 1; + spacing = space$m; + } else { + indent = ceil((marker.length + 1) / tabSize$6) * tabSize$6; + spacing = repeatString(space$m, indent - marker.length); + } + + return value + ? marker + spacing + pad_1(value, indent / tabSize$6).slice(indent) + : marker +} + +var longestStreak_1 = longestStreak; + +// Get the count of the longest repeating streak of `character` in `value`. +function longestStreak(value, character) { + var count = 0; + var maximum = 0; + var expected; + var index; + + if (typeof character !== 'string' || character.length !== 1) { + throw new Error('Expected character') + } + + value = String(value); + index = value.indexOf(character); + expected = index; + + while (index !== -1) { + count++; + + if (index === expected) { + if (count > maximum) { + maximum = count; + } + } else { + count = 1; + } + + expected = index + 1; + index = value.indexOf(character, expected); + } + + return maximum +} + +var inlineCode_1 = inlineCode$1; + +var graveAccentChar = '`'; +var lineFeed$t = 10; // '\n' +var space$n = 32; // ' ' +var graveAccent$4 = 96; // '`' + +// Stringify inline code. +// +// Knows about internal ticks (`\``), and ensures one more tick is used to +// enclose the inline code: +// +// ````markdown +// ```foo ``bar`` baz``` +// ```` +// +// Even knows about inital and final ticks: +// +// ``markdown +// `` `foo `` +// `` foo` `` +// ``` +function inlineCode$1(node) { + var value = node.value; + var ticks = repeatString(graveAccentChar, longestStreak_1(value, graveAccentChar) + 1); + var start = ticks; + var end = ticks; + var head = value.charCodeAt(0); + var tail = value.charCodeAt(value.length - 1); + var wrap = false; + var index; + var length; + + if (head === graveAccent$4 || tail === graveAccent$4) { + wrap = true; + } else if (value.length > 2 && ws(head) && ws(tail)) { + index = 1; + length = value.length - 1; + + while (++index < length) { + if (!ws(value.charCodeAt(index))) { + wrap = true; + break + } + } + } + + if (wrap) { + start += ' '; + end = ' ' + end; + } + + return start + value + end +} + +function ws(code) { + return code === lineFeed$t || code === space$n +} + +var code_1 = code; + +var lineFeed$u = '\n'; +var space$o = ' '; +var tilde$5 = '~'; +var graveAccent$5 = '`'; + +// Stringify code. +// Creates indented code when: +// +// - No language tag exists +// - Not in `fences: true` mode +// - A non-empty value exists +// +// Otherwise, GFM fenced code is created: +// +// ````markdown +// ```js +// foo(); +// ``` +// ```` +// +// When in ``fence: `~` `` mode, uses tildes as fences: +// +// ```markdown +// ~~~js +// foo(); +// ~~~ +// ``` +// +// Knows about internal fences: +// +// `````markdown +// ````markdown +// ```javascript +// foo(); +// ``` +// ```` +// ````` +function code(node, parent) { + var self = this; + var value = node.value; + var options = self.options; + var marker = options.fence; + var info = node.lang || ''; + var fence; + + if (info && node.meta) { + info += space$o + node.meta; + } + + info = self.encode(self.escape(info, node)); + + // Without (needed) fences. + if ( + !info && + !options.fences && + value && + value.charAt(0) !== lineFeed$u && + value.charAt(value.length - 1) !== lineFeed$u + ) { + // Throw when pedantic, in a list item which isn’t compiled using a tab. + if ( + parent && + parent.type === 'listItem' && + options.listItemIndent !== 'tab' && + options.pedantic + ) { + self.file.fail( + 'Cannot indent code properly. See https://git.io/fxKR8', + node.position + ); + } + + return pad_1(value, 1) + } + + // Backticks in the info string don’t work with backtick fenced code. + // Backticks (and tildes) are fine in tilde fenced code. + if (marker === graveAccent$5 && info.indexOf(graveAccent$5) !== -1) { + marker = tilde$5; + } + + fence = repeatString(marker, Math.max(longestStreak_1(value, marker) + 1, 3)); + + return fence + info + lineFeed$u + value + lineFeed$u + fence +} + +var html_1 = html$1; + +function html$1(node) { + return node.value +} + +var thematicBreak$1 = thematic; + +var space$p = ' '; + +// Stringify a `thematic-break`. +// The character used is configurable through `rule`: (`'_'`): +// +// ```markdown +// ___ +// ``` +// +// The number of repititions is defined through `ruleRepetition` (`6`): +// +// ```markdown +// ****** +// ``` +// +// Whether spaces delimit each character, is configured through `ruleSpaces` +// (`true`): +// ```markdown +// * * * +// ``` +function thematic() { + var options = this.options; + var rule = repeatString(options.rule, options.ruleRepetition); + return options.ruleSpaces ? rule.split('').join(space$p) : rule +} + +var strong_1$1 = strong$2; + +// Stringify a `strong`. +// +// The marker used is configurable by `strong`, which defaults to an asterisk +// (`'*'`) but also accepts an underscore (`'_'`): +// +// ```markdown +// __foo__ +// ``` +function strong$2(node) { + var marker = repeatString(this.options.strong, 2); + return marker + this.all(node).join('') + marker +} + +var emphasis_1$1 = emphasis$2; + +var underscore$5 = '_'; +var asterisk$5 = '*'; + +// Stringify an `emphasis`. +// +// The marker used is configurable through `emphasis`, which defaults to an +// underscore (`'_'`) but also accepts an asterisk (`'*'`): +// +// ```markdown +// *foo* +// ``` +// +// In `pedantic` mode, text which itself contains an underscore will cause the +// marker to default to an asterisk instead: +// +// ```markdown +// *foo_bar* +// ``` +function emphasis$2(node) { + var marker = this.options.emphasis; + var content = this.all(node).join(''); + + // When in pedantic mode, prevent using underscore as the marker when there + // are underscores in the content. + if ( + this.options.pedantic && + marker === underscore$5 && + content.indexOf(marker) !== -1 + ) { + marker = asterisk$5; + } + + return marker + content + marker +} + +var _break$2 = lineBreak; + +var backslash$b = '\\'; +var lineFeed$v = '\n'; +var space$q = ' '; + +var commonmark$1 = backslash$b + lineFeed$v; +var normal = space$q + space$q + lineFeed$v; + +function lineBreak() { + return this.options.commonmark ? commonmark$1 : normal +} + +var _delete$2 = strikethrough$1; + +var tilde$6 = '~'; + +var fence$1 = tilde$6 + tilde$6; + +function strikethrough$1(node) { + return fence$1 + this.all(node).join('') + fence$1 +} + +var ccount_1 = ccount; + +function ccount(value, character) { + var count = 0; + var index; + + value = String(value); + + if (typeof character !== 'string' || character.length !== 1) { + throw new Error('Expected character') + } + + index = value.indexOf(character); + + while (index !== -1) { + count++; + index = value.indexOf(character, index + 1); + } + + return count +} + +var encloseUri = enclose; + +var leftParenthesis$4 = '('; +var rightParenthesis$5 = ')'; +var lessThan$8 = '<'; +var greaterThan$6 = '>'; + +var expression = /\s/; + +// Wrap `url` in angle brackets when needed, or when +// forced. +// In links, images, and definitions, the URL part needs +// to be enclosed when it: +// +// - has a length of `0` +// - contains white-space +// - has more or less opening than closing parentheses +function enclose(uri, always) { + if ( + always || + uri.length === 0 || + expression.test(uri) || + ccount_1(uri, leftParenthesis$4) !== ccount_1(uri, rightParenthesis$5) + ) { + return lessThan$8 + uri + greaterThan$6 + } + + return uri +} + +var encloseTitle = enclose$1; + +var quotationMark$3 = '"'; +var apostrophe$3 = "'"; + +// There is currently no way to support nested delimiters across Markdown.pl, +// CommonMark, and GitHub (RedCarpet). The following code supports Markdown.pl +// and GitHub. +// CommonMark is not supported when mixing double- and single quotes inside a +// title. +function enclose$1(title) { + var delimiter = + title.indexOf(quotationMark$3) === -1 ? quotationMark$3 : apostrophe$3; + return delimiter + title + delimiter +} + +var link_1$1 = link$4; + +var space$r = ' '; +var leftSquareBracket$7 = '['; +var rightSquareBracket$7 = ']'; +var leftParenthesis$5 = '('; +var rightParenthesis$6 = ')'; + +// Expression for a protocol: +// See . +var protocol$1 = /^[a-z][a-z+.-]+:\/?/i; + +// Stringify a link. +// +// When no title exists, the compiled `children` equal `url`, and `url` starts +// with a protocol, an auto link is created: +// +// ```markdown +// +// ``` +// +// Otherwise, is smart about enclosing `url` (see `encloseURI()`) and `title` +// (see `encloseTitle()`). +// ``` +// +// ```markdown +// [foo]( 'An "example" e-mail') +// ``` +// +// Supports named entities in the `url` and `title` when in `settings.encode` +// mode. +function link$4(node) { + var self = this; + var content = self.encode(node.url || '', node); + var exit = self.enterLink(); + var escaped = self.encode(self.escape(node.url || '', node)); + var value = self.all(node).join(''); + + exit(); + + if (node.title == null && protocol$1.test(content) && escaped === value) { + // Backslash escapes do not work in autolinks, so we do not escape. + return encloseUri(self.encode(node.url), true) + } + + content = encloseUri(content); + + if (node.title) { + content += space$r + encloseTitle(self.encode(self.escape(node.title, node), node)); + } + + return ( + leftSquareBracket$7 + + value + + rightSquareBracket$7 + + leftParenthesis$5 + + content + + rightParenthesis$6 + ) +} + +var copyIdentifierEncoding = copy$4; + +var ampersand$3 = '&'; + +var punctuationExppresion = /[-!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~_]/; + +// For shortcut and collapsed reference links, the contents is also an +// identifier, so we need to restore the original encoding and escaping +// that were present in the source string. +// +// This function takes the unescaped & unencoded value from shortcut’s +// child nodes and the identifier and encodes the former according to +// the latter. +function copy$4(value, identifier) { + var length = value.length; + var count = identifier.length; + var result = []; + var position = 0; + var index = 0; + var start; + + while (index < length) { + // Take next non-punctuation characters from `value`. + start = index; + + while (index < length && !punctuationExppresion.test(value.charAt(index))) { + index += 1; + } + + result.push(value.slice(start, index)); + + // Advance `position` to the next punctuation character. + while ( + position < count && + !punctuationExppresion.test(identifier.charAt(position)) + ) { + position += 1; + } + + // Take next punctuation characters from `identifier`. + start = position; + + while ( + position < count && + punctuationExppresion.test(identifier.charAt(position)) + ) { + if (identifier.charAt(position) === ampersand$3) { + position += entityPrefixLength(identifier.slice(position)); + } + + position += 1; + } + + result.push(identifier.slice(start, position)); + + // Advance `index` to the next non-punctuation character. + while (index < length && punctuationExppresion.test(value.charAt(index))) { + index += 1; + } + } + + return result.join('') +} + +var label_1 = label; + +var leftSquareBracket$8 = '['; +var rightSquareBracket$8 = ']'; + +var shortcut$2 = 'shortcut'; +var collapsed$1 = 'collapsed'; + +// Stringify a reference label. +// Because link references are easily, mistakingly, created (for example, +// `[foo]`), reference nodes have an extra property depicting how it looked in +// the original document, so stringification can cause minimal changes. +function label(node) { + var type = node.referenceType; + + if (type === shortcut$2) { + return '' + } + + return ( + leftSquareBracket$8 + + (type === collapsed$1 ? '' : node.label || node.identifier) + + rightSquareBracket$8 + ) +} + +var linkReference_1 = linkReference; + +var leftSquareBracket$9 = '['; +var rightSquareBracket$9 = ']'; + +var shortcut$3 = 'shortcut'; +var collapsed$2 = 'collapsed'; + +function linkReference(node) { + var self = this; + var type = node.referenceType; + var exit = self.enterLinkReference(self, node); + var value = self.all(node).join(''); + + exit(); + + if (type === shortcut$3 || type === collapsed$2) { + value = copyIdentifierEncoding(value, node.label || node.identifier); + } + + return leftSquareBracket$9 + value + rightSquareBracket$9 + label_1(node) +} + +var imageReference_1 = imageReference; + +var leftSquareBracket$a = '['; +var rightSquareBracket$a = ']'; +var exclamationMark$5 = '!'; + +function imageReference(node) { + return ( + exclamationMark$5 + + leftSquareBracket$a + + (this.encode(node.alt, node) || '') + + rightSquareBracket$a + + label_1(node) + ) +} + +var definition_1$1 = definition$1; + +var space$s = ' '; +var colon$6 = ':'; +var leftSquareBracket$b = '['; +var rightSquareBracket$b = ']'; + +// Stringify an URL definition. +// +// Is smart about enclosing `url` (see `encloseURI()`) and `title` (see +// `encloseTitle()`). +// +// ```markdown +// [foo]: 'An "example" e-mail' +// ``` +function definition$1(node) { + var content = encloseUri(node.url); + + if (node.title) { + content += space$s + encloseTitle(node.title); + } + + return ( + leftSquareBracket$b + + (node.label || node.identifier) + + rightSquareBracket$b + + colon$6 + + space$s + + content + ) +} + +var image_1 = image$3; + +var space$t = ' '; +var leftParenthesis$6 = '('; +var rightParenthesis$7 = ')'; +var leftSquareBracket$c = '['; +var rightSquareBracket$c = ']'; +var exclamationMark$6 = '!'; + +// Stringify an image. +// +// Is smart about enclosing `url` (see `encloseURI()`) and `title` (see +// `encloseTitle()`). +// +// ```markdown +// ![foo]( 'My "favourite" icon') +// ``` +// +// Supports named entities in `url`, `alt`, and `title` when in +// `settings.encode` mode. +function image$3(node) { + var self = this; + var content = encloseUri(self.encode(node.url || '', node)); + var exit = self.enterLink(); + var alt = self.encode(self.escape(node.alt || '', node)); + + exit(); + + if (node.title) { + content += space$t + encloseTitle(self.encode(node.title, node)); + } + + return ( + exclamationMark$6 + + leftSquareBracket$c + + alt + + rightSquareBracket$c + + leftParenthesis$6 + + content + + rightParenthesis$7 + ) +} + +var footnote_1 = footnote$1; + +var leftSquareBracket$d = '['; +var rightSquareBracket$d = ']'; +var caret$3 = '^'; + +function footnote$1(node) { + return ( + leftSquareBracket$d + caret$3 + this.all(node).join('') + rightSquareBracket$d + ) +} + +var footnoteReference_1 = footnoteReference; + +var leftSquareBracket$e = '['; +var rightSquareBracket$e = ']'; +var caret$4 = '^'; + +function footnoteReference(node) { + return ( + leftSquareBracket$e + + caret$4 + + (node.label || node.identifier) + + rightSquareBracket$e + ) +} + +var lineFeed$w = '\n'; +var space$u = ' '; +var colon$7 = ':'; +var leftSquareBracket$f = '['; +var rightSquareBracket$f = ']'; +var caret$5 = '^'; + +var tabSize$7 = 4; +var blank$5 = lineFeed$w + lineFeed$w; +var indent = repeatString(space$u, tabSize$7); + +var footnoteDefinition_1$1 = footnoteDefinition$1; + +function footnoteDefinition$1(node) { + var content = this.all(node).join(blank$5 + indent); + + return ( + leftSquareBracket$f + + caret$5 + + (node.label || node.identifier) + + rightSquareBracket$f + + colon$7 + + space$u + + content + ) +} + +var markdownTable_1 = markdownTable; + +var dotRe = /\./; +var lastDotRe = /\.[^.]*$/; + +// Characters. +var space$v = ' '; +var lineFeed$x = '\n'; +var dash$7 = '-'; +var dot$5 = '.'; +var colon$8 = ':'; +var lowercaseC = 'c'; +var lowercaseL = 'l'; +var lowercaseR = 'r'; +var verticalBar$2 = '|'; + +var minCellSize = 3; + +// Create a table from a matrix of strings. +function markdownTable(table, options) { + var settings = options || {}; + var delimiter = settings.delimiter; + var start = settings.start; + var end = settings.end; + var alignment = settings.align; + var calculateStringLength = settings.stringLength || lengthNoop; + var cellCount = 0; + var rowIndex = -1; + var rowLength = table.length; + var sizes = []; + var align; + var rule; + var rows; + var row; + var cells; + var index; + var position; + var size; + var value; + var spacing; + var before; + var after; + + alignment = alignment ? alignment.concat() : []; + + if (delimiter === null || delimiter === undefined) { + delimiter = space$v + verticalBar$2 + space$v; + } + + if (start === null || start === undefined) { + start = verticalBar$2 + space$v; + } + + if (end === null || end === undefined) { + end = space$v + verticalBar$2; + } + + while (++rowIndex < rowLength) { + row = table[rowIndex]; + + index = -1; + + if (row.length > cellCount) { + cellCount = row.length; + } + + while (++index < cellCount) { + position = row[index] ? dotindex$1(row[index]) : null; + + if (!sizes[index]) { + sizes[index] = minCellSize; + } + + if (position > sizes[index]) { + sizes[index] = position; + } + } + } + + if (typeof alignment === 'string') { + alignment = pad$2(cellCount, alignment).split(''); + } + + // Make sure only valid alignments are used. + index = -1; + + while (++index < cellCount) { + align = alignment[index]; + + if (typeof align === 'string') { + align = align.charAt(0).toLowerCase(); + } + + if ( + align !== lowercaseL && + align !== lowercaseR && + align !== lowercaseC && + align !== dot$5 + ) { + align = ''; + } + + alignment[index] = align; + } + + rowIndex = -1; + rows = []; + + while (++rowIndex < rowLength) { + row = table[rowIndex]; + + index = -1; + cells = []; + + while (++index < cellCount) { + value = row[index]; + + value = stringify$6(value); + + if (alignment[index] === dot$5) { + position = dotindex$1(value); + + size = + sizes[index] + + (dotRe.test(value) ? 0 : 1) - + (calculateStringLength(value) - position); + + cells[index] = value + pad$2(size - 1); + } else { + cells[index] = value; + } + } + + rows[rowIndex] = cells; + } + + sizes = []; + rowIndex = -1; + + while (++rowIndex < rowLength) { + cells = rows[rowIndex]; + + index = -1; + + while (++index < cellCount) { + value = cells[index]; + + if (!sizes[index]) { + sizes[index] = minCellSize; + } + + size = calculateStringLength(value); + + if (size > sizes[index]) { + sizes[index] = size; + } + } + } + + rowIndex = -1; + + while (++rowIndex < rowLength) { + cells = rows[rowIndex]; + + index = -1; + + if (settings.pad !== false) { + while (++index < cellCount) { + value = cells[index]; + + position = sizes[index] - (calculateStringLength(value) || 0); + spacing = pad$2(position); + + if (alignment[index] === lowercaseR || alignment[index] === dot$5) { + value = spacing + value; + } else if (alignment[index] === lowercaseC) { + position /= 2; + + if (position % 1 === 0) { + before = position; + after = position; + } else { + before = position + 0.5; + after = position - 0.5; + } + + value = pad$2(before) + value + pad$2(after); + } else { + value += spacing; + } + + cells[index] = value; + } + } + + rows[rowIndex] = cells.join(delimiter); + } + + if (settings.rule !== false) { + index = -1; + rule = []; + + while (++index < cellCount) { + // When `pad` is false, make the rule the same size as the first row. + if (settings.pad === false) { + value = table[0][index]; + spacing = calculateStringLength(stringify$6(value)); + spacing = spacing > minCellSize ? spacing : minCellSize; + } else { + spacing = sizes[index]; + } + + align = alignment[index]; + + // When `align` is left, don't add colons. + value = align === lowercaseR || align === '' ? dash$7 : colon$8; + value += pad$2(spacing - 2, dash$7); + value += align !== lowercaseL && align !== '' ? colon$8 : dash$7; + + rule[index] = value; + } + + rows.splice(1, 0, rule.join(delimiter)); + } + + return start + rows.join(end + lineFeed$x + start) + end +} + +function stringify$6(value) { + return value === null || value === undefined ? '' : String(value) +} + +// Get the length of `value`. +function lengthNoop(value) { + return String(value).length +} + +// Get a string consisting of `length` `character`s. +function pad$2(length, character) { + return new Array(length + 1).join(character || space$v) +} + +// Get the position of the last dot in `value`. +function dotindex$1(value) { + var match = lastDotRe.exec(value); + + return match ? match.index + 1 : value.length +} + +var table_1$1 = table$1; + +var space$w = ' '; +var verticalBar$3 = '|'; + +// Stringify table. +// +// Creates a fenced table by default, but not in `looseTable: true` mode: +// +// ```markdown +// Foo | Bar +// :-: | --- +// Baz | Qux +// +// NOTE: Be careful with `looseTable: true` mode, as a loose table inside an +// indented code block on GitHub renders as an actual table! +// +// Creates a spaced table by default, but not in `spacedTable: false`: +// +// ```markdown +// |Foo|Bar| +// |:-:|---| +// |Baz|Qux| +// ``` +function table$1(node) { + var self = this; + var options = self.options; + var loose = options.looseTable; + var spaced = options.spacedTable; + var pad = options.paddedTable; + var stringLength = options.stringLength; + var rows = node.children; + var index = rows.length; + var exit = self.enterTable(); + var result = []; + var start; + var end; + + while (index--) { + result[index] = self.all(rows[index]); + } + + exit(); + + if (loose) { + start = ''; + end = ''; + } else if (spaced) { + start = verticalBar$3 + space$w; + end = space$w + verticalBar$3; + } else { + start = verticalBar$3; + end = verticalBar$3; + } + + return markdownTable_1(result, { + align: node.align, + pad: pad, + start: start, + end: end, + stringLength: stringLength, + delimiter: spaced ? space$w + verticalBar$3 + space$w : verticalBar$3 + }) +} + +var tableCell_1 = tableCell; + +var lineFeed$y = /\r?\n/g; + +function tableCell(node) { + return this.all(node) + .join('') + .replace(lineFeed$y, ' ') +} + +var compiler = Compiler; + +// Construct a new compiler. +function Compiler(tree, file) { + this.inLink = false; + this.inTable = false; + this.tree = tree; + this.file = file; + this.options = immutable(this.options); + this.setOptions({}); +} + +var proto$4 = Compiler.prototype; + +// Enter and exit helpers. */ +proto$4.enterLink = stateToggle('inLink', false); +proto$4.enterTable = stateToggle('inTable', false); +proto$4.enterLinkReference = enterLinkReference; + +// Configuration. +proto$4.options = defaults$3; +proto$4.setOptions = setOptions_1$1; + +proto$4.compile = compile_1$1; +proto$4.visit = one_1; +proto$4.all = all_1; +proto$4.block = block_1; +proto$4.visitOrderedItems = orderedItems_1; +proto$4.visitUnorderedItems = unorderedItems_1; + +// Expose visitors. +proto$4.visitors = { + root: root_1, + text: text_1$1, + heading: heading_1, + paragraph: paragraph_1$1, + blockquote: blockquote_1$1, + list: list_1$1, + listItem: listItem_1, + inlineCode: inlineCode_1, + code: code_1, + html: html_1, + thematicBreak: thematicBreak$1, + strong: strong_1$1, + emphasis: emphasis_1$1, + break: _break$2, + delete: _delete$2, + link: link_1$1, + linkReference: linkReference_1, + imageReference: imageReference_1, + definition: definition_1$1, + image: image_1, + footnote: footnote_1, + footnoteReference: footnoteReference_1, + footnoteDefinition: footnoteDefinition_1$1, + table: table_1$1, + tableCell: tableCell_1 +}; + +var remarkStringify = stringify$7; +stringify$7.Compiler = compiler; + +function stringify$7(options) { + var Local = unherit_1(compiler); + Local.prototype.options = immutable( + Local.prototype.options, + this.data('settings'), + options + ); + this.Compiler = Local; +} + +var remark = unified_1() + .use(remarkParse) + .use(remarkStringify) + .freeze(); + +const _from = "remark@^11.0.2"; +const _id = "remark@11.0.2"; +const _inBundle = false; +const _integrity = "sha512-bh+eJgn8wgmbHmIBOuwJFdTVRVpl3fcVP6HxmpPWO0ULGP9Qkh6INJh0N5Uy7GqlV7DQYGoqaKiEIpM5LLvJ8w=="; +const _location = "/remark"; +const _phantomChildren = { +}; +const _requested = { + type: "range", + registry: true, + raw: "remark@^11.0.2", + name: "remark", + escapedName: "remark", + rawSpec: "^11.0.2", + saveSpec: null, + fetchSpec: "^11.0.2" +}; +const _requiredBy = [ + "/" +]; +const _resolved = "https://registry.npmjs.org/remark/-/remark-11.0.2.tgz"; +const _shasum = "12b90ea100ac3362b1976fa87a6e4e0ab5968202"; +const _spec = "remark@^11.0.2"; +const _where = "/mnt/c/orgs/nodejs/node-runtime/tools/node-lint-md-cli-rollup"; +const author = { + name: "Titus Wormer", + email: "tituswormer@gmail.com", + url: "https://wooorm.com" +}; +const bugs = { + url: "https://github.com/remarkjs/remark/issues" +}; +const bundleDependencies = false; +const contributors = [ + { + name: "Titus Wormer", + email: "tituswormer@gmail.com", + url: "https://wooorm.com" + } +]; +const dependencies = { + "remark-parse": "^7.0.0", + "remark-stringify": "^7.0.0", + unified: "^8.2.0" +}; +const deprecated$1 = false; +const description = "Markdown processor powered by plugins"; +const files = [ + "index.js", + "types/index.d.ts" +]; +const funding = { + type: "opencollective", + url: "https://opencollective.com/unified" +}; +const homepage = "https://remark.js.org"; +const keywords = [ + "unified", + "remark", + "markdown", + "mdast", + "abstract", + "syntax", + "tree", + "ast", + "parse", + "stringify", + "process" +]; +const license = "MIT"; +const name$1 = "remark"; +const repository = { + type: "git", + url: "https://github.com/remarkjs/remark/tree/master/packages/remark" +}; +const scripts = { + test: "tape test.js" +}; +const types = "types/index.d.ts"; +const version$1 = "11.0.2"; +const xo = false; +var _package = { + _from: _from, + _id: _id, + _inBundle: _inBundle, + _integrity: _integrity, + _location: _location, + _phantomChildren: _phantomChildren, + _requested: _requested, + _requiredBy: _requiredBy, + _resolved: _resolved, + _shasum: _shasum, + _spec: _spec, + _where: _where, + author: author, + bugs: bugs, + bundleDependencies: bundleDependencies, + contributors: contributors, + dependencies: dependencies, + deprecated: deprecated$1, + description: description, + files: files, + funding: funding, + homepage: homepage, + keywords: keywords, + license: license, + name: name$1, + repository: repository, + scripts: scripts, + types: types, + version: version$1, + xo: xo +}; + +var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + _from: _from, + _id: _id, + _inBundle: _inBundle, + _integrity: _integrity, + _location: _location, + _phantomChildren: _phantomChildren, + _requested: _requested, + _requiredBy: _requiredBy, + _resolved: _resolved, + _shasum: _shasum, + _spec: _spec, + _where: _where, + author: author, + bugs: bugs, + bundleDependencies: bundleDependencies, + contributors: contributors, + dependencies: dependencies, + deprecated: deprecated$1, + description: description, + files: files, + funding: funding, + homepage: homepage, + keywords: keywords, + license: license, + name: name$1, + repository: repository, + scripts: scripts, + types: types, + version: version$1, + xo: xo, + 'default': _package +}); + +const name$2 = "node-lint-md-cli-rollup"; +const description$1 = "remark packaged for Node.js Markdown linting"; +const version$2 = "2.0.2"; +const devDependencies = { + "@rollup/plugin-commonjs": "^11.0.1", + "@rollup/plugin-json": "^4.0.1", + "@rollup/plugin-node-resolve": "^7.0.0", + rollup: "^1.30.1", + shx: "^0.3.2" +}; +const dependencies$1 = { + "markdown-extensions": "^1.1.1", + remark: "^11.0.2", + "remark-lint": "^6.0.5", + "remark-preset-lint-node": "^1.12.0", + "unified-args": "^7.1.0" +}; +const main = "dist/index.js"; +const scripts$1 = { + build: "npx rollup -c", + "build-node": "npm run build && npx shx cp dist/index.js ../lint-md.js" +}; +var _package$2 = { + name: name$2, + description: description$1, + version: version$2, + devDependencies: devDependencies, + dependencies: dependencies$1, + main: main, + scripts: scripts$1 +}; + +var _package$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$2, + description: description$1, + version: version$2, + devDependencies: devDependencies, + dependencies: dependencies$1, + main: main, + scripts: scripts$1, + 'default': _package$2 +}); + +/* Map of allowed verbs. */ +var ALLOWED_VERBS = { + enable: true, + disable: true, + ignore: true +}; + +var unifiedMessageControl = messageControl; + +function messageControl(options) { + var name = options && options.name; + var marker = options && options.marker; + var test = options && options.test; + var sources; + var known; + var reset; + var enable; + var disable; + + if (!name) { + throw new Error('Expected `name` in `options`, got `' + name + '`') + } + + if (!marker) { + throw new Error('Expected `name` in `options`, got `' + name + '`') + } + + if (!test) { + throw new Error('Expected `test` in `options`, got `' + test + '`') + } + + known = options.known; + reset = options.reset; + enable = options.enable || []; + disable = options.disable || []; + sources = options.source; + + if (!sources) { + sources = [name]; + } else if (typeof sources === 'string') { + sources = [sources]; + } + + return transformer + + function transformer(tree, file) { + var toOffset = vfileLocation(file).toOffset; + var initial = !reset; + var gaps = detectGaps(tree, file); + var scope = {}; + var globals = []; + + unistUtilVisit(tree, test, visitor); + + file.messages = file.messages.filter(filter); + + function visitor(node, position, parent) { + var mark = marker(node); + var ruleIds; + var ruleId; + var verb; + var index; + var length; + var next; + var pos; + var tail; + + if (!mark || mark.name !== options.name) { + return + } + + ruleIds = mark.attributes.split(/\s/g); + verb = ruleIds.shift(); + next = parent.children[position + 1]; + pos = mark.node.position && mark.node.position.start; + tail = next && next.position && next.position.end; + + if (!verb || !ALLOWED_VERBS[verb] === true) { + file.fail( + 'Unknown keyword `' + + verb + + '`: expected ' + + "`'enable'`, `'disable'`, or `'ignore'`", + mark.node + ); + } + + length = ruleIds.length; + index = -1; + + while (++index < length) { + ruleId = ruleIds[index]; + + if (isKnown(ruleId, verb, mark.node)) { + toggle(pos, verb === 'enable', ruleId); + + if (verb === 'ignore') { + toggle(tail, true, ruleId); + } + } + } + + /* Apply to all rules. */ + if (!length) { + if (verb === 'ignore') { + toggle(pos, false); + toggle(tail, true); + } else { + toggle(pos, verb === 'enable'); + reset = verb !== 'enable'; + } + } + } + + function filter(message) { + var gapIndex = gaps.length; + var ruleId = message.ruleId; + var ranges = scope[ruleId]; + var pos; + + /* Keep messages from a different source. */ + if (!message.source || sources.indexOf(message.source) === -1) { + return true + } + + /* We only ignore messages if they‘re disabled, + * *not* when they’re not in the document. */ + if (!message.line) { + message.line = 1; + } + + if (!message.column) { + message.column = 1; + } + + /* Check whether the warning is inside a gap. */ + pos = toOffset(message); + + while (gapIndex--) { + if (gaps[gapIndex].start <= pos && gaps[gapIndex].end > pos) { + return false + } + } + + /* Check whether allowed by specific and global states. */ + return check(message, ranges, ruleId) && check(message, globals) + } + + /* Helper to check (and possibly warn) if a ruleId is unknown. */ + function isKnown(ruleId, verb, pos) { + var result = known ? known.indexOf(ruleId) !== -1 : true; + + if (!result) { + file.warn('Unknown rule: cannot ' + verb + " `'" + ruleId + "'`", pos); + } + + return result + } + + /* Get the latest state of a rule. When without `ruleId`, gets global state. */ + function getState(ruleId) { + var ranges = ruleId ? scope[ruleId] : globals; + + if (ranges && ranges.length !== 0) { + return ranges[ranges.length - 1].state + } + + if (!ruleId) { + return !reset + } + + if (reset) { + return enable.indexOf(ruleId) !== -1 + } + + return disable.indexOf(ruleId) === -1 + } + + /* Handle a rule. */ + function toggle(pos, state, ruleId) { + var markers = ruleId ? scope[ruleId] : globals; + var currentState; + var previousState; + + if (!markers) { + markers = []; + scope[ruleId] = markers; + } + + previousState = getState(ruleId); + currentState = state; + + if (currentState !== previousState) { + markers.push({state: currentState, position: pos}); + } + + /* Toggle all known rules. */ + if (!ruleId) { + for (ruleId in scope) { + toggle(pos, state, ruleId); + } + } + } + + /* Check all `ranges` for `message`. */ + function check(message, ranges, id) { + /* Check the state at the message's position. */ + var index = ranges && ranges.length; + var length = -1; + var range; + + while (--index > length) { + range = ranges[index]; + + /* istanbul ignore if - generated marker. */ + if (!range.position || !range.position.line || !range.position.column) { + continue + } + + if ( + range.position.line < message.line || + (range.position.line === message.line && + range.position.column < message.column) + ) { + return range.state === true + } + } + + /* The first marker ocurred after the first + * message, so we check the initial state. */ + if (!id) { + return initial || reset + } + + return reset ? enable.indexOf(id) !== -1 : disable.indexOf(id) === -1 + } + } +} + +/* Detect gaps in `ast`. */ +function detectGaps(tree, file) { + var lastNode = tree.children[tree.children.length - 1]; + var offset = 0; + var isGap = false; + var gaps = []; + + /* Find all gaps. */ + unistUtilVisit(tree, one); + + /* Get the end of the document. + * This detects if the last node was the last node. + * If not, there’s an extra gap between the last node + * and the end of the document. */ + if ( + lastNode && + lastNode.position && + lastNode.position.end && + offset === lastNode.position.end.offset && + trim_1(file.toString().slice(offset)) !== '' + ) { + update(); + + update( + tree && tree.position && tree.position.end && tree.position.end.offset - 1 + ); + } + + return gaps + + function one(node) { + var pos = node.position; + + update(pos && pos.start && pos.start.offset); + + if (!node.children) { + update(pos && pos.end && pos.end.offset); + } + } + + /* Detect a new position. */ + function update(latest) { + if (latest === null || latest === undefined) { + isGap = true; + return + } + + if (offset >= latest) { + return + } + + if (isGap) { + gaps.push({start: offset, end: latest}); + isGap = false; + } + + offset = latest; + } +} + +var mdastCommentMarker = marker$1; + +var whiteSpaceExpression = /\s+/g; + +var parametersExpression = /\s+([-a-z0-9_]+)(?:=(?:"((?:\\[\s\S]|[^"])+)"|'((?:\\[\s\S]|[^'])+)'|((?:\\[\s\S]|[^"'\s])+)))?/gi; + +var commentExpression = /\s*([a-zA-Z0-9-]+)(\s+([\s\S]*))?\s*/; + +var markerExpression = new RegExp( + '(\\s*\\s*)' +); + +// Parse a comment marker. +function marker$1(node) { + var type; + var value; + var match; + var params; + + if (!node) { + return null + } + + type = node.type; + + if (type !== 'html' && type !== 'comment') { + return null + } + + value = node.value; + match = value.match(type === 'comment' ? commentExpression : markerExpression); + + if (!match || match[0].length !== value.length) { + return null + } + + match = match.slice(node.type === 'comment' ? 1 : 2); + + params = parameters(match[1] || ''); + + if (!params) { + return null + } + + return { + name: match[0], + attributes: match[2] || '', + parameters: params, + node: node + } +} + +// Parse `value` into an object. +function parameters(value) { + var attributes = {}; + var rest = value.replace(parametersExpression, replacer); + + return rest.replace(whiteSpaceExpression, '') ? null : attributes + + /* eslint-disable max-params */ + function replacer($0, $1, $2, $3, $4) { + var result = $2 || $3 || $4 || ''; + + if (result === 'true' || result === '') { + result = true; + } else if (result === 'false') { + result = false; + } else if (!isNaN(result)) { + result = Number(result); + } + + attributes[$1] = result; + + return '' + } +} + +var remarkMessageControl = messageControl$1; + +var test = [ + 'html', // Comments are `html` nodes in mdast. + 'comment' // In MDX, comments have their own node. +]; + +function messageControl$1(options) { + return unifiedMessageControl(immutable({marker: mdastCommentMarker, test: test}, options)) +} + +var remarkLint = lint; + +// `remark-lint`. +// This adds support for ignoring stuff from messages (``). +// All rules are in their own packages and presets. +function lint() { + this.use(lintMessageControl); +} + +function lintMessageControl() { + return remarkMessageControl({name: 'lint', source: 'remark-lint'}) +} + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +var sliced = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd; + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +}; + +/** + * slice() reference. + */ + +var slice$4 = Array.prototype.slice; + +/** + * Expose `co`. + */ + +var co_1 = co; + +/** + * Wrap the given generator `fn` and + * return a thunk. + * + * @param {Function} fn + * @return {Function} + * @api public + */ + +function co(fn) { + var isGenFun = isGeneratorFunction(fn); + + return function (done) { + var ctx = this; + + // in toThunk() below we invoke co() + // with a generator, so optimize for + // this case + var gen = fn; + + // we only need to parse the arguments + // if gen is a generator function. + if (isGenFun) { + var args = slice$4.call(arguments), len = args.length; + var hasCallback = len && 'function' == typeof args[len - 1]; + done = hasCallback ? args.pop() : error; + gen = fn.apply(this, args); + } else { + done = done || error; + } + + next(); + + // #92 + // wrap the callback in a setImmediate + // so that any of its errors aren't caught by `co` + function exit(err, res) { + setImmediate(function(){ + done.call(ctx, err, res); + }); + } + + function next(err, res) { + var ret; + + // multiple args + if (arguments.length > 2) res = slice$4.call(arguments, 1); + + // error + if (err) { + try { + ret = gen.throw(err); + } catch (e) { + return exit(e); + } + } + + // ok + if (!err) { + try { + ret = gen.next(res); + } catch (e) { + return exit(e); + } + } + + // done + if (ret.done) return exit(null, ret.value); + + // normalize + ret.value = toThunk(ret.value, ctx); + + // run + if ('function' == typeof ret.value) { + var called = false; + try { + ret.value.call(ctx, function(){ + if (called) return; + called = true; + next.apply(ctx, arguments); + }); + } catch (e) { + setImmediate(function(){ + if (called) return; + called = true; + next(e); + }); + } + return; + } + + // invalid + next(new TypeError('You may only yield a function, promise, generator, array, or object, ' + + 'but the following was passed: "' + String(ret.value) + '"')); + } + } +} + +/** + * Convert `obj` into a normalized thunk. + * + * @param {Mixed} obj + * @param {Mixed} ctx + * @return {Function} + * @api private + */ + +function toThunk(obj, ctx) { + + if (isGeneratorFunction(obj)) { + return co(obj.call(ctx)); + } + + if (isGenerator(obj)) { + return co(obj); + } + + if (isPromise(obj)) { + return promiseToThunk(obj); + } + + if ('function' == typeof obj) { + return obj; + } + + if (isObject$4(obj) || Array.isArray(obj)) { + return objectToThunk.call(ctx, obj); + } + + return obj; +} + +/** + * Convert an object of yieldables to a thunk. + * + * @param {Object} obj + * @return {Function} + * @api private + */ + +function objectToThunk(obj){ + var ctx = this; + var isArray = Array.isArray(obj); + + return function(done){ + var keys = Object.keys(obj); + var pending = keys.length; + var results = isArray + ? new Array(pending) // predefine the array length + : new obj.constructor(); + var finished; + + if (!pending) { + setImmediate(function(){ + done(null, results); + }); + return; + } + + // prepopulate object keys to preserve key ordering + if (!isArray) { + for (var i = 0; i < pending; i++) { + results[keys[i]] = undefined; + } + } + + for (var i = 0; i < keys.length; i++) { + run(obj[keys[i]], keys[i]); + } + + function run(fn, key) { + if (finished) return; + try { + fn = toThunk(fn, ctx); + + if ('function' != typeof fn) { + results[key] = fn; + return --pending || done(null, results); + } + + fn.call(ctx, function(err, res){ + if (finished) return; + + if (err) { + finished = true; + return done(err); + } + + results[key] = res; + --pending || done(null, results); + }); + } catch (err) { + finished = true; + done(err); + } + } + } +} + +/** + * Convert `promise` to a thunk. + * + * @param {Object} promise + * @return {Function} + * @api private + */ + +function promiseToThunk(promise) { + return function(fn){ + promise.then(function(res) { + fn(null, res); + }, fn); + } +} + +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isPromise(obj) { + return obj && 'function' == typeof obj.then; +} + +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGenerator(obj) { + return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw; +} + +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGeneratorFunction(obj) { + return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; +} + +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ + +function isObject$4(val) { + return val && Object == val.constructor; +} + +/** + * Throw `err` in a new stack. + * + * This is used when co() is invoked + * without supplying a callback, which + * should only be for demonstrational + * purposes. + * + * @param {Error} err + * @api private + */ + +function error(err) { + if (!err) return; + setImmediate(function(){ + throw err; + }); +} + +/** + * Module Dependencies + */ + + +var noop$3 = function(){}; + + +/** + * Export `wrapped` + */ + +var wrapped_1 = wrapped; + +/** + * Wrap a function to support + * sync, async, and gen functions. + * + * @param {Function} fn + * @return {Function} + * @api public + */ + +function wrapped(fn) { + function wrap() { + var args = sliced(arguments); + var last = args[args.length - 1]; + var ctx = this; + + // done + var done = typeof last == 'function' ? args.pop() : noop$3; + + // nothing + if (!fn) { + return done.apply(ctx, [null].concat(args)); + } + + // generator + if (generator(fn)) { + return co_1(fn).apply(ctx, args.concat(done)); + } + + // async + if (fn.length > args.length) { + // NOTE: this only handles uncaught synchronous errors + try { + return fn.apply(ctx, args.concat(done)); + } catch (e) { + return done(e); + } + } + + // sync + return sync$2(fn, done).apply(ctx, args); + } + + return wrap; +} + +/** + * Wrap a synchronous function execution. + * + * @param {Function} fn + * @param {Function} done + * @return {Function} + * @api private + */ + +function sync$2(fn, done) { + return function () { + var ret; + + try { + ret = fn.apply(this, arguments); + } catch (err) { + return done(err); + } + + if (promise(ret)) { + ret.then(function (value) { done(null, value); }, done); + } else { + ret instanceof Error ? done(ret) : done(null, ret); + } + } +} + +/** + * Is `value` a generator? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function generator(value) { + return value + && value.constructor + && 'GeneratorFunction' == value.constructor.name; +} + + +/** + * Is `value` a promise? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function promise(value) { + return value && 'function' == typeof value.then; +} + +var unifiedLintRule = factory$7; + +function factory$7(id, rule) { + var parts = id.split(':'); + var source = parts[0]; + var ruleId = parts[1]; + var fn = wrapped_1(rule); + + /* istanbul ignore if - possibly useful if externalised later. */ + if (!ruleId) { + ruleId = source; + source = null; + } + + attacher.displayName = id; + + return attacher + + function attacher(raw) { + var config = coerce(ruleId, raw); + var severity = config[0]; + var options = config[1]; + var fatal = severity === 2; + + return severity ? transformer : undefined + + function transformer(tree, file, next) { + var index = file.messages.length; + + fn(tree, file, options, done); + + function done(err) { + var messages = file.messages; + var message; + + // Add the error, if not already properly added. + /* istanbul ignore if - only happens for incorrect plugins */ + if (err && messages.indexOf(err) === -1) { + try { + file.fail(err); + } catch (error) {} + } + + while (index < messages.length) { + message = messages[index]; + message.ruleId = ruleId; + message.source = source; + message.fatal = fatal; + + index++; + } + + next(); + } + } + } +} + +// Coerce a value to a severity--options tuple. +function coerce(name, value) { + var def = 1; + var result; + var level; + + /* istanbul ignore if - Handled by unified in v6.0.0 */ + if (typeof value === 'boolean') { + result = [value]; + } else if (value == null) { + result = [def]; + } else if ( + typeof value === 'object' && + (typeof value[0] === 'number' || + typeof value[0] === 'boolean' || + typeof value[0] === 'string') + ) { + result = value.concat(); + } else { + result = [1, value]; + } + + level = result[0]; + + if (typeof level === 'boolean') { + level = level ? 1 : 0; + } else if (typeof level === 'string') { + if (level === 'off') { + level = 0; + } else if (level === 'on' || level === 'warn') { + level = 1; + } else if (level === 'error') { + level = 2; + } else { + level = 1; + result = [level, result]; + } + } + + if (level < 0 || level > 2) { + throw new Error( + 'Invalid severity `' + + level + + '` for `' + + name + + '`, ' + + 'expected 0, 1, or 2' + ) + } + + result[0] = level; + + return result +} + +var remarkLintFinalNewline = unifiedLintRule('remark-lint:final-newline', finalNewline); + +function finalNewline(tree, file) { + var contents = String(file); + var last = contents.length - 1; + + if (last > -1 && contents.charAt(last) !== '\n') { + file.message('Missing newline character at end of file'); + } +} + +const addendum = "addenda"; +const aircraft = "aircraft"; +const alga = "algae"; +const alumna = "alumnae"; +const alumnus = "alumni"; +const amoeba = "amoebae"; +const analysis = "analyses"; +const antenna = "antennae"; +const antithesis = "antitheses"; +const apex = "apices"; +const appendix = "appendices"; +const automaton = "automata"; +const axis = "axes"; +const bacillus = "bacilli"; +const bacterium = "bacteria"; +const barracks = "barracks"; +const basis = "bases"; +const beau = "beaux"; +const bison = "bison"; +const buffalo = "buffalo"; +const bureau = "bureaus"; +const cactus = "cacti"; +const calf = "calves"; +const carp = "carp"; +const census = "censuses"; +const chassis = "chassis"; +const cherub = "cherubim"; +const child = "children"; +const cod = "cod"; +const codex = "codices"; +const concerto = "concerti"; +const corpus = "corpora"; +const crisis = "crises"; +const criterion = "criteria"; +const curriculum = "curricula"; +const datum = "data"; +const deer = "deer"; +const diagnosis = "diagnoses"; +const die$1 = "dice"; +const dwarf = "dwarfs"; +const echo = "echoes"; +const elf = "elves"; +const elk = "elk"; +const ellipsis = "ellipses"; +const embargo = "embargoes"; +const emphasis$3 = "emphases"; +const erratum = "errata"; +const fez = "fezes"; +const firmware = "firmware"; +const fish = "fish"; +const focus = "foci"; +const foot = "feet"; +const formula = "formulae"; +const fungus = "fungi"; +const gallows = "gallows"; +const genus = "genera"; +const goose = "geese"; +const graffito = "graffiti"; +const grouse = "grouse"; +const half$1 = "halves"; +const hero = "heroes"; +const hoof = "hooves"; +const hovercraft = "hovercraft"; +const hypothesis = "hypotheses"; +const index$5 = "indices"; +const kakapo = "kakapo"; +const knife = "knives"; +const larva = "larvae"; +const leaf = "leaves"; +const libretto = "libretti"; +const life = "lives"; +const loaf = "loaves"; +const locus = "loci"; +const louse = "lice"; +const man = "men"; +const matrix = "matrices"; +const means = "means"; +const medium = "media"; +const memorandum = "memoranda"; +const millennium = "millennia"; +const minutia = "minutiae"; +const moose = "moose"; +const mouse = "mice"; +const nebula = "nebulae"; +const nemesis = "nemeses"; +const neurosis = "neuroses"; +const news = "news"; +const nucleus = "nuclei"; +const oasis = "oases"; +const offspring = "offspring"; +const opus = "opera"; +const ovum = "ova"; +const ox = "oxen"; +const paralysis = "paralyses"; +const parenthesis = "parentheses"; +const person = "people"; +const phenomenon = "phenomena"; +const phylum = "phyla"; +const pike = "pike"; +const polyhedron = "polyhedra"; +const potato = "potatoes"; +const prognosis = "prognoses"; +const quiz = "quizzes"; +const radius = "radii"; +const referendum = "referenda"; +const salmon = "salmon"; +const scarf = "scarves"; +const self = "selves"; +const series = "series"; +const sheep = "sheep"; +const shelf = "shelves"; +const shrimp = "shrimp"; +const spacecraft = "spacecraft"; +const species = "species"; +const spectrum = "spectra"; +const squid = "squid"; +const stimulus = "stimuli"; +const stratum = "strata"; +const swine = "swine"; +const syllabus = "syllabi"; +const symposium = "symposia"; +const synopsis = "synopses"; +const synthesis = "syntheses"; +const tableau = "tableaus"; +const that = "those"; +const thesis = "theses"; +const thief = "thieves"; +const tomato = "tomatoes"; +const tooth = "teeth"; +const trout = "trout"; +const tuna = "tuna"; +const vertebra = "vertebrae"; +const vertex = "vertices"; +const veto = "vetoes"; +const vita = "vitae"; +const vortex = "vortices"; +const watercraft = "watercraft"; +const wharf = "wharves"; +const wife = "wives"; +const wolf = "wolves"; +const woman = "women"; +var irregularPlurals = { + addendum: addendum, + aircraft: aircraft, + alga: alga, + alumna: alumna, + alumnus: alumnus, + amoeba: amoeba, + analysis: analysis, + antenna: antenna, + antithesis: antithesis, + apex: apex, + appendix: appendix, + automaton: automaton, + axis: axis, + bacillus: bacillus, + bacterium: bacterium, + barracks: barracks, + basis: basis, + beau: beau, + bison: bison, + buffalo: buffalo, + bureau: bureau, + cactus: cactus, + calf: calf, + carp: carp, + census: census, + chassis: chassis, + cherub: cherub, + child: child, + "château": "châteaus", + cod: cod, + codex: codex, + concerto: concerto, + corpus: corpus, + crisis: crisis, + criterion: criterion, + curriculum: curriculum, + datum: datum, + deer: deer, + diagnosis: diagnosis, + die: die$1, + dwarf: dwarf, + echo: echo, + elf: elf, + elk: elk, + ellipsis: ellipsis, + embargo: embargo, + emphasis: emphasis$3, + erratum: erratum, + "faux pas": "faux pas", + fez: fez, + firmware: firmware, + fish: fish, + focus: focus, + foot: foot, + formula: formula, + fungus: fungus, + gallows: gallows, + genus: genus, + goose: goose, + graffito: graffito, + grouse: grouse, + half: half$1, + hero: hero, + hoof: hoof, + hovercraft: hovercraft, + hypothesis: hypothesis, + index: index$5, + kakapo: kakapo, + knife: knife, + larva: larva, + leaf: leaf, + libretto: libretto, + life: life, + loaf: loaf, + locus: locus, + louse: louse, + man: man, + matrix: matrix, + means: means, + medium: medium, + memorandum: memorandum, + millennium: millennium, + minutia: minutia, + moose: moose, + mouse: mouse, + nebula: nebula, + nemesis: nemesis, + neurosis: neurosis, + news: news, + nucleus: nucleus, + oasis: oasis, + offspring: offspring, + opus: opus, + ovum: ovum, + ox: ox, + paralysis: paralysis, + parenthesis: parenthesis, + person: person, + phenomenon: phenomenon, + phylum: phylum, + pike: pike, + polyhedron: polyhedron, + potato: potato, + prognosis: prognosis, + quiz: quiz, + radius: radius, + referendum: referendum, + salmon: salmon, + scarf: scarf, + self: self, + series: series, + sheep: sheep, + shelf: shelf, + shrimp: shrimp, + spacecraft: spacecraft, + species: species, + spectrum: spectrum, + squid: squid, + stimulus: stimulus, + stratum: stratum, + swine: swine, + syllabus: syllabus, + symposium: symposium, + synopsis: synopsis, + synthesis: synthesis, + tableau: tableau, + that: that, + thesis: thesis, + thief: thief, + "this": "these", + tomato: tomato, + tooth: tooth, + trout: trout, + tuna: tuna, + vertebra: vertebra, + vertex: vertex, + veto: veto, + vita: vita, + vortex: vortex, + watercraft: watercraft, + wharf: wharf, + wife: wife, + wolf: wolf, + woman: woman +}; + +var irregularPlurals$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + addendum: addendum, + aircraft: aircraft, + alga: alga, + alumna: alumna, + alumnus: alumnus, + amoeba: amoeba, + analysis: analysis, + antenna: antenna, + antithesis: antithesis, + apex: apex, + appendix: appendix, + automaton: automaton, + axis: axis, + bacillus: bacillus, + bacterium: bacterium, + barracks: barracks, + basis: basis, + beau: beau, + bison: bison, + buffalo: buffalo, + bureau: bureau, + cactus: cactus, + calf: calf, + carp: carp, + census: census, + chassis: chassis, + cherub: cherub, + child: child, + cod: cod, + codex: codex, + concerto: concerto, + corpus: corpus, + crisis: crisis, + criterion: criterion, + curriculum: curriculum, + datum: datum, + deer: deer, + diagnosis: diagnosis, + die: die$1, + dwarf: dwarf, + echo: echo, + elf: elf, + elk: elk, + ellipsis: ellipsis, + embargo: embargo, + emphasis: emphasis$3, + erratum: erratum, + fez: fez, + firmware: firmware, + fish: fish, + focus: focus, + foot: foot, + formula: formula, + fungus: fungus, + gallows: gallows, + genus: genus, + goose: goose, + graffito: graffito, + grouse: grouse, + half: half$1, + hero: hero, + hoof: hoof, + hovercraft: hovercraft, + hypothesis: hypothesis, + index: index$5, + kakapo: kakapo, + knife: knife, + larva: larva, + leaf: leaf, + libretto: libretto, + life: life, + loaf: loaf, + locus: locus, + louse: louse, + man: man, + matrix: matrix, + means: means, + medium: medium, + memorandum: memorandum, + millennium: millennium, + minutia: minutia, + moose: moose, + mouse: mouse, + nebula: nebula, + nemesis: nemesis, + neurosis: neurosis, + news: news, + nucleus: nucleus, + oasis: oasis, + offspring: offspring, + opus: opus, + ovum: ovum, + ox: ox, + paralysis: paralysis, + parenthesis: parenthesis, + person: person, + phenomenon: phenomenon, + phylum: phylum, + pike: pike, + polyhedron: polyhedron, + potato: potato, + prognosis: prognosis, + quiz: quiz, + radius: radius, + referendum: referendum, + salmon: salmon, + scarf: scarf, + self: self, + series: series, + sheep: sheep, + shelf: shelf, + shrimp: shrimp, + spacecraft: spacecraft, + species: species, + spectrum: spectrum, + squid: squid, + stimulus: stimulus, + stratum: stratum, + swine: swine, + syllabus: syllabus, + symposium: symposium, + synopsis: synopsis, + synthesis: synthesis, + tableau: tableau, + that: that, + thesis: thesis, + thief: thief, + tomato: tomato, + tooth: tooth, + trout: trout, + tuna: tuna, + vertebra: vertebra, + vertex: vertex, + veto: veto, + vita: vita, + vortex: vortex, + watercraft: watercraft, + wharf: wharf, + wife: wife, + wolf: wolf, + woman: woman, + 'default': irregularPlurals +}); + +var irregularPlurals$2 = getCjsExportFromNamespace(irregularPlurals$1); + +var irregularPlurals_1 = createCommonjsModule(function (module) { + + +const map = new Map(); +// TODO: Use Object.entries when targeting Node.js 8 +for (const key of Object.keys(irregularPlurals$2)) { + map.set(key, irregularPlurals$2[key]); +} + +// Ensure nobody can modify each others Map +Object.defineProperty(module, 'exports', { + get() { + return map; + } +}); +}); + +var plur = (word, plural, count) => { + if (typeof plural === 'number') { + count = plural; + } + + if (irregularPlurals_1.has(word.toLowerCase())) { + plural = irregularPlurals_1.get(word.toLowerCase()); + + const firstLetter = word.charAt(0); + const isFirstLetterUpperCase = firstLetter === firstLetter.toUpperCase(); + if (isFirstLetterUpperCase) { + plural = firstLetter.toUpperCase() + plural.slice(1); + } + + const isWholeWordUpperCase = word === word.toUpperCase(); + if (isWholeWordUpperCase) { + plural = plural.toUpperCase(); + } + } else if (typeof plural !== 'string') { + plural = (word.replace(/(?:s|x|z|ch|sh)$/i, '$&e').replace(/([^aeiou])y$/i, '$1ie') + 's') + .replace(/i?e?s$/i, match => { + const isTailLowerCase = word.slice(-1) === word.slice(-1).toLowerCase(); + return isTailLowerCase ? match.toLowerCase() : match.toUpperCase(); + }); + } + + return Math.abs(count) === 1 ? word : plural; +}; + +var unistUtilPosition = createCommonjsModule(function (module, exports) { + +var position = exports; + +position.start = factory('start'); +position.end = factory('end'); + +function factory(type) { + point.displayName = type; + + return point + + function point(node) { + var point = (node && node.position && node.position[type]) || {}; + + return { + line: point.line || null, + column: point.column || null, + offset: isNaN(point.offset) ? null : point.offset + } + } +} +}); + +var unistUtilGenerated = generated; + +function generated(node) { + var position = optional(optional(node).position); + var start = optional(position.start); + var end = optional(position.end); + + return !start.line || !start.column || !end.line || !end.column +} + +function optional(value) { + return value && typeof value === 'object' ? value : {} +} + +var remarkLintListItemBulletIndent = unifiedLintRule( + 'remark-lint:list-item-bullet-indent', + listItemBulletIndent +); + +var start$1 = unistUtilPosition.start; + +function listItemBulletIndent(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + node.children.forEach(visitItems); + } + + function visitItems(item) { + var final; + var indent; + var reason; + + if (!unistUtilGenerated(item)) { + final = start$1(item.children[0]); + indent = contents.slice(start$1(item).offset, final.offset).match(/^\s*/)[0] + .length; + + if (indent !== 0) { + reason = + 'Incorrect indentation before bullet: remove ' + + indent + + ' ' + + plur('space', indent); + + file.message(reason, { + line: final.line, + column: final.column - indent + }); + } + } + } +} + +var remarkLintListItemIndent = unifiedLintRule('remark-lint:list-item-indent', listItemIndent); + +var start$2 = unistUtilPosition.start; + +var styles = {'tab-size': true, mixed: true, space: true}; + +function listItemIndent(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' ? pref : 'tab-size'; + + if (styles[pref] !== true) { + file.fail( + 'Invalid list-item indent style `' + + pref + + "`: use either `'tab-size'`, `'space'`, or `'mixed'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var spread = node.spread || node.loose; + + if (!unistUtilGenerated(node)) { + node.children.forEach(visitItem); + } + + function visitItem(item) { + var head = item.children[0]; + var final = start$2(head); + var marker; + var bulletSize; + var style; + var diff; + var reason; + + marker = contents + .slice(start$2(item).offset, final.offset) + .replace(/\[[x ]?]\s*$/i, ''); + + bulletSize = marker.trimRight().length; + + style = + pref === 'tab-size' || (pref === 'mixed' && spread) + ? Math.ceil(bulletSize / 4) * 4 + : bulletSize + 1; + + if (marker.length !== style) { + diff = style - marker.length; + + reason = + 'Incorrect list-item indent: ' + + (diff > 0 ? 'add' : 'remove') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff); + + file.message(reason, final); + } + } + } +} + +var mdastUtilToString = toString$4; + +// Get the text content of a node. If the node itself does not expose +// plain-text fields, `toString` will recursivly try its children. +function toString$4(node) { + return ( + valueOf$1(node) || + (node.children && node.children.map(toString$4).join('')) || + '' + ) +} + +// Get the value of `node`. Checks, `value`, `alt`, and `title`, in that order. +function valueOf$1(node) { + return ( + (node && node.value ? node.value : node.alt ? node.alt : node.title) || '' + ) +} + +var remarkLintNoAutoLinkWithoutProtocol = unifiedLintRule( + 'remark-lint:no-auto-link-without-protocol', + noAutoLinkWithoutProtocol +); + +var start$3 = unistUtilPosition.start; +var end = unistUtilPosition.end; + +// Protocol expression. +// See: . +var protocol$2 = /^[a-z][a-z+.-]+:\/?/i; + +var reason = 'All automatic links must start with a protocol'; + +function noAutoLinkWithoutProtocol(tree, file) { + unistUtilVisit(tree, 'link', visitor); + + function visitor(node) { + var children; + + if (!unistUtilGenerated(node)) { + children = node.children; + + if ( + start$3(node).column === start$3(children[0]).column - 1 && + end(node).column === end(children[children.length - 1]).column + 1 && + !protocol$2.test(mdastUtilToString(node)) + ) { + file.message(reason, node); + } + } + } +} + +var remarkLintNoBlockquoteWithoutMarker = unifiedLintRule( + 'remark-lint:no-blockquote-without-marker', + noBlockquoteWithoutMarker +); + +var reason$1 = 'Missing marker in blockquote'; + +function noBlockquoteWithoutMarker(tree, file) { + var contents = String(file); + var location = vfileLocation(file); + var last = contents.length; + + unistUtilVisit(tree, 'blockquote', visitor); + + function visitor(node) { + var indent = node.position && node.position.indent; + var start; + var length; + var index; + var line; + var offset; + var character; + var pos; + + if (unistUtilGenerated(node) || !indent || indent.length === 0) { + return + } + + start = unistUtilPosition.start(node).line; + length = indent.length; + index = -1; + + while (++index < length) { + line = start + index + 1; + pos = {line: line, column: indent[index]}; + offset = location.toOffset(pos) - 1; + + while (++offset < last) { + character = contents.charAt(offset); + + if (character === '>') { + break + } + + /* istanbul ignore else - just for safety */ + if (character !== ' ' && character !== '\t') { + file.message(reason$1, pos); + break + } + } + } + } +} + +var remarkLintNoLiteralUrls = unifiedLintRule('remark-lint:no-literal-urls', noLiteralURLs); + +var start$4 = unistUtilPosition.start; +var end$1 = unistUtilPosition.end; +var mailto$3 = 'mailto:'; +var reason$2 = 'Don’t use literal URLs without angle brackets'; + +function noLiteralURLs(tree, file) { + unistUtilVisit(tree, 'link', visitor); + + function visitor(node) { + var children = node.children; + var value = mdastUtilToString(node); + + if ( + !unistUtilGenerated(node) && + start$4(node).column === start$4(children[0]).column && + end$1(node).column === end$1(children[children.length - 1]).column && + (node.url === mailto$3 + value || node.url === value) + ) { + file.message(reason$2, node); + } + } +} + +var remarkLintOrderedListMarkerStyle = unifiedLintRule( + 'remark-lint:ordered-list-marker-style', + orderedListMarkerStyle +); + +var start$5 = unistUtilPosition.start; + +var styles$1 = { + ')': true, + '.': true, + null: true +}; + +function orderedListMarkerStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref !== 'string' || pref === 'consistent' ? null : pref; + + if (styles$1[pref] !== true) { + file.fail( + 'Invalid ordered list-item marker style `' + + pref + + "`: use either `'.'` or `')'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var children = node.children; + var length = node.ordered ? children.length : 0; + var index = -1; + var marker; + var child; + + while (++index < length) { + child = children[index]; + + if (!unistUtilGenerated(child)) { + marker = contents + .slice(start$5(child).offset, start$5(child.children[0]).offset) + .replace(/\s|\d/g, '') + .replace(/\[[x ]?]\s*$/i, ''); + + if (pref) { + if (marker !== pref) { + file.message('Marker style should be `' + pref + '`', child); + } + } else { + pref = marker; + } + } + } + } +} + +var remarkLintHardBreakSpaces = unifiedLintRule('remark-lint:hard-break-spaces', hardBreakSpaces); + +var reason$3 = 'Use two spaces for hard line breaks'; + +function hardBreakSpaces(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'break', visitor); + + function visitor(node) { + var value; + + if (!unistUtilGenerated(node)) { + value = contents + .slice(unistUtilPosition.start(node).offset, unistUtilPosition.end(node).offset) + .split('\n', 1)[0] + .replace(/\r$/, ''); + + if (value.length > 2) { + file.message(reason$3, node); + } + } + } +} + +var remarkLintNoDuplicateDefinitions = unifiedLintRule( + 'remark-lint:no-duplicate-definitions', + noDuplicateDefinitions +); + +var reason$4 = 'Do not use definitions with the same identifier'; + +function noDuplicateDefinitions(tree, file) { + var map = {}; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], validate); + + function validate(node) { + var identifier; + var duplicate; + + if (!unistUtilGenerated(node)) { + identifier = node.identifier; + duplicate = map[identifier]; + + if (duplicate && duplicate.type) { + file.message( + reason$4 + ' (' + unistUtilStringifyPosition(unistUtilPosition.start(duplicate)) + ')', + node + ); + } + + map[identifier] = node; + } + } +} + +var mdastUtilHeadingStyle = style; + +function style(node, relative) { + var last = node.children[node.children.length - 1]; + var depth = node.depth; + var pos = node && node.position && node.position.end; + var final = last && last.position && last.position.end; + + if (!pos) { + return null + } + + // This can only occur for `'atx'` and `'atx-closed'` headings. + // This might incorrectly match `'atx'` headings with lots of trailing white + // space as an `'atx-closed'` heading. + if (!last) { + if (pos.column - 1 <= depth * 2) { + return consolidate(depth, relative) + } + + return 'atx-closed' + } + + if (final.line + 1 === pos.line) { + return 'setext' + } + + if (final.column + depth < pos.column) { + return 'atx-closed' + } + + return consolidate(depth, relative) +} + +// Get the probable style of an atx-heading, depending on preferred style. +function consolidate(depth, relative) { + return depth < 3 + ? 'atx' + : relative === 'atx' || relative === 'setext' + ? relative + : null +} + +var remarkLintNoHeadingContentIndent = unifiedLintRule( + 'remark-lint:no-heading-content-indent', + noHeadingContentIndent +); + +var start$6 = unistUtilPosition.start; +var end$2 = unistUtilPosition.end; + +function noHeadingContentIndent(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + var depth; + var children; + var type; + var head; + var initial; + var final; + var diff; + var index; + var char; + var reason; + + if (unistUtilGenerated(node)) { + return + } + + depth = node.depth; + children = node.children; + type = mdastUtilHeadingStyle(node, 'atx'); + + if (type === 'atx' || type === 'atx-closed') { + initial = start$6(node); + index = initial.offset; + char = contents.charAt(index); + + while (char && char !== '#') { + char = contents.charAt(++index); + } + + /* istanbul ignore if - CR/LF bug: remarkjs/remark#195. */ + if (!char) { + return + } + + index = depth + (index - initial.offset); + head = start$6(children[0]).column; + + // Ignore empty headings. + if (!head) { + return + } + + diff = head - initial.column - 1 - index; + + if (diff) { + reason = + (diff > 0 ? 'Remove' : 'Add') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff) + + ' before this heading’s content'; + + file.message(reason, start$6(children[0])); + } + } + + // Closed ATX-heading always must have a space between their content and the + // final hashes, thus, there is no `add x spaces`. + if (type === 'atx-closed') { + final = end$2(children[children.length - 1]); + diff = end$2(node).column - final.column - 1 - depth; + + if (diff) { + reason = + 'Remove ' + + diff + + ' ' + + plur('space', diff) + + ' after this heading’s content'; + + file.message(reason, final); + } + } + } +} + +var remarkLintNoInlinePadding = unifiedLintRule('remark-lint:no-inline-padding', noInlinePadding); + +function noInlinePadding(tree, file) { + unistUtilVisit(tree, ['emphasis', 'strong', 'delete', 'image', 'link'], visitor); + + function visitor(node) { + var contents; + + if (!unistUtilGenerated(node)) { + contents = mdastUtilToString(node); + + if ( + contents.charAt(0) === ' ' || + contents.charAt(contents.length - 1) === ' ' + ) { + file.message('Don’t pad `' + node.type + '` with inner spaces', node); + } + } + } +} + +var remarkLintNoShortcutReferenceImage = unifiedLintRule( + 'remark-lint:no-shortcut-reference-image', + noShortcutReferenceImage +); + +var reason$5 = 'Use the trailing [] on reference images'; + +function noShortcutReferenceImage(tree, file) { + unistUtilVisit(tree, 'imageReference', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { + file.message(reason$5, node); + } + } +} + +var remarkLintNoShortcutReferenceLink = unifiedLintRule( + 'remark-lint:no-shortcut-reference-link', + noShortcutReferenceLink +); + +var reason$6 = 'Use the trailing [] on reference links'; + +function noShortcutReferenceLink(tree, file) { + unistUtilVisit(tree, 'linkReference', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { + file.message(reason$6, node); + } + } +} + +var remarkLintNoUndefinedReferences = unifiedLintRule( + 'remark-lint:no-undefined-references', + noUndefinedReferences +); + +var reason$7 = 'Found reference to undefined definition'; + +// The identifier is upcased to avoid naming collisions with properties +// inherited from `Object.prototype`. Were `Object.create(null)` to be +// used in place of `{}`, downcasing would work equally well. +function normalize$3(s) { + return collapseWhiteSpace(s.toUpperCase()) +} + +function noUndefinedReferences(tree, file, pref) { + var allow = + pref != null && Array.isArray(pref.allow) ? pref.allow.map(normalize$3) : []; + + var map = {}; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], mark); + unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], find); + + function mark(node) { + if (!unistUtilGenerated(node)) { + map[normalize$3(node.identifier)] = true; + } + } + + function find(node) { + if ( + !( + unistUtilGenerated(node) || + allow.includes(normalize$3(node.identifier)) || + normalize$3(node.identifier) in map + ) + ) { + file.message(reason$7, node); + } + } +} + +var remarkLintNoUnusedDefinitions = unifiedLintRule('remark-lint:no-unused-definitions', noUnusedDefinitions); + +var reason$8 = 'Found unused definition'; + +function noUnusedDefinitions(tree, file) { + var map = {}; + var identifier; + var entry; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], find); + unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], mark); + + for (identifier in map) { + entry = map[identifier]; + + if (!entry.used) { + file.message(reason$8, entry.node); + } + } + + function find(node) { + if (!unistUtilGenerated(node)) { + map[node.identifier.toUpperCase()] = {node: node, used: false}; + } + } + + function mark(node) { + var info = map[node.identifier.toUpperCase()]; + + if (!unistUtilGenerated(node) && info) { + info.used = true; + } + } +} + +var plugins$1 = [ + remarkLint, + // Unix compatibility. + remarkLintFinalNewline, + // Rendering across vendors differs greatly if using other styles. + remarkLintListItemBulletIndent, + [remarkLintListItemIndent, 'tab-size'], + // Differs or unsupported across vendors. + remarkLintNoAutoLinkWithoutProtocol, + remarkLintNoBlockquoteWithoutMarker, + remarkLintNoLiteralUrls, + [remarkLintOrderedListMarkerStyle, '.'], + // Mistakes. + remarkLintHardBreakSpaces, + remarkLintNoDuplicateDefinitions, + remarkLintNoHeadingContentIndent, + remarkLintNoInlinePadding, + remarkLintNoShortcutReferenceImage, + remarkLintNoShortcutReferenceLink, + remarkLintNoUndefinedReferences, + remarkLintNoUnusedDefinitions +]; + +var remarkPresetLintRecommended = { + plugins: plugins$1 +}; + +var remarkLintBlockquoteIndentation = unifiedLintRule( + 'remark-lint:blockquote-indentation', + blockquoteIndentation +); + +function blockquoteIndentation(tree, file, pref) { + pref = typeof pref === 'number' && !isNaN(pref) ? pref : null; + + unistUtilVisit(tree, 'blockquote', visitor); + + function visitor(node) { + var diff; + var reason; + + if (unistUtilGenerated(node) || node.children.length === 0) { + return + } + + if (pref) { + diff = pref - check$3(node); + + if (diff !== 0) { + reason = + (diff > 0 ? 'Add' : 'Remove') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff) + + ' between blockquote and content'; + + file.message(reason, unistUtilPosition.start(node.children[0])); + } + } else { + pref = check$3(node); + } + } +} + +function check$3(node) { + var head = node.children[0]; + var indentation = unistUtilPosition.start(head).column - unistUtilPosition.start(node).column; + var padding = mdastUtilToString(head).match(/^ +/); + + if (padding) { + indentation += padding[0].length; + } + + return indentation +} + +var remarkLintCheckboxCharacterStyle = unifiedLintRule( + 'remark-lint:checkbox-character-style', + checkboxCharacterStyle +); + +var start$7 = unistUtilPosition.start; +var end$3 = unistUtilPosition.end; + +var checked = {x: true, X: true}; +var unchecked = {' ': true, '\t': true}; +var types$1 = {true: 'checked', false: 'unchecked'}; + +function checkboxCharacterStyle(tree, file, pref) { + var contents = String(file); + var location = vfileLocation(file); + + pref = typeof pref === 'object' ? pref : {}; + + if (pref.unchecked && unchecked[pref.unchecked] !== true) { + file.fail( + 'Invalid unchecked checkbox marker `' + + pref.unchecked + + "`: use either `'\\t'`, or `' '`" + ); + } + + if (pref.checked && checked[pref.checked] !== true) { + file.fail( + 'Invalid checked checkbox marker `' + + pref.checked + + "`: use either `'x'`, or `'X'`" + ); + } + + unistUtilVisit(tree, 'listItem', visitor); + + function visitor(node) { + var type; + var initial; + var final; + var value; + var style; + var character; + var reason; + + // Exit early for items without checkbox. + if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { + return + } + + type = types$1[node.checked]; + initial = start$7(node).offset; + final = (node.children.length === 0 ? end$3(node) : start$7(node.children[0])) + .offset; + + // For a checkbox to be parsed, it must be followed by a whitespace. + value = contents + .slice(initial, final) + .trimRight() + .slice(0, -1); + + // The checkbox character is behind a square bracket. + character = value.charAt(value.length - 1); + style = pref[type]; + + if (style) { + if (character !== style) { + reason = + type.charAt(0).toUpperCase() + + type.slice(1) + + ' checkboxes should use `' + + style + + '` as a marker'; + + file.message(reason, { + start: location.toPosition(initial + value.length - 1), + end: location.toPosition(initial + value.length) + }); + } + } else { + pref[type] = character; + } + } +} + +var remarkLintCheckboxContentIndent = unifiedLintRule( + 'remark-lint:checkbox-content-indent', + checkboxContentIndent +); + +var start$8 = unistUtilPosition.start; +var end$4 = unistUtilPosition.end; + +var reason$9 = 'Checkboxes should be followed by a single character'; + +function checkboxContentIndent(tree, file) { + var contents = String(file); + var location = vfileLocation(file); + + unistUtilVisit(tree, 'listItem', visitor); + + function visitor(node) { + var initial; + var final; + var value; + + // Exit early for items without checkbox. + if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { + return + } + + initial = start$8(node).offset; + /* istanbul ignore next - hard to test, couldn’t find a case. */ + final = (node.children.length === 0 ? end$4(node) : start$8(node.children[0])) + .offset; + + while (/[^\S\n]/.test(contents.charAt(final))) { + final++; + } + + // For a checkbox to be parsed, it must be followed by a whitespace. + value = contents.slice(initial, final); + value = value.slice(value.indexOf(']') + 1); + + if (value.length !== 1) { + file.message(reason$9, { + start: location.toPosition(final - value.length + 1), + end: location.toPosition(final) + }); + } + } +} + +var remarkLintCodeBlockStyle = unifiedLintRule('remark-lint:code-block-style', codeBlockStyle); + +var start$9 = unistUtilPosition.start; +var end$5 = unistUtilPosition.end; + +var styles$2 = {null: true, fenced: true, indented: true}; + +function codeBlockStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$2[pref] !== true) { + file.fail( + 'Invalid code block style `' + + pref + + "`: use either `'consistent'`, `'fenced'`, or `'indented'`" + ); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var current = check(node); + + if (current) { + if (!pref) { + pref = current; + } else if (pref !== current) { + file.message('Code blocks should be ' + pref, node); + } + } + } + + // Get the style of `node`. + function check(node) { + var initial = start$9(node).offset; + var final = end$5(node).offset; + + if (unistUtilGenerated(node)) { + return null + } + + return node.lang || /^\s*([~`])\1{2,}/.test(contents.slice(initial, final)) + ? 'fenced' + : 'indented' + } +} + +var remarkLintDefinitionSpacing = unifiedLintRule('remark-lint:definition-spacing', definitionSpacing); + +var label$1 = /^\s*\[((?:\\[\s\S]|[^[\]])+)]/; +var reason$a = 'Do not use consecutive white-space in definition labels'; + +function definitionSpacing(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], validate); + + function validate(node) { + var start = unistUtilPosition.start(node).offset; + var end = unistUtilPosition.end(node).offset; + + if ( + !unistUtilGenerated(node) && + /[ \t\n]{2,}/.test(contents.slice(start, end).match(label$1)[1]) + ) { + file.message(reason$a, node); + } + } +} + +var remarkLintFencedCodeFlag = unifiedLintRule('remark-lint:fenced-code-flag', fencedCodeFlag); + +var start$a = unistUtilPosition.start; +var end$6 = unistUtilPosition.end; + +var fence$2 = /^ {0,3}([~`])\1{2,}/; +var reasonInvalid = 'Invalid code-language flag'; +var reasonMissing = 'Missing code-language flag'; + +function fencedCodeFlag(tree, file, pref) { + var contents = String(file); + var allowEmpty = false; + var flags = []; + + if (typeof pref === 'object' && !('length' in pref)) { + allowEmpty = Boolean(pref.allowEmpty); + pref = pref.flags; + } + + if (typeof pref === 'object' && 'length' in pref) { + flags = String(pref).split(','); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var value; + + if (!unistUtilGenerated(node)) { + if (node.lang) { + if (flags.length !== 0 && flags.indexOf(node.lang) === -1) { + file.message(reasonInvalid, node); + } + } else { + value = contents.slice(start$a(node).offset, end$6(node).offset); + + if (!allowEmpty && fence$2.test(value)) { + file.message(reasonMissing, node); + } + } + } + } +} + +var remarkLintFencedCodeMarker = unifiedLintRule('remark-lint:fenced-code-marker', fencedCodeMarker); + +var markers = { + '`': true, + '~': true, + null: true +}; + +function fencedCodeMarker(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (markers[pref] !== true) { + file.fail( + 'Invalid fenced code marker `' + + pref + + "`: use either `'consistent'`, `` '`' ``, or `'~'`" + ); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var marker; + + if (!unistUtilGenerated(node)) { + marker = contents + .substr(unistUtilPosition.start(node).offset, 4) + .trimLeft() + .charAt(0); + + // Ignore unfenced code blocks. + if (markers[marker] === true) { + if (pref) { + if (marker !== pref) { + file.message( + 'Fenced code should use ' + pref + ' as a marker', + node + ); + } + } else { + pref = marker; + } + } + } + } +} + +var remarkLintFileExtension = unifiedLintRule('remark-lint:file-extension', fileExtension); + +function fileExtension(tree, file, pref) { + var ext = file.extname; + + pref = typeof pref === 'string' ? pref : 'md'; + + if (ext && ext.slice(1) !== pref) { + file.message('Invalid extension: use `' + pref + '`'); + } +} + +var remarkLintFinalDefinition = unifiedLintRule('remark-lint:final-definition', finalDefinition); + +var start$b = unistUtilPosition.start; + +function finalDefinition(tree, file) { + var last = null; + + unistUtilVisit(tree, visitor, true); + + function visitor(node) { + var line = start$b(node).line; + + // Ignore generated nodes. + if (node.type === 'root' || unistUtilGenerated(node)) { + return + } + + if (node.type === 'definition') { + if (last !== null && last > line) { + file.message( + 'Move definitions to the end of the file (after the node at line `' + + last + + '`)', + node + ); + } + } else if (last === null) { + last = line; + } + } +} + +var remarkLintFirstHeadingLevel = unifiedLintRule('remark-lint:first-heading-level', firstHeadingLevel); + +var re$3 = /. + unistUtilVisit(tree, ['heading', 'table', 'code', 'definition', 'html', 'jsx'], ignore); + unistUtilVisit(tree, ['link', 'image', 'inlineCode'], inline); + + // Iterate over every line, and warn for violating lines. + while (++index < length) { + lineLength = lines[index].length; + + if (lineLength > style) { + file.message('Line must be at most ' + style + ' characters', { + line: index + 1, + column: lineLength + 1 + }); + } + } + + // Finally, whitelist some inline spans, but only if they occur at or after + // the wrap. + // However, when they do, and there’s whitespace after it, they are not + // whitelisted. + function inline(node, pos, parent) { + var next = parent.children[pos + 1]; + var initial; + var final; + + /* istanbul ignore if - Nothing to whitelist when generated. */ + if (unistUtilGenerated(node)) { + return + } + + initial = start$c(node); + final = end$7(node); + + // No whitelisting when starting after the border, or ending before it. + if (initial.column > style || final.column < style) { + return + } + + // No whitelisting when there’s whitespace after the link. + if ( + next && + start$c(next).line === initial.line && + (!next.value || /^(.+?[ \t].+?)/.test(next.value)) + ) { + return + } + + whitelist(initial.line - 1, final.line); + } + + function ignore(node) { + /* istanbul ignore else - Hard to test, as we only run this case on `position: true` */ + if (!unistUtilGenerated(node)) { + whitelist(start$c(node).line - 1, end$7(node).line); + } + } + + // Whitelist from `initial` to `final`, zero-based. + function whitelist(initial, final) { + while (initial < final) { + lines[initial++] = ''; + } + } +} + +var remarkLintNoConsecutiveBlankLines = unifiedLintRule( + 'remark-lint:no-consecutive-blank-lines', + noConsecutiveBlankLines +); + +function noConsecutiveBlankLines(tree, file) { + unistUtilVisit(tree, visitor); + + function visitor(node) { + var children = node.children; + var head; + var tail; + + if (!unistUtilGenerated(node) && children) { + head = children[0]; + + if (head && !unistUtilGenerated(head)) { + // Compare parent and first child. + compare(unistUtilPosition.start(node), unistUtilPosition.start(head), 0); + + // Compare between each child. + children.forEach(visitChild); + + tail = children[children.length - 1]; + + // Compare parent and last child. + if (tail !== head && !unistUtilGenerated(tail)) { + compare(unistUtilPosition.end(node), unistUtilPosition.end(tail), 1); + } + } + } + } + + // Compare the difference between `start` and `end`, and warn when that + // difference exceeds `max`. + function compare(start, end, max) { + var diff = end.line - start.line; + var lines = Math.abs(diff) - max; + var reason; + + if (lines > 0) { + reason = + 'Remove ' + + lines + + ' ' + + plur('line', lines) + + ' ' + + (diff > 0 ? 'before' : 'after') + + ' node'; + + file.message(reason, end); + } + } + + function visitChild(child, index, all) { + var prev = all[index - 1]; + var max = 2; + + if (prev && !unistUtilGenerated(prev) && !unistUtilGenerated(child)) { + if ( + (prev.type === 'list' && child.type === 'list') || + (child.type === 'code' && prev.type === 'list' && !child.lang) + ) { + max++; + } + + compare(unistUtilPosition.end(prev), unistUtilPosition.start(child), max); + } + } +} + +var remarkLintNoFileNameArticles = unifiedLintRule('remark-lint:no-file-name-articles', noFileNameArticles); + +function noFileNameArticles(tree, file) { + var match = file.stem && file.stem.match(/^(the|teh|an?)\b/i); + + if (match) { + file.message('Do not start file names with `' + match[0] + '`'); + } +} + +var remarkLintNoFileNameConsecutiveDashes = unifiedLintRule( + 'remark-lint:no-file-name-consecutive-dashes', + noFileNameConsecutiveDashes +); + +var reason$b = 'Do not use consecutive dashes in a file name'; + +function noFileNameConsecutiveDashes(tree, file) { + if (file.stem && /-{2,}/.test(file.stem)) { + file.message(reason$b); + } +} + +var remarkLintNoFileNameOuterDashes = unifiedLintRule( + 'remark-lint:no-file-name-outer-dashes', + noFileNameOuterDashes +); + +var reason$c = 'Do not use initial or final dashes in a file name'; + +function noFileNameOuterDashes(tree, file) { + if (file.stem && /^-|-$/.test(file.stem)) { + file.message(reason$c); + } +} + +var remarkLintNoHeadingIndent = unifiedLintRule('remark-lint:no-heading-indent', noHeadingIndent); + +var start$d = unistUtilPosition.start; + +function noHeadingIndent(tree, file) { + var contents = String(file); + var length = contents.length; + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + var initial; + var begin; + var index; + var character; + var diff; + + if (unistUtilGenerated(node)) { + return + } + + initial = start$d(node); + begin = initial.offset; + index = begin - 1; + + while (++index < length) { + character = contents.charAt(index); + + if (character !== ' ' && character !== '\t') { + break + } + } + + diff = index - begin; + + if (diff) { + file.message( + 'Remove ' + diff + ' ' + plur('space', diff) + ' before this heading', + { + line: initial.line, + column: initial.column + diff + } + ); + } + } +} + +var start$e = unistUtilPosition.start; + + + +var remarkLintNoMultipleToplevelHeadings = unifiedLintRule( + 'remark-lint:no-multiple-toplevel-headings', + noMultipleToplevelHeadings +); + +function noMultipleToplevelHeadings(tree, file, pref) { + var style = pref ? pref : 1; + var duplicate; + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.depth === style) { + if (duplicate) { + file.message( + 'Don’t use multiple top level headings (' + duplicate + ')', + node + ); + } else { + duplicate = unistUtilStringifyPosition(start$e(node)); + } + } + } +} + +var remarkLintNoShellDollars = unifiedLintRule('remark-lint:no-shell-dollars', noShellDollars); + +var reason$d = 'Do not use dollar signs before shell-commands'; + +// List of shell script file extensions (also used as code flags for syntax +// highlighting on GitHub): +// See: +var flags = [ + 'sh', + 'bash', + 'bats', + 'cgi', + 'command', + 'fcgi', + 'ksh', + 'tmux', + 'tool', + 'zsh' +]; + +function noShellDollars(tree, file) { + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var lines; + var line; + var length; + var index; + + // Check both known shell code and unknown code. + if (!unistUtilGenerated(node) && node.lang && flags.indexOf(node.lang) !== -1) { + lines = node.value.split('\n'); + length = lines.length; + index = -1; + + if (length <= 1) { + return + } + + while (++index < length) { + line = lines[index]; + + if (line.trim() && !line.match(/^\s*\$\s*/)) { + return + } + } + + file.message(reason$d, node); + } + } +} + +var remarkLintNoTableIndentation = unifiedLintRule('remark-lint:no-table-indentation', noTableIndentation); + +var reason$e = 'Do not indent table rows'; + +function noTableIndentation(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node)) { + node.children.forEach(each); + } + + return unistUtilVisit.SKIP + } + + function each(row) { + var fence = contents.slice( + unistUtilPosition.start(row).offset, + unistUtilPosition.start(row.children[0]).offset + ); + + if (fence.indexOf('|') > 1) { + file.message(reason$e, row); + } + } +} + +var remarkLintNoTabs = unifiedLintRule('remark-lint:no-tabs', noTabs); + +var reason$f = 'Use spaces instead of hard-tabs'; + +function noTabs(tree, file) { + var content = String(file); + var position = vfileLocation(file).toPosition; + var index = content.indexOf('\t'); + + while (index !== -1) { + file.message(reason$f, position(index)); + index = content.indexOf('\t', index + 1); + } +} + +var remarkLintNoTrailingSpaces = unifiedLintRule('remark-lint:no-trailing-spaces', noTrailingSpaces); + +/** + * Lines that are just space characters are not present in + * the AST, which is why we loop through lines manually. + */ + +function noTrailingSpaces(ast, file) { + var lines = file.toString().split(/\r?\n/); + for (var i = 0; i < lines.length; i++) { + var currentLine = lines[i]; + var lineIndex = i + 1; + if (/\s$/.test(currentLine)) { + file.message('Remove trailing whitespace', { + position: { + start: { line: lineIndex, column: currentLine.length + 1 }, + end: { line: lineIndex } + } + }); + } + } +} + +var remarkLintProhibitedStrings = unifiedLintRule('remark-lint:prohibited-strings', prohibitedStrings); + +function testProhibited(val, content) { + const re = new RegExp(`(\\.|@[a-z0-9/-]*)?\\b(${val.no})\\b(\\.\\w)?`, 'g'); + + let result = null; + while (result = re.exec(content)) { + if (!result[1] && !result[3]) { + return result[2]; + } + } + + return false; +} + +function prohibitedStrings(ast, file, strings) { + unistUtilVisit(ast, 'text', checkText); + + function checkText(node) { + const content = node.value; + + strings.forEach((val) => { + const result = testProhibited(val, content); + if (result) { + file.message(`Use "${val.yes}" instead of "${result}"`, node); + } + }); + } +} + +var rule = unifiedLintRule; + + + + +var remarkLintRuleStyle = rule('remark-lint:rule-style', ruleStyle); + +var start$f = unistUtilPosition.start; +var end$8 = unistUtilPosition.end; + +function ruleStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (pref !== null && /[^-_* ]/.test(pref)) { + file.fail( + "Invalid preferred rule-style: provide a valid markdown rule, or `'consistent'`" + ); + } + + unistUtilVisit(tree, 'thematicBreak', visitor); + + function visitor(node) { + var initial = start$f(node).offset; + var final = end$8(node).offset; + var rule; + + if (!unistUtilGenerated(node)) { + rule = contents.slice(initial, final); + + if (pref) { + if (rule !== pref) { + file.message('Rules should use `' + pref + '`', node); + } + } else { + pref = rule; + } + } + } +} + +var remarkLintStrongMarker = unifiedLintRule('remark-lint:strong-marker', strongMarker); + +var markers$1 = {'*': true, _: true, null: true}; + +function strongMarker(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (markers$1[pref] !== true) { + file.fail( + 'Invalid strong marker `' + + pref + + "`: use either `'consistent'`, `'*'`, or `'_'`" + ); + } + + unistUtilVisit(tree, 'strong', visitor); + + function visitor(node) { + var marker = contents.charAt(unistUtilPosition.start(node).offset); + + if (!unistUtilGenerated(node)) { + if (pref) { + if (marker !== pref) { + file.message('Strong should use `' + pref + '` as a marker', node); + } + } else { + pref = marker; + } + } + } +} + +var remarkLintTableCellPadding = unifiedLintRule('remark-lint:table-cell-padding', tableCellPadding); + +var start$g = unistUtilPosition.start; +var end$9 = unistUtilPosition.end; + +var styles$3 = {null: true, padded: true, compact: true}; + +function tableCellPadding(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$3[pref] !== true) { + file.fail('Invalid table-cell-padding style `' + pref + '`'); + } + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + var rows = node.children; + var sizes = new Array(node.align.length); + var length = unistUtilGenerated(node) ? -1 : rows.length; + var index = -1; + var entries = []; + var style; + var row; + var cells; + var column; + var cellCount; + var cell; + var next; + var fence; + var pos; + var entry; + var final; + + // Check rows. + while (++index < length) { + row = rows[index]; + cells = row.children; + cellCount = cells.length; + column = -2; // Start without a first cell. + next = null; + final = undefined; + + // Check fences (before, between, and after cells). + while (++column < cellCount) { + cell = next; + next = cells[column + 1]; + + fence = contents.slice( + cell ? end$9(cell).offset : start$g(row).offset, + next ? start$g(next).offset : end$9(row).offset + ); + + pos = fence.indexOf('|'); + + if (cell && cell.children.length !== 0 && final !== undefined) { + entries.push({node: cell, start: final, end: pos, index: column}); + + // Detect max space per column. + sizes[column] = Math.max(sizes[column] || 0, size(cell)); + } else { + final = undefined; + } + + if (next && next.children.length !== 0) { + final = fence.length - pos - 1; + } else { + final = undefined; + } + } + } + + if (pref) { + style = pref === 'padded' ? 1 : 0; + } else { + style = entries[0] && (!entries[0].start || !entries[0].end) ? 0 : 1; + } + + index = -1; + length = entries.length; + + while (++index < length) { + entry = entries[index]; + checkSide('start', entry, style, sizes); + checkSide('end', entry, style, sizes); + } + + return unistUtilVisit.SKIP + } + + function checkSide(side, entry, style, sizes) { + var cell = entry.node; + var spacing = entry[side]; + var index = entry.index; + var reason; + + if (spacing === undefined || spacing === style) { + return + } + + reason = 'Cell should be '; + + if (style === 0) { + reason += 'compact'; + + // Ignore every cell except the biggest in the column. + if (size(cell) < sizes[index]) { + return + } + } else { + reason += 'padded'; + + if (spacing > style) { + reason += ' with 1 space, not ' + spacing; + + // May be right or center aligned. + if (size(cell) < sizes[index]) { + return + } + } + } + + file.message(reason, cell.position[side]); + } +} + +function size(node) { + return end$9(node).offset - start$g(node).offset +} + +var remarkLintTablePipes = unifiedLintRule('remark-lint:table-pipes', tablePipes); + +var start$h = unistUtilPosition.start; +var end$a = unistUtilPosition.end; + +var reasonStart = 'Missing initial pipe in table fence'; +var reasonEnd = 'Missing final pipe in table fence'; + +function tablePipes(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + var rows = node.children; + var length = rows.length; + var index = -1; + var row; + var cells; + var head; + var tail; + var initial; + var final; + + while (++index < length) { + row = rows[index]; + + if (!unistUtilGenerated(row)) { + cells = row.children; + head = cells[0]; + tail = cells[cells.length - 1]; + initial = contents.slice(start$h(row).offset, start$h(head).offset); + final = contents.slice(end$a(tail).offset, end$a(row).offset); + + if (initial.indexOf('|') === -1) { + file.message(reasonStart, start$h(row)); + } + + if (final.indexOf('|') === -1) { + file.message(reasonEnd, end$a(row)); + } + } + } + } +} + +var remarkLintUnorderedListMarkerStyle = unifiedLintRule( + 'remark-lint:unordered-list-marker-style', + unorderedListMarkerStyle +); + +var start$i = unistUtilPosition.start; + +var styles$4 = { + '-': true, + '*': true, + '+': true, + null: true +}; + +function unorderedListMarkerStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$4[pref] !== true) { + file.fail( + 'Invalid unordered list-item marker style `' + + pref + + "`: use either `'-'`, `'*'`, or `'+'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var children = node.children; + var length = node.ordered ? 0 : children.length; + var index = -1; + var child; + var marker; + + while (++index < length) { + child = children[index]; + + if (!unistUtilGenerated(child)) { + marker = contents + .slice(start$i(child).offset, start$i(child.children[0]).offset) + .replace(/\[[x ]?]\s*$/i, '') + .replace(/\s/g, ''); + + if (pref) { + if (marker !== pref) { + file.message('Marker style should be `' + pref + '`', child); + } + } else { + pref = marker; + } + } + } + } +} + +// Add in rules alphabetically +var plugins$2 = [ + remarkLint, + // Leave preset at the top so it can be overridden + remarkPresetLintRecommended, + [remarkLintBlockquoteIndentation, 2], + [ + remarkLintCheckboxCharacterStyle, + { + checked: "x", + unchecked: " " + } + ], + remarkLintCheckboxContentIndent, + [remarkLintCodeBlockStyle, "fenced"], + remarkLintDefinitionSpacing, + remarkLintFencedCodeFlag, + [remarkLintFencedCodeMarker, "`"], + [remarkLintFileExtension, "md"], + remarkLintFinalDefinition, + [remarkLintFirstHeadingLevel, 1], + [remarkLintHeadingStyle, "atx"], + [remarkLintListItemIndent, "space"], + remarkLintMaximumLineLength, + remarkLintNoConsecutiveBlankLines, + remarkLintNoFileNameArticles, + remarkLintNoFileNameConsecutiveDashes, + remarkLintNoFileNameOuterDashes, + remarkLintNoHeadingIndent, + [remarkLintNoLiteralUrls, false], + remarkLintNoMultipleToplevelHeadings, + remarkLintNoShellDollars, + remarkLintNoTableIndentation, + remarkLintNoTabs, + remarkLintNoTrailingSpaces, + [ + remarkLintProhibitedStrings, + [ + { no: "End-Of-Life", yes: "End-of-Life" }, + { no: "End-of-life", yes: "End-of-Life" }, + { no: "Github", yes: "GitHub" }, + { no: "hostname", yes: "host name" }, + { no: "[Jj]avascript", yes: "JavaScript" }, + { no: "Node", yes: "Node.js" }, + { no: "Node.JS", yes: "Node.js" }, + { no: "node.js", yes: "Node.js" }, + { no: "[Nn]ote that", yes: "" }, + { no: "Rfc", yes: "RFC" }, + { no: "[Rr][Ff][Cc]\\d+", yes: "RFC " }, + { no: "rfc", yes: "RFC" }, + { no: "UNIX", yes: "Unix" }, + { no: "unix", yes: "Unix" }, + { no: "v8", yes: "V8" } + ] + ], + remarkLintRuleStyle, + [remarkLintStrongMarker, "*"], + [remarkLintTableCellPadding, "padded"], + remarkLintTablePipes, + [remarkLintUnorderedListMarkerStyle, "*"] +]; + +var remarkPresetLintNode = { + plugins: plugins$2 +}; + +var proc = getCjsExportFromNamespace(_package$1); + +var cli = getCjsExportFromNamespace(_package$3); + +// To aid in future maintenance, this layout closely matches remark-cli/cli.js. +// https://github.com/remarkjs/remark/blob/master/packages/remark-cli/cli.js + + + + + + + + +unifiedArgs({ + processor: remark().use(remarkPresetLintNode), + name: proc.name, + description: cli.description, + version: [ + proc.name + ': ' + proc.version, + cli.name + ': ' + cli.version, + ].join(', '), + pluginPrefix: proc.name, + presetPrefix: proc.name + '-preset', + packageField: proc.name + 'Config', + rcName: '.' + proc.name + 'rc', + ignoreName: '.' + proc.name + 'ignore', + extensions: markdownExtensions$2, + detectConfig: false, +}); diff --git a/tools/make-v8.sh b/tools/make-v8.sh index 41c5ff76dbd641..37bc57f4994fb0 100755 --- a/tools/make-v8.sh +++ b/tools/make-v8.sh @@ -8,35 +8,28 @@ tools/node/fetch_deps.py . ARCH="`arch`" if [[ "$ARCH" == "s390x" ]] || [[ "$ARCH" == "ppc64le" ]]; then + TARGET_ARCH=$ARCH + if [[ "$ARCH" == "ppc64le" ]]; then + TARGET_ARCH="ppc64" + fi # set paths manually for now to use locally installed gn export BUILD_TOOLS=/home/iojs/build-tools export LD_LIBRARY_PATH=$BUILD_TOOLS:$LD_LIBRARY_PATH - export PATH=$BUILD_TOOLS:$PATH - if [[ X"$CXX" != X ]]; then - CXX_PATH=`which $CXX |grep g++` - fi - if [[ X"$CC" != X ]]; then - CC_PATH=`which $CC |grep gcc` - fi + # Avoid linking to ccache symbolic links as ccache decides which + # binary to run based on the name of the link (we always name them gcc/g++). + CC_PATH=`which -a $CC gcc | grep -v ccache | head -n 1` + CXX_PATH=`which -a $CXX g++ | grep -v ccache | head -n 1` rm -f "$BUILD_TOOLS/g++" rm -f "$BUILD_TOOLS/gcc" -fi -if [[ "$ARCH" == "s390x" ]]; then ln -s $CXX_PATH "$BUILD_TOOLS/g++" ln -s $CC_PATH "$BUILD_TOOLS/gcc" + export PATH=$BUILD_TOOLS:$PATH + g++ --version + gcc --version export PKG_CONFIG_PATH=$BUILD_TOOLS/pkg-config - gn gen -v out.gn/$BUILD_ARCH_TYPE --args='is_component_build=false is_debug=false use_goma=false goma_dir="None" use_custom_libcxx=false v8_target_cpu="s390x" target_cpu="s390x"' + gn gen -v out.gn/$BUILD_ARCH_TYPE --args="is_component_build=false is_debug=false use_goma=false goma_dir=\"None\" use_custom_libcxx=false v8_target_cpu=\"$TARGET_ARCH\" target_cpu=\"$TARGET_ARCH\"" ninja -v -C out.gn/$BUILD_ARCH_TYPE d8 cctest inspector-test -elif [[ "$ARCH" == "ppc64le" ]]; then - if [[ X"$CXX" != X ]]; then - ln -s /usr/bin/$CXX "$BUILD_TOOLS/g++" - ln -s /usr/bin/$CC "$BUILD_TOOLS/gcc" - fi - g++ --version - export PKG_CONFIG_PATH=$BUILD_TOOLS/pkg-config-files - gn gen out.gn/$BUILD_ARCH_TYPE --args='is_component_build=false is_debug=false use_goma=false goma_dir="None" use_custom_libcxx=false v8_target_cpu="ppc64" target_cpu="ppc64"' - ninja -C out.gn/$BUILD_ARCH_TYPE d8 cctest inspector-test else PATH=~/_depot_tools:$PATH tools/dev/v8gen.py $BUILD_ARCH_TYPE --no-goma $V8_BUILD_OPTIONS PATH=~/_depot_tools:$PATH ninja -C out.gn/$BUILD_ARCH_TYPE/ d8 cctest inspector-test diff --git a/tools/node-lint-md-cli-rollup/package-lock.json b/tools/node-lint-md-cli-rollup/package-lock.json index 933c9ffbda3c7d..af4ac3812a00e1 100644 --- a/tools/node-lint-md-cli-rollup/package-lock.json +++ b/tools/node-lint-md-cli-rollup/package-lock.json @@ -1,20 +1,90 @@ { "name": "node-lint-md-cli-rollup", - "version": "2.0.1", + "version": "2.0.2", "lockfileVersion": 1, "requires": true, "dependencies": { + "@rollup/plugin-commonjs": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.0.1.tgz", + "integrity": "sha512-SaVUoaLDg3KnIXC5IBNIspr1APTYDzk05VaYcI6qz+0XX3ZlSCwAkfAhNSOxfd5GAdcm/63Noi4TowOY9MpcDg==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.0.0", + "estree-walker": "^0.6.1", + "is-reference": "^1.1.2", + "magic-string": "^0.25.2", + "resolve": "^1.11.0" + } + }, + "@rollup/plugin-json": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.0.1.tgz", + "integrity": "sha512-soxllkhOGgchswBAAaTe7X9G80U2tjjHvXv0sBrriLJcC/89PkP59iTrKPOfbz3SjX088mKDmMhAscuyLz8ZSg==", + "dev": true, + "requires": { + "rollup-pluginutils": "^2.5.0" + } + }, + "@rollup/plugin-node-resolve": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.0.0.tgz", + "integrity": "sha512-+vOx2+WMBMFotYKM3yYeDGZxIvcQ7yO4g+SuKDFsjKaq8Lw3EPgfB6qNlp8Z/3ceDCEhHvC9/b+PgBGwDQGbzQ==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.0.0", + "@types/resolve": "0.0.8", + "builtin-modules": "^3.1.0", + "is-module": "^1.0.0", + "resolve": "^1.11.1" + } + }, + "@rollup/pluginutils": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.0.4.tgz", + "integrity": "sha512-buc0oeq2zqQu2mpMyvZgAaQvitikYjT/4JYhA4EXwxX8/g0ZGHoGiX+0AwmfhrNqH4oJv67gn80sTZFQ/jL1bw==", + "dev": true, + "requires": { + "estree-walker": "^0.6.1" + } + }, + "@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "@types/node": { + "version": "13.1.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.8.tgz", + "integrity": "sha512-6XzyyNM9EKQW4HKuzbo/CkOIjn/evtCmsU+MUM1xDfJ+3/rNjBttM1NgN7AOQvN6tP1Sl1D1PIKMreTArnxM9A==", + "dev": true + }, + "@types/resolve": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", + "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, "@types/unist": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.3.tgz", "integrity": "sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ==" }, - "@zeit/ncc": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/@zeit/ncc/-/ncc-0.21.0.tgz", - "integrity": "sha512-RUMdvVK/w78oo+yBjruZltt0kJXYar2un/1bYQ2LuHG7GmFVm+QjxzEmySwREctaJdEnBvlMdUNWd9hXHxEI3g==", + "acorn": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.0.tgz", + "integrity": "sha512-kL5CuoXA/dgxlBbVrflsflzQ3PAas7RYZB52NOm/6839iVYJgKMJ3cQJD+t2i5+qFa8h3MDpEOJiS64E8JLnSQ==", "dev": true }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" + }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -77,6 +147,12 @@ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" }, + "builtin-modules": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.1.0.tgz", + "integrity": "sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw==", + "dev": true + }, "camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -160,6 +236,17 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, + "concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, "debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", @@ -186,6 +273,12 @@ "is-arrayish": "^0.2.1" } }, + "es6-object-assign": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz", + "integrity": "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw=", + "dev": true + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -196,6 +289,12 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, + "estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -272,6 +371,11 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, + "ignore": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", + "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" + }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -291,6 +395,12 @@ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, + "interpret": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", + "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", + "dev": true + }, "irregular-plurals": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-2.0.0.tgz", @@ -348,6 +458,11 @@ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, "is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -366,6 +481,12 @@ "resolved": "https://registry.npmjs.org/is-hidden/-/is-hidden-1.1.2.tgz", "integrity": "sha512-kytBeNVW2QTIqZdJBDKIjP+EkUTzDT07rsc111w/gxqR6wK3ODkOswcpxgED6HU6t7fEhOxqojVZ2a2kU9rj+A==" }, + "is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "dev": true + }, "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -381,6 +502,15 @@ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.0.0.tgz", "integrity": "sha512-EYisGhpgSCwspmIuRHGjROWTon2Xp8Z7U03Wubk/bTL5TTRC5R1rGVgyjzBrk9+ULdH6cRD06KRcw/xfqhVYKQ==" }, + "is-reference": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz", + "integrity": "sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw==", + "dev": true, + "requires": { + "@types/estree": "0.0.39" + } + }, "is-whitespace-character": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-whitespace-character/-/is-whitespace-character-1.0.3.tgz", @@ -427,6 +557,15 @@ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-2.0.3.tgz", "integrity": "sha512-9lz5IVdpwsKLMzQi0MQ+oD9EA0mIGcWYP7jXMTZVXP8D42PwuAk+M/HBFYQoxt1G5OR8m7aSIgb1UymfWGBWEw==" }, + "magic-string": { + "version": "0.25.6", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.6.tgz", + "integrity": "sha512-3a5LOMSGoCTH5rbqobC2HuDNRtE2glHZ8J7pK+QZYppyWA36yuNpsX994rIY2nCuyP7CZYy7lQq/X2jygiZ89g==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.4" + } + }, "markdown-escapes": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/markdown-escapes/-/markdown-escapes-1.0.3.tgz", @@ -538,6 +677,12 @@ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, "picomatch": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz", @@ -562,6 +707,16 @@ "strip-json-comments": "~2.0.1" } }, + "readable-stream": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.5.0.tgz", + "integrity": "sha512-gSz026xs2LfxBPudDuI41V1lka8cxg64E66SGe78zJlsUofOg/yqwezdIcdfwik6B4h8LFmWPA9ef9X3FiNFLA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, "readdirp": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz", @@ -570,6 +725,15 @@ "picomatch": "^2.0.7" } }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, "remark": { "version": "11.0.2", "resolved": "https://registry.npmjs.org/remark/-/remark-11.0.2.tgz", @@ -1174,26 +1338,83 @@ "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=" }, + "resolve": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.14.2.tgz", + "integrity": "sha512-EjlOBLBO1kxsUxsKjLt7TAECyKW6fOh1VRkykQkKGzcBbjjPIxBqGh0jf7GJ3k/f5mxMqW3htMD3WdTUVtW8HQ==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" }, + "rollup": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.30.1.tgz", + "integrity": "sha512-Uus8mwQXwaO+ZVoNwBcXKhT0AvycFCBW/W8VZtkpVGsotRllWk9oldfCjqWmTnFRI0y7x6BnEqSqc65N+/YdBw==", + "dev": true, + "requires": { + "@types/estree": "*", + "@types/node": "*", + "acorn": "^7.1.0" + } + }, + "rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "requires": { + "estree-walker": "^0.6.1" + } + }, "safe-buffer": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" }, + "shelljs": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.3.tgz", + "integrity": "sha512-fc0BKlAWiLpwZljmOvAOTE/gXawtCoNrP5oaY7KIaQbbyHeQVg01pSEuEGvGh3HEdBU4baCD7wQBwADmM/7f7A==", + "dev": true, + "requires": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + } + }, "shellsubstitute": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shellsubstitute/-/shellsubstitute-1.2.0.tgz", "integrity": "sha1-5PcCpQxRiw9v6YRRiQ1wWvKba3A=" }, + "shx": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/shx/-/shx-0.3.2.tgz", + "integrity": "sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA==", + "dev": true, + "requires": { + "es6-object-assign": "^1.0.3", + "minimist": "^1.2.0", + "shelljs": "^0.8.1" + } + }, "sliced": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" }, + "sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -1204,6 +1425,16 @@ "resolved": "https://registry.npmjs.org/state-toggle/-/state-toggle-1.0.2.tgz", "integrity": "sha512-8LpelPGR0qQM4PnfLiplOQNJcIN1/r2Gy0xKB2zKnIW2YzPMt2sR4I/+gtPjhN7Svh9kw+zqEg2SFwpBO9iNiw==" }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, "string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -1224,6 +1455,14 @@ "is-hexadecimal": "^1.0.0" } }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "requires": { + "ansi-regex": "^5.0.0" + } + }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -1250,6 +1489,15 @@ "is-number": "^7.0.0" } }, + "to-vfile": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/to-vfile/-/to-vfile-6.0.0.tgz", + "integrity": "sha512-i9fwXXSsHLu7mzgixc1WjgnqSe6pGpjnzCYoFmrASvEueLfyKf09QAe+XQYu8OAJ62aFqHpe2EKXojeRVvEzqA==", + "requires": { + "is-buffer": "^2.0.0", + "vfile": "^4.0.0" + } + }, "trim": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/trim/-/trim-0.0.1.tgz", @@ -1304,119 +1552,33 @@ "minimist": "^1.2.0", "text-table": "^0.2.0", "unified-engine": "^7.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" - }, - "concat-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", - "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.0.2", - "typedarray": "^0.0.6" - } - }, - "ignore": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", - "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" - }, - "readable-stream": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", - "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "string-width": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", - "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" - } - }, - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", - "requires": { - "ansi-regex": "^5.0.0" - } - }, - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "requires": { - "has-flag": "^3.0.0" - } - }, - "to-vfile": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/to-vfile/-/to-vfile-6.0.0.tgz", - "integrity": "sha512-i9fwXXSsHLu7mzgixc1WjgnqSe6pGpjnzCYoFmrASvEueLfyKf09QAe+XQYu8OAJ62aFqHpe2EKXojeRVvEzqA==", - "requires": { - "is-buffer": "^2.0.0", - "vfile": "^4.0.0" - } - }, - "unified-engine": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/unified-engine/-/unified-engine-7.0.0.tgz", - "integrity": "sha512-zH/MvcISpWg3JZtCoY/GYBw1WnVHkhnPoMBWpmuvAifCPSS9mzT9EbtimesJp6t2nnr/ojI0mg3TmkO1CjIwVA==", - "requires": { - "concat-stream": "^2.0.0", - "debug": "^4.0.0", - "fault": "^1.0.0", - "figures": "^3.0.0", - "fn-name": "^2.0.1", - "glob": "^7.0.3", - "ignore": "^5.0.0", - "is-empty": "^1.0.0", - "is-hidden": "^1.0.1", - "is-object": "^1.0.1", - "js-yaml": "^3.6.1", - "load-plugin": "^2.0.0", - "parse-json": "^4.0.0", - "to-vfile": "^6.0.0", - "trough": "^1.0.0", - "unist-util-inspect": "^4.1.2", - "vfile-reporter": "^6.0.0", - "vfile-statistics": "^1.1.0", - "x-is-string": "^0.1.0", - "xtend": "^4.0.1" - } - }, - "vfile-reporter": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/vfile-reporter/-/vfile-reporter-6.0.0.tgz", - "integrity": "sha512-8Is0XxFxWJUhPJdOg3CyZTqd3ICCWg6r304PuBl818ZG91h4FMS3Q+lrOPS+cs5/DZK3H0+AkJdH0J8JEwKtDA==", - "requires": { - "repeat-string": "^1.5.0", - "string-width": "^4.0.0", - "supports-color": "^6.0.0", - "unist-util-stringify-position": "^2.0.0", - "vfile-sort": "^2.1.2", - "vfile-statistics": "^1.1.0" - } - } + } + }, + "unified-engine": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/unified-engine/-/unified-engine-7.0.0.tgz", + "integrity": "sha512-zH/MvcISpWg3JZtCoY/GYBw1WnVHkhnPoMBWpmuvAifCPSS9mzT9EbtimesJp6t2nnr/ojI0mg3TmkO1CjIwVA==", + "requires": { + "concat-stream": "^2.0.0", + "debug": "^4.0.0", + "fault": "^1.0.0", + "figures": "^3.0.0", + "fn-name": "^2.0.1", + "glob": "^7.0.3", + "ignore": "^5.0.0", + "is-empty": "^1.0.0", + "is-hidden": "^1.0.1", + "is-object": "^1.0.1", + "js-yaml": "^3.6.1", + "load-plugin": "^2.0.0", + "parse-json": "^4.0.0", + "to-vfile": "^6.0.0", + "trough": "^1.0.0", + "unist-util-inspect": "^4.1.2", + "vfile-reporter": "^6.0.0", + "vfile-statistics": "^1.1.0", + "x-is-string": "^0.1.0", + "xtend": "^4.0.1" } }, "unified-lint-rule": { @@ -1531,6 +1693,29 @@ "unist-util-stringify-position": "^2.0.0" } }, + "vfile-reporter": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/vfile-reporter/-/vfile-reporter-6.0.0.tgz", + "integrity": "sha512-8Is0XxFxWJUhPJdOg3CyZTqd3ICCWg6r304PuBl818ZG91h4FMS3Q+lrOPS+cs5/DZK3H0+AkJdH0J8JEwKtDA==", + "requires": { + "repeat-string": "^1.5.0", + "string-width": "^4.0.0", + "supports-color": "^6.0.0", + "unist-util-stringify-position": "^2.0.0", + "vfile-sort": "^2.1.2", + "vfile-statistics": "^1.1.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, "vfile-sort": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/vfile-sort/-/vfile-sort-2.2.1.tgz", diff --git a/tools/node-lint-md-cli-rollup/package.json b/tools/node-lint-md-cli-rollup/package.json index 8e02bbcac7140f..67cad50ce21516 100644 --- a/tools/node-lint-md-cli-rollup/package.json +++ b/tools/node-lint-md-cli-rollup/package.json @@ -1,20 +1,24 @@ { "name": "node-lint-md-cli-rollup", "description": "remark packaged for Node.js Markdown linting", - "version": "2.0.1", + "version": "2.0.2", "devDependencies": { - "@zeit/ncc": "^0.21.0" + "@rollup/plugin-commonjs": "^11.0.1", + "@rollup/plugin-json": "^4.0.1", + "@rollup/plugin-node-resolve": "^7.0.0", + "rollup": "^1.30.1", + "shx": "^0.3.2" }, "dependencies": { "markdown-extensions": "^1.1.1", "remark": "^11.0.2", "remark-lint": "^6.0.5", - "remark-preset-lint-node": "^1.11.0", + "remark-preset-lint-node": "^1.12.0", "unified-args": "^7.1.0" }, - "main": "src/cli-entry.js", + "main": "dist/index.js", "scripts": { - "build": "ncc build -m", - "build-node": "npm run build && cp dist/index.js ../lint-md.js" + "build": "npx rollup -c", + "build-node": "npm run build && npx shx cp dist/index.js ../lint-md.js" } } diff --git a/tools/node-lint-md-cli-rollup/rollup.config.js b/tools/node-lint-md-cli-rollup/rollup.config.js new file mode 100644 index 00000000000000..73770d8836a9df --- /dev/null +++ b/tools/node-lint-md-cli-rollup/rollup.config.js @@ -0,0 +1,51 @@ +'use strict'; + +const resolve = require('@rollup/plugin-node-resolve'); +const commonjs = require('@rollup/plugin-commonjs'); +const json = require('@rollup/plugin-json'); + +module.exports = { + input: 'src/cli-entry.js', + output: { + file: 'dist/index.js', + format: 'cjs', + sourcemap: false, + }, + external: [ + 'stream', + 'path', + 'module', + 'util', + 'tty', + 'os', + 'fs', + 'fsevents', + 'events', + 'assert', + ], + plugins: [ + { + name: 'brute-replace', + transform(code, id) { + const normID = id.replace(__dirname, '').replace(/\\+/g, '/'); + if (normID === '/node_modules/concat-stream/index.js') { + return code.replace('\'readable-stream\'', '\'stream\''); + } + if (normID === '/node_modules/unified-args/lib/options.js') { + return code.replace('\'./schema\'', '\'./schema.json\''); + } + if (normID === '/node_modules/chokidar/lib/fsevents-handler.js' && + process.platform !== 'darwin') { + return code.replace( + 'fsevents = require(\'fsevents\');', 'fsevents = undefined;' + ); + } + } + }, + json({ + preferConst: true + }), + resolve(), // tells Rollup how to find date-fns in node_modules + commonjs(), // Converts date-fns to ES modules + ] +}; diff --git a/tools/node-lint-md-cli-rollup/src/cli-entry.js b/tools/node-lint-md-cli-rollup/src/cli-entry.js index 9fe8050b7ee071..a66c4a6894aef6 100644 --- a/tools/node-lint-md-cli-rollup/src/cli-entry.js +++ b/tools/node-lint-md-cli-rollup/src/cli-entry.js @@ -1,4 +1,3 @@ -#!/usr/bin/env node 'use strict'; // To aid in future maintenance, this layout closely matches remark-cli/cli.js.