From e94a7f2996e7732284e7aaddbfcad8b264072674 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.js | 19 +++++++++++++++++++ test/parallel/test-buffer-write.js | 7 +++++++ 3 files changed, 26 insertions(+), 9 deletions(-) create mode 100644 test.js 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.js b/test.js new file mode 100644 index 00000000000000..1038398edbf627 --- /dev/null +++ b/test.js @@ -0,0 +1,19 @@ +let i = 0; + +while (i < 1_000_000) { + const buf = Buffer.from("\x80") + + if (buf[0] !== 194 || buf[1] !== 128) { + console.log("Unexpected return value:", buf, buf[0], buf[1]); + break + } + + i++; +} + +if (i < 1_000_000) { + console.log("FAILED after %d iterations", i); + process.exit(1); +} else { + console.log("PASSED after %d iterations", i); +} diff --git a/test/parallel/test-buffer-write.js b/test/parallel/test-buffer-write.js index 128327c47e5d6f..75913abab55046 100644 --- a/test/parallel/test-buffer-write.js +++ b/test/parallel/test-buffer-write.js @@ -106,3 +106,10 @@ 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'); +}