node/lib/zlib.js

587 lines
16 KiB
JavaScript
Raw Normal View History

2011-09-06 23:13:05 +00:00
// 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.
2012-10-02 23:15:39 +00:00
var Transform = require('_stream_transform');
2011-09-06 23:13:05 +00:00
var binding = process.binding('zlib');
var util = require('util');
var assert = require('assert').ok;
2011-09-06 23:13:05 +00:00
// 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;
});
2011-09-06 23:13:05 +00:00
exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;
2011-09-18 06:03:36 +00:00
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);
};
2011-09-06 23:13:05 +00:00
// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new Deflate(opts), buffer, callback);
};
exports.gzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new Gzip(opts), buffer, callback);
};
exports.deflateRaw = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};
exports.unzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new Unzip(opts), buffer, callback);
};
exports.inflate = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new Inflate(opts), buffer, callback);
};
exports.gunzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new Gunzip(opts), buffer, callback);
};
exports.inflateRaw = function(buffer, opts, callback) {
if (util.isFunction(opts)) {
callback = opts;
opts = {};
}
return zlibBuffer(new InflateRaw(opts), buffer, callback);
};
function zlibBuffer(engine, buffer, callback) {
if (!util.isFunction(callback)) {
return zlibBufferSync(engine, buffer, callback);
}
var buffers = [];
var nread = 0;
2012-10-02 23:15:39 +00:00
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);
2012-10-02 23:15:39 +00:00
engine.removeListener('readable', flow);
callback(err);
}
function onEnd() {
var buf = Buffer.concat(buffers, nread);
buffers = [];
callback(null, buf);
Merge remote-tracking branch 'ry/v0.8' into master Conflicts: AUTHORS ChangeLog deps/npm/html/api/bin.html deps/npm/html/api/bugs.html deps/npm/html/api/commands.html deps/npm/html/api/config.html deps/npm/html/api/deprecate.html deps/npm/html/api/docs.html deps/npm/html/api/edit.html deps/npm/html/api/explore.html deps/npm/html/api/help-search.html deps/npm/html/api/init.html deps/npm/html/api/install.html deps/npm/html/api/link.html deps/npm/html/api/load.html deps/npm/html/api/ls.html deps/npm/html/api/npm.html deps/npm/html/api/outdated.html deps/npm/html/api/owner.html deps/npm/html/api/pack.html deps/npm/html/api/prefix.html deps/npm/html/api/prune.html deps/npm/html/api/publish.html deps/npm/html/api/rebuild.html deps/npm/html/api/restart.html deps/npm/html/api/root.html deps/npm/html/api/run-script.html deps/npm/html/api/search.html deps/npm/html/api/shrinkwrap.html deps/npm/html/api/start.html deps/npm/html/api/stop.html deps/npm/html/api/submodule.html deps/npm/html/api/tag.html deps/npm/html/api/test.html deps/npm/html/api/uninstall.html deps/npm/html/api/unpublish.html deps/npm/html/api/update.html deps/npm/html/api/version.html deps/npm/html/api/view.html deps/npm/html/api/whoami.html deps/npm/html/doc/README.html deps/npm/html/doc/adduser.html deps/npm/html/doc/bin.html deps/npm/html/doc/bugs.html deps/npm/html/doc/build.html deps/npm/html/doc/bundle.html deps/npm/html/doc/cache.html deps/npm/html/doc/changelog.html deps/npm/html/doc/coding-style.html deps/npm/html/doc/completion.html deps/npm/html/doc/config.html deps/npm/html/doc/dedupe.html deps/npm/html/doc/deprecate.html deps/npm/html/doc/developers.html deps/npm/html/doc/disputes.html deps/npm/html/doc/docs.html deps/npm/html/doc/edit.html deps/npm/html/doc/explore.html deps/npm/html/doc/faq.html deps/npm/html/doc/folders.html deps/npm/html/doc/global.html deps/npm/html/doc/help-search.html deps/npm/html/doc/help.html deps/npm/html/doc/index.html deps/npm/html/doc/init.html deps/npm/html/doc/install.html deps/npm/html/doc/json.html deps/npm/html/doc/link.html deps/npm/html/doc/ls.html deps/npm/html/doc/npm.html deps/npm/html/doc/outdated.html deps/npm/html/doc/owner.html deps/npm/html/doc/pack.html deps/npm/html/doc/prefix.html deps/npm/html/doc/prune.html deps/npm/html/doc/publish.html deps/npm/html/doc/rebuild.html deps/npm/html/doc/registry.html deps/npm/html/doc/removing-npm.html deps/npm/html/doc/restart.html deps/npm/html/doc/rm.html deps/npm/html/doc/root.html deps/npm/html/doc/run-script.html deps/npm/html/doc/scripts.html deps/npm/html/doc/search.html deps/npm/html/doc/semver.html deps/npm/html/doc/shrinkwrap.html deps/npm/html/doc/star.html deps/npm/html/doc/start.html deps/npm/html/doc/stop.html deps/npm/html/doc/submodule.html deps/npm/html/doc/tag.html deps/npm/html/doc/test.html deps/npm/html/doc/uninstall.html deps/npm/html/doc/unpublish.html deps/npm/html/doc/update.html deps/npm/html/doc/version.html deps/npm/html/doc/view.html deps/npm/html/doc/whoami.html deps/npm/man/man1/global.1 deps/npm/man/man1/ls.1 deps/npm/man/man1/npm.1 deps/npm/man/man1/rm.1 deps/npm/man/man3/npm.3 deps/npm/node_modules/glob/glob.js deps/npm/node_modules/glob/package.json deps/npm/node_modules/node-gyp/package.json deps/npm/node_modules/npm-registry-client/package.json deps/npm/node_modules/npmconf/package.json deps/npm/node_modules/read-installed/package.json deps/npm/node_modules/rimraf/package.json deps/npm/node_modules/rimraf/rimraf.js deps/npm/package.json deps/uv/src/win/error.c doc/api/crypto.markdown lib/zlib.js src/node_version.h src/node_zlib.cc test/simple/test-buffer.js
2013-02-07 00:29:30 +00:00
engine.close();
}
}
function zlibBufferSync(engine, buffer, callback) {
if (util.isString(buffer))
buffer = new Buffer(buffer);
if (!util.isBuffer(buffer))
throw new TypeError('Not a string or buffer');
var flushFlag = binding.Z_FINISH;
return engine._processChunk(buffer, flushFlag);
}
2011-09-06 23:13:05 +00:00
// generic zlib
// minimal 2-byte header
function Deflate(opts) {
2011-09-26 18:50:20 +00:00
if (!(this instanceof Deflate)) return new Deflate(opts);
Zlib.call(this, opts, binding.DEFLATE);
2011-09-06 23:13:05 +00:00
}
function Inflate(opts) {
if (!(this instanceof Inflate)) return new Inflate(opts);
Zlib.call(this, opts, binding.INFLATE);
2011-09-06 23:13:05 +00:00
}
// gzip - bigger header, same deflate compression
function Gzip(opts) {
if (!(this instanceof Gzip)) return new Gzip(opts);
Zlib.call(this, opts, binding.GZIP);
2011-09-06 23:13:05 +00:00
}
function Gunzip(opts) {
if (!(this instanceof Gunzip)) return new Gunzip(opts);
Zlib.call(this, opts, binding.GUNZIP);
2011-09-06 23:13:05 +00:00
}
// raw - no header
function DeflateRaw(opts) {
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
Zlib.call(this, opts, binding.DEFLATERAW);
2011-09-06 23:13:05 +00:00
}
function InflateRaw(opts) {
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
Zlib.call(this, opts, binding.INFLATERAW);
2011-09-06 23:13:05 +00:00
}
// auto-detect header.
function Unzip(opts) {
if (!(this instanceof Unzip)) return new Unzip(opts);
Zlib.call(this, opts, binding.UNZIP);
2011-09-06 23:13:05 +00:00
}
// 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) {
2011-09-06 23:13:05 +00:00
this._opts = opts = opts || {};
2012-10-02 23:15:39 +00:00
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;
2011-09-06 23:13:05 +00:00
if (opts.chunkSize) {
if (opts.chunkSize < exports.Z_MIN_CHUNK ||
opts.chunkSize > exports.Z_MAX_CHUNK) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid chunk size: ' + opts.chunkSize);
2011-09-06 23:13:05 +00:00
}
}
if (opts.windowBits) {
if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
opts.windowBits > exports.Z_MAX_WINDOWBITS) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid windowBits: ' + opts.windowBits);
2011-09-06 23:13:05 +00:00
}
}
if (opts.level) {
if (opts.level < exports.Z_MIN_LEVEL ||
opts.level > exports.Z_MAX_LEVEL) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid compression level: ' + opts.level);
2011-09-06 23:13:05 +00:00
}
}
if (opts.memLevel) {
if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
opts.memLevel > exports.Z_MAX_MEMLEVEL) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid memLevel: ' + opts.memLevel);
2011-09-06 23:13:05 +00:00
}
}
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) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid strategy: ' + opts.strategy);
2011-09-06 23:13:05 +00:00
}
}
2011-12-02 07:53:56 +00:00
if (opts.dictionary) {
if (!util.isBuffer(opts.dictionary)) {
2011-12-02 07:53:56 +00:00
throw new Error('Invalid dictionary: it should be a Buffer instance');
}
}
this._binding = new binding.Zlib(mode);
var self = this;
2012-10-02 23:15:39 +00:00
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 (util.isNumber(opts.level)) level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY;
if (util.isNumber(opts.strategy)) strategy = opts.strategy;
2011-09-06 23:13:05 +00:00
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level,
2011-09-18 06:03:36 +00:00
opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
strategy,
2011-12-02 07:53:56 +00:00
opts.dictionary);
2011-09-06 23:13:05 +00:00
this._buffer = new Buffer(this._chunkSize);
this._offset = 0;
this._closed = false;
this._level = level;
this._strategy = strategy;
this.once('end', this.close);
2011-09-06 23:13:05 +00:00
}
2012-10-02 23:15:39 +00:00
util.inherits(Zlib, Transform);
2011-09-06 23:13:05 +00:00
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);
2011-09-06 23:13:05 +00:00
};
Zlib.prototype.flush = function(kind, callback) {
2012-10-02 23:15:39 +00:00
var ws = this._writableState;
if (util.isFunction(kind) || (util.isUndefined(kind) && !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) {
2012-10-02 23:15:39 +00:00
var self = this;
this.once('drain', function() {
self.flush(callback);
2012-10-02 23:15:39 +00:00
});
} else {
this._flushFlag = kind;
this.write(new Buffer(0), '', callback);
}
2011-09-06 23:13:05 +00:00
};
Zlib.prototype.close = function(callback) {
if (callback)
process.nextTick(callback);
if (this._closed)
return;
this._closed = true;
this._binding.close();
2012-10-02 23:15:39 +00:00
var self = this;
process.nextTick(function() {
self.emit('close');
});
};
Zlib.prototype._transform = function(chunk, encoding, cb) {
2012-10-02 23:15:39 +00:00
var flushFlag;
var ws = this._writableState;
var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length);
if (!util.isNull(chunk) && !util.isBuffer(chunk))
2012-10-02 23:15:39 +00:00
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;
}
}
2011-09-06 23:13:05 +00:00
var self = this;
this._processChunk(chunk, flushFlag, cb);
};
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
2011-09-06 23:13:05 +00:00
var availInBefore = chunk && chunk.length;
var availOutBefore = this._chunkSize - this._offset;
var inOff = 0;
2012-10-02 23:15:39 +00:00
var self = this;
var async = util.isFunction(cb);
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;
}
2012-10-02 23:15:39 +00:00
var req = this._binding.write(flushFlag,
2011-09-06 23:13:05 +00:00
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
req.buffer = chunk;
req.callback = callback;
2013-07-01 09:42:57 +00:00
function callback(availInAfter, availOutAfter) {
2012-10-02 23:15:39 +00:00
if (self._hadError)
return;
var have = availOutBefore - availOutAfter;
assert(have >= 0, 'have should not go down');
2011-09-06 23:13:05 +00:00
if (have > 0) {
var out = self._buffer.slice(self._offset, self._offset + have);
self._offset += have;
2012-10-02 23:15:39 +00:00
// serve some output to the consumer.
if (async) {
self.push(out);
} else {
buffers.push(out);
nread += out.length;
}
2011-09-06 23:13:05 +00:00
}
2012-10-02 23:15:39 +00:00
// exhausted the output buffer, or used all the input create a new one.
2011-09-06 23:13:05 +00:00
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize;
2011-09-06 23:13:05 +00:00
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.
2011-09-06 23:13:05 +00:00
inOff += (availInBefore - availInAfter);
availInBefore = availInAfter;
if (!async)
return true;
2012-10-02 23:15:39 +00:00
var newReq = self._binding.write(flushFlag,
2011-09-06 23:13:05 +00:00
chunk,
inOff,
availInBefore,
2011-09-06 23:13:05 +00:00
self._buffer,
self._offset,
self._chunkSize);
newReq.callback = callback; // this same function
newReq.buffer = chunk;
return;
}
if (!async)
return false;
2011-09-06 23:13:05 +00:00
// finished with the chunk.
2012-10-02 23:15:39 +00:00
cb();
2011-09-06 23:13:05 +00:00
}
};
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);