|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Regression test for https://github.com/nodejs/node/issues/66078: ending a |
| 4 | +// ZstdCompress stream with writes still queued appended an empty frame. |
| 5 | + |
| 6 | +const common = require('../common'); |
| 7 | +const assert = require('assert'); |
| 8 | +const { finished } = require('stream/promises'); |
| 9 | +const zlib = require('zlib'); |
| 10 | + |
| 11 | +const kMagic = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); |
| 12 | + |
| 13 | +function countFrames(buffer) { |
| 14 | + let count = 0; |
| 15 | + for (let i = buffer.indexOf(kMagic); i !== -1; i = buffer.indexOf(kMagic, i + 1)) { |
| 16 | + count++; |
| 17 | + } |
| 18 | + return count; |
| 19 | +} |
| 20 | + |
| 21 | +async function compress(use) { |
| 22 | + const stream = zlib.createZstdCompress(); |
| 23 | + const chunks = []; |
| 24 | + stream.on('data', (chunk) => chunks.push(chunk)); |
| 25 | + await use(stream); |
| 26 | + stream.end(); |
| 27 | + await finished(stream); |
| 28 | + return Buffer.concat(chunks); |
| 29 | +} |
| 30 | + |
| 31 | +(async () => { |
| 32 | + const expected = await compress((stream) => stream.write('hello world')); |
| 33 | + assert.strictEqual(countFrames(expected), 1); |
| 34 | + |
| 35 | + assert.deepStrictEqual(await compress((stream) => { |
| 36 | + stream.write('hello '); |
| 37 | + stream.write('world'); |
| 38 | + }), expected); |
| 39 | + |
| 40 | + assert.deepStrictEqual(await compress((stream) => { |
| 41 | + stream.write('hello world'); |
| 42 | + stream.flush(zlib.constants.ZSTD_e_end); |
| 43 | + }), expected); |
| 44 | + |
| 45 | + // The empty flush has to complete before end(), which would otherwise |
| 46 | + // promote it to ZSTD_e_end. |
| 47 | + assert.deepStrictEqual(await compress((stream) => { |
| 48 | + stream.write('hello world'); |
| 49 | + stream.flush(zlib.constants.ZSTD_e_end); |
| 50 | + return new Promise((resolve) => stream.flush(resolve)); |
| 51 | + }), expected); |
| 52 | + |
| 53 | + const empty = await compress(() => {}); |
| 54 | + assert.strictEqual(countFrames(empty), 1); |
| 55 | + assert.strictEqual(zlib.zstdDecompressSync(empty).length, 0); |
| 56 | + |
| 57 | + const twoFrames = await compress((stream) => { |
| 58 | + stream.write('hello '); |
| 59 | + stream.flush(zlib.constants.ZSTD_e_end); |
| 60 | + stream.write('world'); |
| 61 | + }); |
| 62 | + assert.strictEqual(countFrames(twoFrames), 2); |
| 63 | + assert.strictEqual(zlib.zstdDecompressSync(twoFrames).toString(), 'hello world'); |
| 64 | +})().then(common.mustCall()); |