buffer: truncate instead of throw when writing beyond buffer

Fixes: https://github.com/nodejs/node/issues/54523
Fixes: https://github.com/nodejs/node/issues/54518
PR-URL: https://github.com/nodejs/node/pull/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>
This commit is contained in:
Robert Nagy 2024-08-27 10:48:52 +02:00 committed by GitHub
parent 74ea78ddc6
commit dd8eeec3f0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 3 deletions

View File

@ -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);
@ -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);
@ -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);

View File

@ -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',
}));