Skip to content

Commit e94a7f2

Browse files
committed
buffer: truncate instead of throw when writing beyond buffer
Fixes: #54523 PR-URL: #54524
1 parent d5dc540 commit e94a7f2

File tree

3 files changed

+26
-9
lines changed

3 files changed

+26
-9
lines changed

lib/internal/buffer.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1040,9 +1040,6 @@ 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) {
1044-
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
1045-
}
10461043
return asciiWriteStatic(this, string, offset, length);
10471044
};
10481045
proto.base64Write = base64Write;
@@ -1051,9 +1048,6 @@ function addBufferPrototypeMethods(proto) {
10511048
if (offset < 0 || offset > this.byteLength) {
10521049
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10531050
}
1054-
if (length < 0 || length > this.byteLength - offset) {
1055-
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
1056-
}
10571051
return latin1WriteStatic(this, string, offset, length);
10581052
};
10591053
proto.hexWrite = hexWrite;
@@ -1062,9 +1056,6 @@ function addBufferPrototypeMethods(proto) {
10621056
if (offset < 0 || offset > this.byteLength) {
10631057
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10641058
}
1065-
if (length < 0 || length > this.byteLength - offset) {
1066-
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
1067-
}
10681059
return utf8WriteStatic(this, string, offset, length);
10691060
};
10701061
}

test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
let i = 0;
2+
3+
while (i < 1_000_000) {
4+
const buf = Buffer.from("\x80")
5+
6+
if (buf[0] !== 194 || buf[1] !== 128) {
7+
console.log("Unexpected return value:", buf, buf[0], buf[1]);
8+
break
9+
}
10+
11+
i++;
12+
}
13+
14+
if (i < 1_000_000) {
15+
console.log("FAILED after %d iterations", i);
16+
process.exit(1);
17+
} else {
18+
console.log("PASSED after %d iterations", i);
19+
}

test/parallel/test-buffer-write.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,10 @@ 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+
{
112+
const buf = Buffer.alloc(1);
113+
assert.strictEqual(buf.write('ww'), 1);
114+
assert.strictEqual(buf.toString(), 'w');
115+
}

0 commit comments

Comments
 (0)