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: nodejs#54523

PR-URL: nodejs#54524
  • Loading branch information
ronag committed Aug 23, 2024
1 parent d5dc540 commit e94a7f2
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 9 deletions.
9 changes: 0 additions & 9 deletions lib/internal/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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);
};
}
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -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);
}
7 changes: 7 additions & 0 deletions test/parallel/test-buffer-write.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

0 comments on commit e94a7f2

Please sign in to comment.