[Pkg-javascript-commits] [node-browserify-zlib] 01/33: Initial commit
Bastien Roucariès
rouca at moszumanska.debian.org
Fri Apr 14 16:24:29 UTC 2017
This is an automated email from the git hooks/post-receive script.
rouca pushed a commit to branch master
in repository node-browserify-zlib.
commit 2b2ef87b58c8d69148d05979257043aec46757e9
Author: Devon Govett <devongovett at gmail.com>
Date: Mon Apr 7 22:47:54 2014 -0700
Initial commit
---
.gitignore | 2 +
README.md | 9 +
package.json | 40 ++
src/binding.js | 233 ++++++++++++
src/index.js | 610 ++++++++++++++++++++++++++++++
test/fixtures/elipses.txt | 1 +
test/fixtures/empty.txt | 1 +
test/fixtures/person.jpg | Bin 0 -> 57928 bytes
test/ignored/test-zlib-dictionary-fail.js | 48 +++
test/ignored/test-zlib-dictionary.js | 95 +++++
test/ignored/test-zlib-params.js | 33 ++
test/test-zlib-close-after-write.js | 35 ++
test/test-zlib-convenience-methods.js | 70 ++++
test/test-zlib-from-string.js | 89 +++++
test/test-zlib-invalid-input.js | 62 +++
test/test-zlib-random-byte-pipes.js | 178 +++++++++
test/test-zlib-write-after-flush.js | 55 +++
test/test-zlib-zero-byte.js | 41 ++
test/test-zlib.js | 206 ++++++++++
19 files changed, 1808 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2752eb9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+node_modules/
+.DS_Store
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ca50b47
--- /dev/null
+++ b/README.md
@@ -0,0 +1,9 @@
+# browserify-zlib
+
+Emulates Node's [zlib](http://nodejs.org/api/zlib.html) module for [Browserify](http://browserify.org)
+using [pako](https://github.com/nodeca/pako). It uses the actual Node source code and passes the Node zlib tests
+by emulating the C++ binding that actually calls zlib.
+
+## License
+
+MIT
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..397dc72
--- /dev/null
+++ b/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "browserify-zlib",
+ "version": "0.1.0",
+ "description": "Full zlib module for browserify",
+ "main": "index.js",
+ "directories": {
+ "test": "test"
+ },
+ "dependencies": {
+ "pako": "~0.1.1"
+ },
+ "devDependencies": {
+ "tape": "^2.12.3",
+ "brfs": "^1.0.1"
+ },
+ "testling": {
+ "files": "test/*.js",
+ "browsers": [
+ "ie/6..latest",
+ "chrome/22..latest",
+ "firefox/16..latest",
+ "safari/latest",
+ "opera/11.0..latest",
+ "iphone/6",
+ "ipad/6",
+ "android-browser/latest"
+ ]
+ },
+ "browserify": {
+ "transform": [
+ "brfs"
+ ]
+ },
+ "scripts": {
+ "test": "node_modules/tape/bin/tape test/*.js"
+ },
+ "main": "src/index.js",
+ "author": "Devon Govett <devongovett at gmail.com>",
+ "license": "MIT"
+}
diff --git a/src/binding.js b/src/binding.js
new file mode 100644
index 0000000..230ea5b
--- /dev/null
+++ b/src/binding.js
@@ -0,0 +1,233 @@
+var msg = require('pako/lib/zlib/messages');
+var zstream = require('pako/lib/zlib/zstream');
+var zlib_deflate = require('pako/lib/zlib/deflate.js');
+var zlib_inflate = require('pako/lib/zlib/inflate.js');
+var constants = require('pako/lib/zlib/constants');
+
+for (var key in constants) {
+ exports[key] = constants[key];
+}
+
+// zlib modes
+exports.NONE = 0;
+exports.DEFLATE = 1;
+exports.INFLATE = 2;
+exports.GZIP = 3;
+exports.GUNZIP = 4;
+exports.DEFLATERAW = 5;
+exports.INFLATERAW = 6;
+exports.UNZIP = 7;
+
+function Zlib(mode) {
+ if (mode < exports.DEFLATE || mode > exports.UNZIP)
+ throw new TypeError("Bad argument");
+
+ this.mode = mode;
+ this.init_done = false;
+ this.write_in_progress = false;
+ this.pending_close = false;
+ this.windowBits = 0;
+ this.level = 0;
+ this.memLevel = 0;
+ this.strategy = 0;
+ this.dictionary = null;
+}
+
+Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
+ this.windowBits = windowBits;
+ this.level = level;
+ this.memLevel = memLevel;
+ this.strategy = strategy;
+ // dictionary not supported.
+
+ if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
+ this.windowBits += 16;
+
+ if (this.mode === exports.UNZIP)
+ this.windowBits += 32;
+
+ if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
+ this.windowBits = -this.windowBits;
+
+ this.strm = new zstream();
+
+ switch (this.mode) {
+ case exports.DEFLATE:
+ case exports.GZIP:
+ case exports.DEFLATERAW:
+ var status = zlib_deflate.deflateInit2(
+ this.strm,
+ this.level,
+ exports.Z_DEFLATED,
+ this.windowBits,
+ this.memLevel,
+ this.strategy
+ );
+ break;
+ case exports.INFLATE:
+ case exports.GUNZIP:
+ case exports.INFLATERAW:
+ case exports.UNZIP:
+ var status = zlib_inflate.inflateInit2(
+ this.strm,
+ this.windowBits
+ );
+ break;
+ default:
+ throw new Error("Unknown mode " + this.mode);
+ }
+
+ if (status !== exports.Z_OK) {
+ this._error(status);
+ return;
+ }
+
+ this.write_in_progress = false;
+ this.init_done = true;
+};
+
+Zlib.prototype.params = function() {
+ throw new Error("deflateParams Not supported");
+};
+
+Zlib.prototype._writeCheck = function() {
+ if (!this.init_done)
+ throw new Error("write before init");
+
+ if (this.mode === exports.NONE)
+ throw new Error("already finalized");
+
+ if (this.write_in_progress)
+ throw new Error("write already in progress");
+
+ if (this.pending_close)
+ throw new Error("close is pending");
+};
+
+Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this._writeCheck();
+ this.write_in_progress = true;
+
+ var self = this;
+ process.nextTick(function() {
+ self.write_in_progress = false;
+ var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
+ self.callback(res[0], res[1]);
+
+ if (self.pending_close)
+ self.close();
+ });
+
+ return this;
+};
+
+// set method for Node buffers, used by pako
+function bufferSet(data, offset) {
+ for (var i = 0; i < data.length; i++) {
+ this[offset + i] = data[i];
+ }
+}
+
+Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this._writeCheck();
+ return this._write(flush, input, in_off, in_len, out, out_off, out_len);
+};
+
+Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this.write_in_progress = true;
+
+ if (flush !== exports.Z_NO_FLUSH &&
+ flush !== exports.Z_PARTIAL_FLUSH &&
+ flush !== exports.Z_SYNC_FLUSH &&
+ flush !== exports.Z_FULL_FLUSH &&
+ flush !== exports.Z_FINISH &&
+ flush !== exports.Z_BLOCK) {
+ throw new Error("Invalid flush value");
+ }
+
+ if (input == null) {
+ input = new Buffer(0);
+ in_len = 0;
+ in_off = 0;
+ }
+
+ if (out._set)
+ out.set = out._set;
+ else
+ out.set = bufferSet;
+
+ var strm = this.strm;
+ strm.avail_in = in_len;
+ strm.next_in = input;
+ strm.next_in_index = in_off;
+ strm.avail_out = out_len;
+ strm.next_out = out;
+ strm.next_out_index = out_off;
+
+ switch (this.mode) {
+ case exports.DEFLATE:
+ case exports.GZIP:
+ case exports.DEFLATERAW:
+ var status = zlib_deflate.deflate(strm, flush);
+ break;
+ case exports.UNZIP:
+ case exports.INFLATE:
+ case exports.GUNZIP:
+ case exports.INFLATERAW:
+ var status = zlib_inflate.inflate(strm, flush);
+ break;
+ default:
+ throw new Error("Unknown mode " + this.mode);
+ }
+
+ if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
+ this._error(status);
+ }
+
+ this.write_in_progress = false;
+ return [strm.avail_in, strm.avail_out];
+};
+
+Zlib.prototype.close = function() {
+ if (this.write_in_progress) {
+ this.pending_close = true;
+ return;
+ }
+
+ this.pending_close = false;
+
+ if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
+ zlib_deflate.deflateEnd(this.strm);
+ } else {
+ zlib_inflate.inflateEnd(this.strm);
+ }
+
+ this.mode = exports.NONE;
+};
+
+Zlib.prototype.reset = function() {
+ switch (this.mode) {
+ case DEFLATE:
+ case DEFLATERAW:
+ var status = zlib_deflate.deflateReset(this.strm);
+ break;
+ case INFLATE:
+ case INFLATERAW:
+ var status = zlib_inflate.inflateReset(this.strm);
+ break;
+ }
+
+ if (status !== exports.Z_OK) {
+ this._error(status);
+ }
+};
+
+Zlib.prototype._error = function(status) {
+ this.onerror(msg[status] + ': ' + this.strm.msg, status);
+
+ this.write_in_progress = false;
+ if (this.pending_close)
+ this.close();
+};
+
+exports.Zlib = Zlib;
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 0000000..032689c
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1,610 @@
+// 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 Transform = require('_stream_transform');
+
+var binding = require('./binding');
+var util = require('util');
+var assert = require('assert').ok;
+
+// zlib doesn't provide these, so kludge them in following the same
+// const naming scheme zlib uses.
+binding.Z_MIN_WINDOWBITS = 8;
+binding.Z_MAX_WINDOWBITS = 15;
+binding.Z_DEFAULT_WINDOWBITS = 15;
+
+// fewer than 64 bytes per chunk is stupid.
+// technically it could work with as few as 8, but even 64 bytes
+// is absurdly low. Usually a MB or more is best.
+binding.Z_MIN_CHUNK = 64;
+binding.Z_MAX_CHUNK = Infinity;
+binding.Z_DEFAULT_CHUNK = (16 * 1024);
+
+binding.Z_MIN_MEMLEVEL = 1;
+binding.Z_MAX_MEMLEVEL = 9;
+binding.Z_DEFAULT_MEMLEVEL = 8;
+
+binding.Z_MIN_LEVEL = -1;
+binding.Z_MAX_LEVEL = 9;
+binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
+
+// expose all the zlib constants
+Object.keys(binding).forEach(function(k) {
+ if (k.match(/^Z/)) exports[k] = binding[k];
+});
+
+// translation table for return codes.
+exports.codes = {
+ Z_OK: binding.Z_OK,
+ Z_STREAM_END: binding.Z_STREAM_END,
+ Z_NEED_DICT: binding.Z_NEED_DICT,
+ Z_ERRNO: binding.Z_ERRNO,
+ Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
+ Z_DATA_ERROR: binding.Z_DATA_ERROR,
+ Z_MEM_ERROR: binding.Z_MEM_ERROR,
+ Z_BUF_ERROR: binding.Z_BUF_ERROR,
+ Z_VERSION_ERROR: binding.Z_VERSION_ERROR
+};
+
+Object.keys(exports.codes).forEach(function(k) {
+ exports.codes[exports.codes[k]] = k;
+});
+
+exports.Deflate = Deflate;
+exports.Inflate = Inflate;
+exports.Gzip = Gzip;
+exports.Gunzip = Gunzip;
+exports.DeflateRaw = DeflateRaw;
+exports.InflateRaw = InflateRaw;
+exports.Unzip = Unzip;
+
+exports.createDeflate = function(o) {
+ return new Deflate(o);
+};
+
+exports.createInflate = function(o) {
+ return new Inflate(o);
+};
+
+exports.createDeflateRaw = function(o) {
+ return new DeflateRaw(o);
+};
+
+exports.createInflateRaw = function(o) {
+ return new InflateRaw(o);
+};
+
+exports.createGzip = function(o) {
+ return new Gzip(o);
+};
+
+exports.createGunzip = function(o) {
+ return new Gunzip(o);
+};
+
+exports.createUnzip = function(o) {
+ return new Unzip(o);
+};
+
+
+// Convenience methods.
+// compress/decompress a string or buffer in one step.
+exports.deflate = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Deflate(opts), buffer, callback);
+};
+
+exports.deflateSync = function(buffer, opts) {
+ return zlibBufferSync(new Deflate(opts), buffer);
+};
+
+exports.gzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Gzip(opts), buffer, callback);
+};
+
+exports.gzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Gzip(opts), buffer);
+};
+
+exports.deflateRaw = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new DeflateRaw(opts), buffer, callback);
+};
+
+exports.deflateRawSync = function(buffer, opts) {
+ return zlibBufferSync(new DeflateRaw(opts), buffer);
+};
+
+exports.unzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Unzip(opts), buffer, callback);
+};
+
+exports.unzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Unzip(opts), buffer);
+};
+
+exports.inflate = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Inflate(opts), buffer, callback);
+};
+
+exports.inflateSync = function(buffer, opts) {
+ return zlibBufferSync(new Inflate(opts), buffer);
+};
+
+exports.gunzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Gunzip(opts), buffer, callback);
+};
+
+exports.gunzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Gunzip(opts), buffer);
+};
+
+exports.inflateRaw = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new InflateRaw(opts), buffer, callback);
+};
+
+exports.inflateRawSync = function(buffer, opts) {
+ return zlibBufferSync(new InflateRaw(opts), buffer);
+};
+
+function zlibBuffer(engine, buffer, callback) {
+ var buffers = [];
+ var nread = 0;
+
+ engine.on('error', onError);
+ engine.on('end', onEnd);
+
+ engine.end(buffer);
+ flow();
+
+ function flow() {
+ var chunk;
+ while (null !== (chunk = engine.read())) {
+ buffers.push(chunk);
+ nread += chunk.length;
+ }
+ engine.once('readable', flow);
+ }
+
+ function onError(err) {
+ engine.removeListener('end', onEnd);
+ engine.removeListener('readable', flow);
+ callback(err);
+ }
+
+ function onEnd() {
+ var buf = Buffer.concat(buffers, nread);
+ buffers = [];
+ callback(null, buf);
+ engine.close();
+ }
+}
+
+function zlibBufferSync(engine, buffer) {
+ if (typeof buffer === 'string')
+ buffer = new Buffer(buffer);
+ if (!Buffer.isBuffer(buffer))
+ throw new TypeError('Not a string or buffer');
+
+ var flushFlag = binding.Z_FINISH;
+
+ return engine._processChunk(buffer, flushFlag);
+}
+
+// generic zlib
+// minimal 2-byte header
+function Deflate(opts) {
+ if (!(this instanceof Deflate)) return new Deflate(opts);
+ Zlib.call(this, opts, binding.DEFLATE);
+}
+
+function Inflate(opts) {
+ if (!(this instanceof Inflate)) return new Inflate(opts);
+ Zlib.call(this, opts, binding.INFLATE);
+}
+
+
+
+// gzip - bigger header, same deflate compression
+function Gzip(opts) {
+ if (!(this instanceof Gzip)) return new Gzip(opts);
+ Zlib.call(this, opts, binding.GZIP);
+}
+
+function Gunzip(opts) {
+ if (!(this instanceof Gunzip)) return new Gunzip(opts);
+ Zlib.call(this, opts, binding.GUNZIP);
+}
+
+
+
+// raw - no header
+function DeflateRaw(opts) {
+ if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
+ Zlib.call(this, opts, binding.DEFLATERAW);
+}
+
+function InflateRaw(opts) {
+ if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
+ Zlib.call(this, opts, binding.INFLATERAW);
+}
+
+
+// auto-detect header.
+function Unzip(opts) {
+ if (!(this instanceof Unzip)) return new Unzip(opts);
+ Zlib.call(this, opts, binding.UNZIP);
+}
+
+
+// the Zlib class they all inherit from
+// This thing manages the queue of requests, and returns
+// true or false if there is anything in the queue when
+// you call the .write() method.
+
+function Zlib(opts, mode) {
+ this._opts = opts = opts || {};
+ this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
+
+ Transform.call(this, opts);
+
+ if (opts.flush) {
+ if (opts.flush !== binding.Z_NO_FLUSH &&
+ opts.flush !== binding.Z_PARTIAL_FLUSH &&
+ opts.flush !== binding.Z_SYNC_FLUSH &&
+ opts.flush !== binding.Z_FULL_FLUSH &&
+ opts.flush !== binding.Z_FINISH &&
+ opts.flush !== binding.Z_BLOCK) {
+ throw new Error('Invalid flush flag: ' + opts.flush);
+ }
+ }
+ this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
+
+ if (opts.chunkSize) {
+ if (opts.chunkSize < exports.Z_MIN_CHUNK ||
+ opts.chunkSize > exports.Z_MAX_CHUNK) {
+ throw new Error('Invalid chunk size: ' + opts.chunkSize);
+ }
+ }
+
+ if (opts.windowBits) {
+ if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
+ opts.windowBits > exports.Z_MAX_WINDOWBITS) {
+ throw new Error('Invalid windowBits: ' + opts.windowBits);
+ }
+ }
+
+ if (opts.level) {
+ if (opts.level < exports.Z_MIN_LEVEL ||
+ opts.level > exports.Z_MAX_LEVEL) {
+ throw new Error('Invalid compression level: ' + opts.level);
+ }
+ }
+
+ if (opts.memLevel) {
+ if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
+ opts.memLevel > exports.Z_MAX_MEMLEVEL) {
+ throw new Error('Invalid memLevel: ' + opts.memLevel);
+ }
+ }
+
+ if (opts.strategy) {
+ if (opts.strategy != exports.Z_FILTERED &&
+ opts.strategy != exports.Z_HUFFMAN_ONLY &&
+ opts.strategy != exports.Z_RLE &&
+ opts.strategy != exports.Z_FIXED &&
+ opts.strategy != exports.Z_DEFAULT_STRATEGY) {
+ throw new Error('Invalid strategy: ' + opts.strategy);
+ }
+ }
+
+ if (opts.dictionary) {
+ if (!Buffer.isBuffer(opts.dictionary)) {
+ throw new Error('Invalid dictionary: it should be a Buffer instance');
+ }
+ }
+
+ this._binding = new binding.Zlib(mode);
+
+ var self = this;
+ this._hadError = false;
+ this._binding.onerror = function(message, errno) {
+ // there is no way to cleanly recover.
+ // continuing only obscures problems.
+ self._binding = null;
+ self._hadError = true;
+
+ var error = new Error(message);
+ error.errno = errno;
+ error.code = exports.codes[errno];
+ self.emit('error', error);
+ };
+
+ var level = exports.Z_DEFAULT_COMPRESSION;
+ if (typeof opts.level === 'number') level = opts.level;
+
+ var strategy = exports.Z_DEFAULT_STRATEGY;
+ if (typeof opts.strategy === 'number') strategy = opts.strategy;
+
+ this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
+ level,
+ opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
+ strategy,
+ opts.dictionary);
+
+ this._buffer = new Buffer(this._chunkSize);
+ this._offset = 0;
+ this._closed = false;
+ this._level = level;
+ this._strategy = strategy;
+
+ this.once('end', this.close);
+}
+
+util.inherits(Zlib, Transform);
+
+Zlib.prototype.params = function(level, strategy, callback) {
+ if (level < exports.Z_MIN_LEVEL ||
+ level > exports.Z_MAX_LEVEL) {
+ throw new RangeError('Invalid compression level: ' + level);
+ }
+ if (strategy != exports.Z_FILTERED &&
+ strategy != exports.Z_HUFFMAN_ONLY &&
+ strategy != exports.Z_RLE &&
+ strategy != exports.Z_FIXED &&
+ strategy != exports.Z_DEFAULT_STRATEGY) {
+ throw new TypeError('Invalid strategy: ' + strategy);
+ }
+
+ if (this._level !== level || this._strategy !== strategy) {
+ var self = this;
+ this.flush(binding.Z_SYNC_FLUSH, function() {
+ self._binding.params(level, strategy);
+ if (!self._hadError) {
+ self._level = level;
+ self._strategy = strategy;
+ if (callback) callback();
+ }
+ });
+ } else {
+ process.nextTick(callback);
+ }
+};
+
+Zlib.prototype.reset = function() {
+ return this._binding.reset();
+};
+
+// This is the _flush function called by the transform class,
+// internally, when the last chunk has been written.
+Zlib.prototype._flush = function(callback) {
+ this._transform(new Buffer(0), '', callback);
+};
+
+Zlib.prototype.flush = function(kind, callback) {
+ var ws = this._writableState;
+
+ if (typeof kind === 'function' || (kind === void 0 && !callback)) {
+ callback = kind;
+ kind = binding.Z_FULL_FLUSH;
+ }
+
+ if (ws.ended) {
+ if (callback)
+ process.nextTick(callback);
+ } else if (ws.ending) {
+ if (callback)
+ this.once('end', callback);
+ } else if (ws.needDrain) {
+ var self = this;
+ this.once('drain', function() {
+ self.flush(callback);
+ });
+ } else {
+ this._flushFlag = kind;
+ this.write(new Buffer(0), '', callback);
+ }
+};
+
+Zlib.prototype.close = function(callback) {
+ if (callback)
+ process.nextTick(callback);
+
+ if (this._closed)
+ return;
+
+ this._closed = true;
+
+ this._binding.close();
+
+ var self = this;
+ process.nextTick(function() {
+ self.emit('close');
+ });
+};
+
+Zlib.prototype._transform = function(chunk, encoding, cb) {
+ var flushFlag;
+ var ws = this._writableState;
+ var ending = ws.ending || ws.ended;
+ var last = ending && (!chunk || ws.length === chunk.length);
+
+ if (!chunk === null && !Buffer.isBuffer(chunk))
+ return cb(new Error('invalid input'));
+
+ // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
+ // If it's explicitly flushing at some other time, then we use
+ // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
+ // goodness.
+ if (last)
+ flushFlag = binding.Z_FINISH;
+ else {
+ flushFlag = this._flushFlag;
+ // once we've flushed the last of the queue, stop flushing and
+ // go back to the normal behavior.
+ if (chunk.length >= ws.length) {
+ this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
+ }
+ }
+
+ var self = this;
+ this._processChunk(chunk, flushFlag, cb);
+};
+
+Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
+ var availInBefore = chunk && chunk.length;
+ var availOutBefore = this._chunkSize - this._offset;
+ var inOff = 0;
+
+ var self = this;
+
+ var async = typeof cb === 'function';
+
+ if (!async) {
+ var buffers = [];
+ var nread = 0;
+
+ var error;
+ this.on('error', function(er) {
+ error = er;
+ });
+
+ do {
+ var res = this._binding.writeSync(flushFlag,
+ chunk, // in
+ inOff, // in_off
+ availInBefore, // in_len
+ this._buffer, // out
+ this._offset, //out_off
+ availOutBefore); // out_len
+ } while (!this._hadError && callback(res[0], res[1]));
+
+ if (this._hadError) {
+ throw error;
+ }
+
+ var buf = Buffer.concat(buffers, nread);
+ this.close();
+
+ return buf;
+ }
+
+ var req = this._binding.write(flushFlag,
+ chunk, // in
+ inOff, // in_off
+ availInBefore, // in_len
+ this._buffer, // out
+ this._offset, //out_off
+ availOutBefore); // out_len
+
+ req.buffer = chunk;
+ req.callback = callback;
+
+ function callback(availInAfter, availOutAfter) {
+ if (self._hadError)
+ return;
+
+ var have = availOutBefore - availOutAfter;
+ assert(have >= 0, 'have should not go down');
+
+ if (have > 0) {
+ var out = self._buffer.slice(self._offset, self._offset + have);
+ self._offset += have;
+ // serve some output to the consumer.
+ if (async) {
+ self.push(out);
+ } else {
+ buffers.push(out);
+ nread += out.length;
+ }
+ }
+
+ // exhausted the output buffer, or used all the input create a new one.
+ if (availOutAfter === 0 || self._offset >= self._chunkSize) {
+ availOutBefore = self._chunkSize;
+ self._offset = 0;
+ self._buffer = new Buffer(self._chunkSize);
+ }
+
+ if (availOutAfter === 0) {
+ // Not actually done. Need to reprocess.
+ // Also, update the availInBefore to the availInAfter value,
+ // so that if we have to hit it a third (fourth, etc.) time,
+ // it'll have the correct byte counts.
+ inOff += (availInBefore - availInAfter);
+ availInBefore = availInAfter;
+
+ if (!async)
+ return true;
+
+ var newReq = self._binding.write(flushFlag,
+ chunk,
+ inOff,
+ availInBefore,
+ self._buffer,
+ self._offset,
+ self._chunkSize);
+ newReq.callback = callback; // this same function
+ newReq.buffer = chunk;
+ return;
+ }
+
+ if (!async)
+ return false;
+
+ // finished with the chunk.
+ cb();
+ }
+};
+
+util.inherits(Deflate, Zlib);
+util.inherits(Inflate, Zlib);
+util.inherits(Gzip, Zlib);
+util.inherits(Gunzip, Zlib);
+util.inherits(DeflateRaw, Zlib);
+util.inherits(InflateRaw, Zlib);
+util.inherits(Unzip, Zlib);
diff --git a/test/fixtures/elipses.txt b/test/fixtures/elipses.txt
new file mode 100644
index 0000000..6105600
--- /dev/null
+++ b/test/fixtures/elipses.txt
@@ -0,0 +1 @@
+……………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… [...]
\ No newline at end of file
diff --git a/test/fixtures/empty.txt b/test/fixtures/empty.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/test/fixtures/empty.txt
@@ -0,0 +1 @@
+
diff --git a/test/fixtures/person.jpg b/test/fixtures/person.jpg
new file mode 100644
index 0000000..4f71881
Binary files /dev/null and b/test/fixtures/person.jpg differ
diff --git a/test/ignored/test-zlib-dictionary-fail.js b/test/ignored/test-zlib-dictionary-fail.js
new file mode 100755
index 0000000..fd35a01
--- /dev/null
+++ b/test/ignored/test-zlib-dictionary-fail.js
@@ -0,0 +1,48 @@
+// 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 common = require('../common.js');
+var assert = require('assert');
+var zlib = require('zlib');
+
+// Should raise an error, not trigger an assertion in src/node_zlib.cc
+(function() {
+ var stream = zlib.createInflate();
+
+ stream.on('error', common.mustCall(function(err) {
+ assert(/Missing dictionary/.test(err.message));
+ }));
+
+ // String "test" encoded with dictionary "dict".
+ stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5]));
+})();
+
+// Should raise an error, not trigger an assertion in src/node_zlib.cc
+(function() {
+ var stream = zlib.createInflate({ dictionary: Buffer('fail') });
+
+ stream.on('error', common.mustCall(function(err) {
+ assert(/Bad dictionary/.test(err.message));
+ }));
+
+ // String "test" encoded with dictionary "dict".
+ stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5]));
+})();
diff --git a/test/ignored/test-zlib-dictionary.js b/test/ignored/test-zlib-dictionary.js
new file mode 100755
index 0000000..58da810
--- /dev/null
+++ b/test/ignored/test-zlib-dictionary.js
@@ -0,0 +1,95 @@
+// 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.
+
+// test compression/decompression with dictionary
+
+var common = require('../common.js');
+var assert = require('assert');
+var zlib = require('zlib');
+var path = require('path');
+
+var spdyDict = new Buffer([
+ 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-',
+ 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi',
+ 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser',
+ '-agent10010120020120220320420520630030130230330430530630740040140240340440',
+ '5406407408409410411412413414415416417500501502503504505accept-rangesageeta',
+ 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic',
+ 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran',
+ 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati',
+ 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo',
+ 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe',
+ 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic',
+ 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1',
+ '.1statusversionurl\0'
+].join(''));
+
+var deflate = zlib.createDeflate({ dictionary: spdyDict });
+
+var input = [
+ 'HTTP/1.1 200 Ok',
+ 'Server: node.js',
+ 'Content-Length: 0',
+ ''
+].join('\r\n');
+
+var called = 0;
+
+//
+// We'll use clean-new inflate stream each time
+// and .reset() old dirty deflate one
+//
+function run(num) {
+ var inflate = zlib.createInflate({ dictionary: spdyDict });
+
+ if (num === 2) {
+ deflate.reset();
+ deflate.removeAllListeners('data');
+ }
+
+ // Put data into deflate stream
+ deflate.on('data', function(chunk) {
+ inflate.write(chunk);
+ });
+
+ // Get data from inflate stream
+ var output = [];
+ inflate.on('data', function(chunk) {
+ output.push(chunk);
+ });
+ inflate.on('end', function() {
+ called++;
+
+ assert.equal(output.join(''), input);
+
+ if (num < 2) run(num + 1);
+ });
+
+ deflate.write(input);
+ deflate.flush(function() {
+ inflate.end();
+ });
+}
+run(1);
+
+process.on('exit', function() {
+ assert.equal(called, 2);
+});
diff --git a/test/ignored/test-zlib-params.js b/test/ignored/test-zlib-params.js
new file mode 100755
index 0000000..006f1ea
--- /dev/null
+++ b/test/ignored/test-zlib-params.js
@@ -0,0 +1,33 @@
+var common = require('../common.js');
+var assert = require('assert');
+var zlib = require('zlib');
+var path = require('path');
+var fs = require('fs');
+
+var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')),
+ chunkSize = 24 * 1024,
+ opts = { level: 9, strategy: zlib.Z_DEFAULT_STRATEGY },
+ deflater = zlib.createDeflate(opts);
+
+var chunk1 = file.slice(0, chunkSize),
+ chunk2 = file.slice(chunkSize),
+ blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]),
+ expected = Buffer.concat([blkhdr, chunk2]),
+ actual;
+
+deflater.write(chunk1, function() {
+ deflater.params(0, zlib.Z_DEFAULT_STRATEGY, function() {
+ while (deflater.read());
+ deflater.end(chunk2, function() {
+ var bufs = [], buf;
+ while (buf = deflater.read())
+ bufs.push(buf);
+ actual = Buffer.concat(bufs);
+ });
+ });
+ while (deflater.read());
+});
+
+process.once('exit', function() {
+ assert.deepEqual(actual, expected);
+});
diff --git a/test/test-zlib-close-after-write.js b/test/test-zlib-close-after-write.js
new file mode 100755
index 0000000..6d5a083
--- /dev/null
+++ b/test/test-zlib-close-after-write.js
@@ -0,0 +1,35 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+
+tape(function(t) {
+ t.plan(1);
+
+ zlib.gzip('hello', function(err, out) {
+ var unzip = zlib.createGunzip();
+ unzip.write(out);
+ unzip.close(function() {
+ t.ok(true);
+ });
+ });
+});
diff --git a/test/test-zlib-convenience-methods.js b/test/test-zlib-convenience-methods.js
new file mode 100755
index 0000000..223160b
--- /dev/null
+++ b/test/test-zlib-convenience-methods.js
@@ -0,0 +1,70 @@
+// 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.
+
+// test convenience methods with and without options supplied
+
+var tape = require('tape');
+var zlib = require('../');
+
+var expect = 'blahblahblahblahblahblah';
+var opts = {
+ level: 9,
+ chunkSize: 1024,
+};
+
+[
+ ['gzip', 'gunzip'],
+ ['gzip', 'unzip'],
+ ['deflate', 'inflate'],
+ ['deflateRaw', 'inflateRaw'],
+].forEach(function(method) {
+ tape(method.join(' '), function(t) {
+ t.plan(4);
+
+ zlib[method[0]](expect, opts, function(err, result) {
+ zlib[method[1]](result, opts, function(err, result) {
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' with options.');
+ });
+ });
+
+ zlib[method[0]](expect, function(err, result) {
+ zlib[method[1]](result, function(err, result) {
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' without options.');
+ });
+ });
+
+ var result = zlib[method[0] + 'Sync'](expect, opts);
+ result = zlib[method[1] + 'Sync'](result, opts);
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' with options.');
+
+ result = zlib[method[0] + 'Sync'](expect);
+ result = zlib[method[1] + 'Sync'](result);
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' without options.');
+ });
+});
diff --git a/test/test-zlib-from-string.js b/test/test-zlib-from-string.js
new file mode 100755
index 0000000..5394c53
--- /dev/null
+++ b/test/test-zlib-from-string.js
@@ -0,0 +1,89 @@
+// 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.
+
+// test compressing and uncompressing a string with zlib
+
+var tape = require('tape');
+var zlib = require('../');
+
+var inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el' +
+ 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' +
+ 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' +
+ ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' +
+ 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' +
+ 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' +
+ 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' +
+ 'cu malesuada fermentum. Nunc sed. ';
+var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' +
+ 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' +
+ 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' +
+ 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' +
+ 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' +
+ 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9';
+var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' +
+ '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' +
+ 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' +
+ 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' +
+ 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' +
+ 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' +
+ 'HnHNzRtagj5AQAA';
+
+tape('deflate', function(t) {
+ t.plan(1);
+ zlib.deflate(inputString, function(err, buffer) {
+ t.equal(buffer.toString('base64'), expectedBase64Deflate,
+ 'deflate encoded string should match');
+ });
+});
+
+tape('gzip', function(t) {
+ t.plan(1);
+ zlib.gzip(inputString, function(err, buffer) {
+ // Can't actually guarantee that we'll get exactly the same
+ // deflated bytes when we compress a string, since the header
+ // depends on stuff other than the input string itself.
+ // However, decrypting it should definitely yield the same
+ // result that we're expecting, and this should match what we get
+ // from inflating the known valid deflate data.
+ zlib.gunzip(buffer, function(err, gunzipped) {
+ t.equal(gunzipped.toString(), inputString,
+ 'Should get original string after gzip/gunzip');
+ });
+ });
+});
+
+tape('unzip deflate', function(t) {
+ t.plan(1);
+ var buffer = new Buffer(expectedBase64Deflate, 'base64');
+ zlib.unzip(buffer, function(err, buffer) {
+ t.equal(buffer.toString(), inputString,
+ 'decoded inflated string should match');
+ });
+});
+
+tape('unzip gzip', function(t) {
+ t.plan(1);
+ buffer = new Buffer(expectedBase64Gzip, 'base64');
+ zlib.unzip(buffer, function(err, buffer) {
+ t.equal(buffer.toString(), inputString,
+ 'decoded gunzipped string should match');
+ });
+});
diff --git a/test/test-zlib-invalid-input.js b/test/test-zlib-invalid-input.js
new file mode 100755
index 0000000..5ac08c3
--- /dev/null
+++ b/test/test-zlib-invalid-input.js
@@ -0,0 +1,62 @@
+// 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.
+
+// test uncompressing invalid input
+
+var tape = require('tape'),
+ zlib = require('../');
+
+tape('non-strings', function(t) {
+ var nonStringInputs = [1, true, {a: 1}, ['a']];
+ t.plan(12);
+
+ nonStringInputs.forEach(function(input) {
+ // zlib.gunzip should not throw an error when called with bad input.
+ t.doesNotThrow(function() {
+ zlib.gunzip(input, function(err, buffer) {
+ // zlib.gunzip should pass the error to the callback.
+ t.ok(err);
+ });
+ });
+ });
+});
+
+tape('unzips', function(t) {
+ // zlib.Unzip classes need to get valid data, or else they'll throw.
+ var unzips = [ zlib.Unzip(),
+ zlib.Gunzip(),
+ zlib.Inflate(),
+ zlib.InflateRaw() ];
+
+ t.plan(4);
+ unzips.forEach(function (uz, i) {
+ uz.on('error', function(er) {
+ t.ok(er);
+ });
+
+ uz.on('end', function(er) {
+ throw new Error('end event should not be emitted '+uz.constructor.name);
+ });
+
+ // this will trigger error event
+ uz.write('this is not valid compressed data.');
+ });
+});
diff --git a/test/test-zlib-random-byte-pipes.js b/test/test-zlib-random-byte-pipes.js
new file mode 100755
index 0000000..6b51107
--- /dev/null
+++ b/test/test-zlib-random-byte-pipes.js
@@ -0,0 +1,178 @@
+// 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 crypto = require('crypto');
+var stream = require('stream');
+var Stream = stream.Stream;
+var util = require('util');
+var tape = require('tape');
+var zlib = require('../');
+
+
+
+// emit random bytes, and keep a shasum
+function RandomReadStream(opt) {
+ Stream.call(this);
+
+ this.readable = true;
+ this._paused = false;
+ this._processing = false;
+
+ this._hasher = crypto.createHash('sha1');
+ opt = opt || {};
+
+ // base block size.
+ opt.block = opt.block || 256 * 1024;
+
+ // total number of bytes to emit
+ opt.total = opt.total || 256 * 1024 * 1024;
+ this._remaining = opt.total;
+
+ // how variable to make the block sizes
+ opt.jitter = opt.jitter || 1024;
+
+ this._opt = opt;
+
+ this._process = this._process.bind(this);
+
+ process.nextTick(this._process);
+}
+
+util.inherits(RandomReadStream, Stream);
+
+RandomReadStream.prototype.pause = function() {
+ this._paused = true;
+ this.emit('pause');
+};
+
+RandomReadStream.prototype.resume = function() {
+ // console.error("rrs resume");
+ this._paused = false;
+ this.emit('resume');
+ this._process();
+};
+
+RandomReadStream.prototype._process = function() {
+ if (this._processing) return;
+ if (this._paused) return;
+
+ this._processing = true;
+
+ if (!this._remaining) {
+ this._hash = this._hasher.digest('hex').toLowerCase().trim();
+ this._processing = false;
+
+ this.emit('end');
+ return;
+ }
+
+ // figure out how many bytes to output
+ // if finished, then just emit end.
+ var block = this._opt.block;
+ var jitter = this._opt.jitter;
+ if (jitter) {
+ block += Math.ceil(Math.random() * jitter - (jitter / 2));
+ }
+ block = Math.min(block, this._remaining);
+ var buf = new Buffer(block);
+ for (var i = 0; i < block; i++) {
+ buf[i] = Math.random() * 256;
+ }
+
+ this._hasher.update(buf);
+
+ this._remaining -= block;
+
+ console.error('block=%d\nremain=%d\n', block, this._remaining);
+ this._processing = false;
+
+ this.emit('data', buf);
+ process.nextTick(this._process);
+};
+
+
+// a filter that just verifies a shasum
+function HashStream() {
+ Stream.call(this);
+
+ this.readable = this.writable = true;
+ this._hasher = crypto.createHash('sha1');
+}
+
+util.inherits(HashStream, Stream);
+
+HashStream.prototype.write = function(c) {
+ // Simulate the way that an fs.ReadStream returns false
+ // on *every* write like a jerk, only to resume a
+ // moment later.
+ this._hasher.update(c);
+ process.nextTick(this.resume.bind(this));
+ return false;
+};
+
+HashStream.prototype.resume = function() {
+ this.emit('resume');
+ process.nextTick(this.emit.bind(this, 'drain'));
+};
+
+HashStream.prototype.end = function(c) {
+ if (c) {
+ this.write(c);
+ }
+ this._hash = this._hasher.digest('hex').toLowerCase().trim();
+ this.emit('data', this._hash);
+ this.emit('end');
+};
+
+tape('random byte pipes', function(t) {
+ var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 });
+ var out = new HashStream();
+ var gzip = zlib.createGzip();
+ var gunz = zlib.createGunzip();
+
+ inp.pipe(gzip).pipe(gunz).pipe(out);
+
+ inp.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ gzip.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ gunz.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ out.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ out.on('data', function(c) {
+ t.ok(c.length);
+ t.equal(c, inp._hash, 'hashes should match');
+ });
+
+ out.on('end', function() {
+ t.end();
+ })
+});
+
diff --git a/test/test-zlib-write-after-flush.js b/test/test-zlib-write-after-flush.js
new file mode 100755
index 0000000..5841ef8
--- /dev/null
+++ b/test/test-zlib-write-after-flush.js
@@ -0,0 +1,55 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+var fs = require('fs');
+
+tape('write after flush', function(t) {
+ t.plan(2);
+
+ var gzip = zlib.createGzip();
+ var gunz = zlib.createUnzip();
+
+ gzip.pipe(gunz);
+
+ var output = '';
+ var input = 'A line of data\n';
+ gunz.setEncoding('utf8');
+ gunz.on('data', function(c) {
+ output += c;
+ });
+
+ gunz.on('end', function() {
+ t.equal(output, input);
+
+ // Make sure that the flush flag was set back to normal
+ t.equal(gzip._flushFlag, zlib.Z_NO_FLUSH);
+ });
+
+ // make sure that flush/write doesn't trigger an assert failure
+ gzip.flush(); write();
+ function write() {
+ gzip.write(input);
+ gzip.end();
+ gunz.read(0);
+ }
+});
diff --git a/test/test-zlib-zero-byte.js b/test/test-zlib-zero-byte.js
new file mode 100755
index 0000000..88bdd8c
--- /dev/null
+++ b/test/test-zlib-zero-byte.js
@@ -0,0 +1,41 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+
+tape('zero byte', function(t) {
+ t.plan(2);
+ var gz = zlib.Gzip()
+ var emptyBuffer = new Buffer(0);
+ var received = 0;
+ gz.on('data', function(c) {
+ received += c.length;
+ });
+ gz.on('end', function() {
+ t.equal(received, 20);
+ });
+ gz.on('finish', function() {
+ t.ok(true);
+ });
+ gz.write(emptyBuffer);
+ gz.end();
+});
diff --git a/test/test-zlib.js b/test/test-zlib.js
new file mode 100644
index 0000000..dcb9e68
--- /dev/null
+++ b/test/test-zlib.js
@@ -0,0 +1,206 @@
+// 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 assert = require('assert');
+var zlib = require('../');
+var path = require('path');
+
+var zlibPairs =
+ [[zlib.Deflate, zlib.Inflate],
+ [zlib.Gzip, zlib.Gunzip],
+ [zlib.Deflate, zlib.Unzip],
+ [zlib.Gzip, zlib.Unzip],
+ [zlib.DeflateRaw, zlib.InflateRaw]];
+
+// how fast to trickle through the slowstream
+var trickle = [128, 1024, 1024 * 1024];
+
+// tunable options for zlib classes.
+
+// several different chunk sizes
+var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024];
+
+// this is every possible value.
+var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+var windowBits = [8, 9, 10, 11, 12, 13, 14, 15];
+var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9];
+var strategy = [0, 1, 2, 3, 4];
+
+// it's nice in theory to test every combination, but it
+// takes WAY too long. Maybe a pummel test could do this?
+if (!process.env.PUMMEL) {
+ trickle = [1024];
+ chunkSize = [1024 * 16];
+ level = [6];
+ memLevel = [8];
+ windowBits = [15];
+ strategy = [0];
+}
+
+var fs = require('fs');
+
+if (process.env.FAST) {
+ zlibPairs = [[zlib.Gzip, zlib.Unzip]];
+}
+
+var tests = {
+ 'peron.jpg': fs.readFileSync(__dirname + '/fixtures/person.jpg'),
+ 'elipses.txt': fs.readFileSync(__dirname + '/fixtures/elipses.txt'),
+ 'empty.txt': fs.readFileSync(__dirname + '/fixtures/empty.txt')
+};
+
+var util = require('util');
+var stream = require('stream');
+
+
+// stream that saves everything
+function BufferStream() {
+ this.chunks = [];
+ this.length = 0;
+ this.writable = true;
+ this.readable = true;
+}
+
+util.inherits(BufferStream, stream.Stream);
+
+BufferStream.prototype.write = function(c) {
+ this.chunks.push(c);
+ this.length += c.length;
+ return true;
+};
+
+BufferStream.prototype.end = function(c) {
+ if (c) this.write(c);
+ // flatten
+ var buf = new Buffer(this.length);
+ var i = 0;
+ this.chunks.forEach(function(c) {
+ c.copy(buf, i);
+ i += c.length;
+ });
+ this.emit('data', buf);
+ this.emit('end');
+ return true;
+};
+
+
+function SlowStream(trickle) {
+ this.trickle = trickle;
+ this.offset = 0;
+ this.readable = this.writable = true;
+}
+
+util.inherits(SlowStream, stream.Stream);
+
+SlowStream.prototype.write = function() {
+ throw new Error('not implemented, just call ss.end(chunk)');
+};
+
+SlowStream.prototype.pause = function() {
+ this.paused = true;
+ this.emit('pause');
+};
+
+SlowStream.prototype.resume = function() {
+ var self = this;
+ if (self.ended) return;
+ self.emit('resume');
+ if (!self.chunk) return;
+ self.paused = false;
+ emit();
+ function emit() {
+ if (self.paused) return;
+ if (self.offset >= self.length) {
+ self.ended = true;
+ return self.emit('end');
+ }
+ var end = Math.min(self.offset + self.trickle, self.length);
+ var c = self.chunk.slice(self.offset, end);
+ self.offset += c.length;
+ self.emit('data', c);
+ process.nextTick(emit);
+ }
+};
+
+SlowStream.prototype.end = function(chunk) {
+ // walk over the chunk in blocks.
+ var self = this;
+ self.chunk = chunk;
+ self.length = chunk.length;
+ self.resume();
+ return self.ended;
+};
+
+
+
+// for each of the files, make sure that compressing and
+// decompressing results in the same data, for every combination
+// of the options set above.
+var tape = require('tape');
+
+Object.keys(tests).forEach(function(file) {
+ var test = tests[file];
+ chunkSize.forEach(function(chunkSize) {
+ trickle.forEach(function(trickle) {
+ windowBits.forEach(function(windowBits) {
+ level.forEach(function(level) {
+ memLevel.forEach(function(memLevel) {
+ strategy.forEach(function(strategy) {
+ zlibPairs.forEach(function(pair) {
+ var Def = pair[0];
+ var Inf = pair[1];
+ var opts = {
+ level: level,
+ windowBits: windowBits,
+ memLevel: memLevel,
+ strategy: strategy
+ };
+
+ var msg = file + ' ' +
+ chunkSize + ' ' +
+ JSON.stringify(opts) + ' ' +
+ Def.name + ' -> ' + Inf.name;
+
+ tape('zlib ' + msg, function(t) {
+ t.plan(1);
+
+ var def = new Def(opts);
+ var inf = new Inf(opts);
+ var ss = new SlowStream(trickle);
+ var buf = new BufferStream();
+
+ // verify that the same exact buffer comes out the other end.
+ buf.on('data', function(c) {
+ t.deepEqual(c, test);
+ });
+
+ // the magic happens here.
+ ss.pipe(def).pipe(inf).pipe(buf);
+ ss.end(test);
+ });
+ });
+ });
+ });
+ });
+ });
+ });
+ });
+});
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-browserify-zlib.git
More information about the Pkg-javascript-commits
mailing list