Skip to content

Commit

Permalink
buffer: truncate instead of throw when writing beyond buffer
Browse files Browse the repository at this point in the history
Fixes: #54523
Fixes: #54518
PR-URL: #54524
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
  • Loading branch information
ronag authored and RafaelGSS committed Aug 30, 2024
1 parent e6e1f4e commit ac178b0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/internal/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1040,7 +1040,7 @@ function addBufferPrototypeMethods(proto) {
if (offset < 0 || offset > this.byteLength) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
}
if (length < 0 || length > this.byteLength - offset) {
if (length < 0) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
}
return asciiWriteStatic(this, string, offset, length);
Expand All @@ -1051,7 +1051,7 @@ function addBufferPrototypeMethods(proto) {
if (offset < 0 || offset > this.byteLength) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
}
if (length < 0 || length > this.byteLength - offset) {
if (length < 0) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
}
return latin1WriteStatic(this, string, offset, length);
Expand All @@ -1062,7 +1062,7 @@ function addBufferPrototypeMethods(proto) {
if (offset < 0 || offset > this.byteLength) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
}
if (length < 0 || length > this.byteLength - offset) {
if (length < 0) {
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
}
return utf8WriteStatic(this, string, offset, length);
Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-buffer-write.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,18 @@ 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');
}

assert.throws(() => {
const buf = Buffer.alloc(1);
assert.strictEqual(buf.asciiWrite('ww', 0, -1));
assert.strictEqual(buf.latin1Write('ww', 0, -1));
assert.strictEqual(buf.utf8Write('ww', 0, -1));
}, common.expectsError({
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
}));

0 comments on commit ac178b0

Please sign in to comment.