Skip to content

Commit c71748e

Browse files
mhofmanisaacs
authored andcommitted
Support non-writable Buffer.concat
PR-URL: #28 Credit: @mhofman Close: #28 Reviewed-by: @Rododrendron
1 parent 65ba5a0 commit c71748e

3 files changed

Lines changed: 23 additions & 351 deletions

File tree

index.js

Lines changed: 0 additions & 348 deletions
This file was deleted.

src/index.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@ import { constants } from './constants.js'
66
export { constants } from './constants.js'
77

88
const OriginalBufferConcat = Buffer.concat
9+
const desc = Object.getOwnPropertyDescriptor(Buffer, 'concat')
10+
const noop = (args: Buffer[]) => args as unknown as Buffer
11+
const passthroughBufferConcat =
12+
desc?.writable === true || desc?.set !== undefined
13+
? (makeNoOp: boolean) => {
14+
Buffer.concat = makeNoOp ? noop : OriginalBufferConcat
15+
}
16+
: (_: boolean) => {}
17+
918
const _superWrite = Symbol('_superWrite')
1019

1120
export class ZlibError extends Error {
@@ -217,7 +226,7 @@ abstract class ZlibBase extends Minipass<Buffer, ChunkWithFlushFlag> {
217226
this.#handle.close = () => {}
218227
// It also calls `Buffer.concat()` at the end, which may be convenient
219228
// for some, but which we are not interested in as it slows us down.
220-
Buffer.concat = args => args as unknown as Buffer
229+
passthroughBufferConcat(true)
221230
let result: undefined | Buffer | Buffer[] = undefined
222231
try {
223232
const flushFlag =
@@ -230,11 +239,11 @@ abstract class ZlibBase extends Minipass<Buffer, ChunkWithFlushFlag> {
230239
}
231240
)._processChunk(chunk as Buffer, flushFlag)
232241
// if we don't throw, reset it back how it was
233-
Buffer.concat = OriginalBufferConcat
242+
passthroughBufferConcat(false)
234243
} catch (err) {
235244
// or if we do, put Buffer.concat() back before we emit error
236245
// Error events call into user code, which may call Buffer.concat()
237-
Buffer.concat = OriginalBufferConcat
246+
passthroughBufferConcat(false)
238247
this.#onError(new ZlibError(err as NodeJS.ErrnoException))
239248
} finally {
240249
if (this.#handle) {

test/non-writable-concat.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import t from 'tap'
2+
import { Buffer } from 'buffer'
3+
Object.defineProperty(Buffer, 'concat', { writable: false })
4+
5+
// need to await import so it comes after the prop change
6+
const { Gzip } = await import('../dist/esm/index.js')
7+
const gz = new Gzip()
8+
9+
t.plan(1)
10+
gz.write('', _ => t.pass('called write cb'))
11+
gz.end()

0 commit comments

Comments
 (0)