1'use strict';
2// Test unzipping a gzip file that contains multiple concatenated "members"
3
4const common = require('../common');
5const assert = require('assert');
6const zlib = require('zlib');
7const fs = require('fs');
8const fixtures = require('../common/fixtures');
9
10const abc = 'abc';
11const def = 'def';
12
13const abcEncoded = zlib.gzipSync(abc);
14const defEncoded = zlib.gzipSync(def);
15
16const data = Buffer.concat([
17  abcEncoded,
18  defEncoded,
19]);
20
21assert.strictEqual(zlib.gunzipSync(data).toString(), (abc + def));
22
23zlib.gunzip(data, common.mustSucceed((result) => {
24  assert.strictEqual(result.toString(), (abc + def));
25}));
26
27zlib.unzip(data, common.mustSucceed((result) => {
28  assert.strictEqual(result.toString(), (abc + def));
29}));
30
31// Multi-member support does not apply to zlib inflate/deflate.
32zlib.unzip(Buffer.concat([
33  zlib.deflateSync('abc'),
34  zlib.deflateSync('def'),
35]), common.mustSucceed((result) => {
36  assert.strictEqual(result.toString(), abc);
37}));
38
39// Files that have the "right" magic bytes for starting a new gzip member
40// in the middle of themselves, even if they are part of a single
41// regularly compressed member
42const pmmFileZlib = fixtures.path('pseudo-multimember-gzip.z');
43const pmmFileGz = fixtures.path('pseudo-multimember-gzip.gz');
44
45const pmmExpected = zlib.inflateSync(fs.readFileSync(pmmFileZlib));
46const pmmResultBuffers = [];
47
48fs.createReadStream(pmmFileGz)
49  .pipe(zlib.createGunzip())
50  .on('error', (err) => {
51    assert.ifError(err);
52  })
53  .on('data', (data) => pmmResultBuffers.push(data))
54  .on('finish', common.mustCall(() => {
55    // Result should match original random garbage
56    assert.deepStrictEqual(Buffer.concat(pmmResultBuffers), pmmExpected);
57  }));
58
59// Test that the next gzip member can wrap around the input buffer boundary
60[0, 1, 2, 3, 4, defEncoded.length].forEach((offset) => {
61  const resultBuffers = [];
62
63  const unzip = zlib.createGunzip()
64    .on('error', (err) => {
65      assert.ifError(err);
66    })
67    .on('data', (data) => resultBuffers.push(data))
68    .on('finish', common.mustCall(() => {
69      assert.strictEqual(
70        Buffer.concat(resultBuffers).toString(),
71        'abcdef',
72        `result should match original input (offset = ${offset})`
73      );
74    }));
75
76  // First write: write "abc" + the first bytes of "def"
77  unzip.write(Buffer.concat([
78    abcEncoded, defEncoded.slice(0, offset),
79  ]));
80
81  // Write remaining bytes of "def"
82  unzip.end(defEncoded.slice(offset));
83});
84