From f6f23342be491b5e05408dcdd7a57196ad6d72f1 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Fri, 23 Aug 2024 15:43:05 +0200 Subject: [PATCH] buffer: truncate instead of throw when writing beyond buffer Fixes: https://github.com/nodejs/node/issues/54523 PR-URL: https://github.com/nodejs/node/pull/54524 --- lib/internal/buffer.js | 9 --------- test/parallel/test-buffer-write.js | 6 ++++++ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index c547c1f993fb55..f66a556c698928 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1040,9 +1040,6 @@ function addBufferPrototypeMethods(proto) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0 || length > this.byteLength - offset) { - throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); - } return asciiWriteStatic(this, string, offset, length); }; proto.base64Write = base64Write; @@ -1051,9 +1048,6 @@ function addBufferPrototypeMethods(proto) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0 || length > this.byteLength - offset) { - throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); - } return latin1WriteStatic(this, string, offset, length); }; proto.hexWrite = hexWrite; @@ -1062,9 +1056,6 @@ function addBufferPrototypeMethods(proto) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0 || length > this.byteLength - offset) { - throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); - } return utf8WriteStatic(this, string, offset, length); }; } diff --git a/test/parallel/test-buffer-write.js b/test/parallel/test-buffer-write.js index 128327c47e5d6f..c7c1f890ee4288 100644 --- a/test/parallel/test-buffer-write.js +++ b/test/parallel/test-buffer-write.js @@ -106,3 +106,9 @@ assert.strictEqual(Buffer.alloc(4) assert.strictEqual(buf.write('ыы', 1, 'utf16le'), 4); assert.deepStrictEqual([...buf], [0, 0x4b, 0x04, 0x4b, 0x04, 0, 0, 0]); } + +{ + const buf = Buffer.alloc(1); + assert.strictEqual(buf.write('ww'), 1); + assert.strictEqual(buf.toString(), 'w'); +}