Skip to content

Commit dd8eeec

Browse files
authored
buffer: truncate instead of throw when writing beyond buffer
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>
1 parent 74ea78d commit dd8eeec

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/internal/buffer.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -1040,7 +1040,7 @@ function addBufferPrototypeMethods(proto) {
10401040
if (offset < 0 || offset > this.byteLength) {
10411041
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10421042
}
1043-
if (length < 0 || length > this.byteLength - offset) {
1043+
if (length < 0) {
10441044
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10451045
}
10461046
return asciiWriteStatic(this, string, offset, length);
@@ -1051,7 +1051,7 @@ function addBufferPrototypeMethods(proto) {
10511051
if (offset < 0 || offset > this.byteLength) {
10521052
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10531053
}
1054-
if (length < 0 || length > this.byteLength - offset) {
1054+
if (length < 0) {
10551055
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10561056
}
10571057
return latin1WriteStatic(this, string, offset, length);
@@ -1062,7 +1062,7 @@ function addBufferPrototypeMethods(proto) {
10621062
if (offset < 0 || offset > this.byteLength) {
10631063
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10641064
}
1065-
if (length < 0 || length > this.byteLength - offset) {
1065+
if (length < 0) {
10661066
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10671067
}
10681068
return utf8WriteStatic(this, string, offset, length);

test/parallel/test-buffer-write.js

+15
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,18 @@ assert.strictEqual(Buffer.alloc(4)
106106
assert.strictEqual(buf.write('ыы', 1, 'utf16le'), 4);
107107
assert.deepStrictEqual([...buf], [0, 0x4b, 0x04, 0x4b, 0x04, 0, 0, 0]);
108108
}
109+
110+
{
111+
const buf = Buffer.alloc(1);
112+
assert.strictEqual(buf.write('ww'), 1);
113+
assert.strictEqual(buf.toString(), 'w');
114+
}
115+
116+
assert.throws(() => {
117+
const buf = Buffer.alloc(1);
118+
assert.strictEqual(buf.asciiWrite('ww', 0, -1));
119+
assert.strictEqual(buf.latin1Write('ww', 0, -1));
120+
assert.strictEqual(buf.utf8Write('ww', 0, -1));
121+
}, common.expectsError({
122+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
123+
}));

0 commit comments

Comments
 (0)