zlib: allow custom flush type for flush()
authorBrian White <mscdex@mscdex.net>
Mon, 1 Jul 2013 09:44:03 +0000 (05:44 -0400)
committerBen Noordhuis <info@bnoordhuis.nl>
Mon, 1 Jul 2013 11:08:09 +0000 (13:08 +0200)
doc/api/zlib.markdown
lib/zlib.js
test/simple/test-zlib-flush.js [new file with mode: 0644]

index 3dd8d21..92569b7 100644 (file)
@@ -144,7 +144,9 @@ Returns a new [Unzip](#zlib_class_zlib_unzip) object with an
 Not exported by the `zlib` module. It is documented here because it is the base
 class of the compressor/decompressor classes.
 
-### zlib.flush(callback)
+### zlib.flush([kind], callback)
+
+`kind` defaults to `zlib.Z_FULL_FLUSH`.
 
 Flush pending data. Don't call this frivolously, premature flushes negatively
 impact the effectiveness of the compression algorithm.
index bbe09ef..ef4edd6 100644 (file)
@@ -357,9 +357,14 @@ Zlib.prototype._flush = function(callback) {
   this._transform(new Buffer(0), '', callback);
 };
 
-Zlib.prototype.flush = function(callback) {
+Zlib.prototype.flush = function(kind, callback) {
   var ws = this._writableState;
 
+  if (typeof kind === 'function' || (kind === undefined && !callback)) {
+    callback = kind;
+    kind = binding.Z_FULL_FLUSH;
+  }
+
   if (ws.ended) {
     if (callback)
       process.nextTick(callback);
@@ -372,7 +377,7 @@ Zlib.prototype.flush = function(callback) {
       self.flush(callback);
     });
   } else {
-    this._flushFlag = binding.Z_FULL_FLUSH;
+    this._flushFlag = kind;
     this.write(new Buffer(0), '', callback);
   }
 };
diff --git a/test/simple/test-zlib-flush.js b/test/simple/test-zlib-flush.js
new file mode 100644 (file)
index 0000000..0b189ce
--- /dev/null
@@ -0,0 +1,35 @@
+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 = 16,
+    opts = { level: 0 },
+    deflater = zlib.createDeflate(opts);
+
+var chunk = file.slice(0, chunkSize),
+    expectedNone = new Buffer([0x78, 0x01]),
+    blkhdr = new Buffer([0x00, 0x10, 0x00, 0xef, 0xff]),
+    adler32 = new Buffer([0x00, 0x00, 0x00, 0xff, 0xff]),
+    expectedFull = Buffer.concat([blkhdr, chunk, adler32]),
+    actualNone,
+    actualFull;
+
+deflater.write(chunk, function() {
+  deflater.flush(zlib.Z_NO_FLUSH, function() {
+    actualNone = deflater.read();
+    deflater.flush(function() {
+      var bufs = [], buf;
+      while (buf = deflater.read())
+        bufs.push(buf);
+      actualFull = Buffer.concat(bufs);
+    });
+  });
+});
+
+process.once('exit', function() {
+  assert.deepEqual(actualNone, expectedNone);
+  assert.deepEqual(actualFull, expectedFull);
+});