diff --git a/lib/buffer.js b/lib/buffer.js index a4bd2a2f874bda..2472390086057c 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -199,8 +199,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array); function allocate(size) { - if (size === 0) { - return createBuffer(size); + if (size <= 0) { + return createBuffer(0); } if (size < (Buffer.poolSize >>> 1)) { if (size > (poolSize - poolOffset)) diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index f48cfc2a328647..02f94436968c30 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1465,3 +1465,14 @@ assert.equal(Buffer.prototype.parent, undefined); assert.equal(Buffer.prototype.offset, undefined); assert.equal(SlowBuffer.prototype.parent, undefined); assert.equal(SlowBuffer.prototype.offset, undefined); + +{ + // Test that large negative Buffer length inputs don't affect the pool offset. + assert.deepStrictEqual(Buffer(-Buffer.poolSize), Buffer.from('')); + assert.deepStrictEqual(Buffer(-100), Buffer.from('')); + assert.deepStrictEqual(Buffer.allocUnsafe(-Buffer.poolSize), Buffer.from('')); + assert.deepStrictEqual(Buffer.allocUnsafe(-100), Buffer.from('')); + + // Check pool offset after that by trying to write string into the pool. + assert.doesNotThrow(() => Buffer.from('abc')); +}