Skip to content

Commit 170bcd5

Browse files
authored
Keep Inflater's remaining count exact when the output buffer is small (#64)
1 parent 62c4b48 commit 170bcd5

2 files changed

Lines changed: 25 additions & 5 deletions

File tree

‎src/inflate.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,12 @@ export class Inflate {
168168
if (e !== UNDERFLOW) throw e;
169169
this.ip = ip; this.bitbuf = buf; this.bitcnt = cnt;
170170
}
171-
if (this.stage === Stage.Done) {
172-
// whole bytes still buffered belong to whatever follows the stream
173-
this.ip -= this.bitcnt >> 3;
174-
this.bitbuf = this.bitcnt = 0;
175-
}
171+
// give back whole buffered bytes, as zlib does, so a caller's remaining count stays exact
172+
const back = Math.min(this.bitcnt >> 3, this.ip);
173+
this.ip -= back;
174+
this.bitcnt -= back << 3;
175+
this.bitbuf &= (1 << this.bitcnt) - 1;
176+
if (this.stage === Stage.Done) this.bitbuf = this.bitcnt = 0;
176177
this.finishCall();
177178
return [this.ip, this.op - off];
178179
}

‎test/zip.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,25 @@ test("inflate stops at the end of the stream and leaves the bytes after it", ()
105105
assert.equal(read, packed.length);
106106
});
107107

108+
test("inflate reads exactly the stream when the output is small", () => {
109+
const data = sample(300, 14);
110+
const packed = deflateRawSync(data);
111+
const input = Buffer.concat([packed, Buffer.from([1, 2, 3, 4, 5])]);
112+
for (const size of [1, 2, 3, 4, 5, 8]) {
113+
const z = new Inflate(true);
114+
const out = new Uint8Array(size);
115+
let pos = 0, total = 0;
116+
while (!z.finished) {
117+
const [read, written] = z.run(input.subarray(pos), out, 0, size);
118+
assert.ok(read > 0 || written > 0, `no progress at size ${size}`);
119+
pos += read;
120+
total += written;
121+
}
122+
assert.equal(total, data.length);
123+
assert.equal(pos, packed.length, `size ${size}`);
124+
}
125+
});
126+
108127
test("inflate sees the end of the stream when the output fills on the last byte", () => {
109128
for (const wrap of [true, false]) {
110129
for (const size of [1, 10, 5000]) {

0 commit comments

Comments
 (0)