diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index 20b22ad5293..dc21fb3e334 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1036,33 +1036,33 @@ function addBufferPrototypeMethods(proto) { proto.hexSlice = hexSlice; proto.ucs2Slice = ucs2Slice; proto.utf8Slice = utf8Slice; - proto.asciiWrite = function(string, offset = 0, length = this.byteLength) { + proto.asciiWrite = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return asciiWriteStatic(this, string, offset, length); }; proto.base64Write = base64Write; proto.base64urlWrite = base64urlWrite; - proto.latin1Write = function(string, offset = 0, length = this.byteLength) { + proto.latin1Write = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return latin1WriteStatic(this, string, offset, length); }; proto.hexWrite = hexWrite; proto.ucs2Write = ucs2Write; - proto.utf8Write = function(string, offset = 0, length = this.byteLength) { + proto.utf8Write = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return utf8WriteStatic(this, string, offset, length); diff --git a/test/parallel/test-buffer-write.js b/test/parallel/test-buffer-write.js index 309367c9c75..81076629b1d 100644 --- a/test/parallel/test-buffer-write.js +++ b/test/parallel/test-buffer-write.js @@ -121,3 +121,16 @@ assert.throws(() => { }, common.expectsError({ code: 'ERR_BUFFER_OUT_OF_BOUNDS', })); + + +assert.throws(() => { + Buffer.alloc(1).asciiWrite('ww', 0, 2); +}, common.expectsError({ + code: 'ERR_BUFFER_OUT_OF_BOUNDS', +})); + +assert.throws(() => { + Buffer.alloc(1).asciiWrite('ww', 1, 1); +}, common.expectsError({ + code: 'ERR_BUFFER_OUT_OF_BOUNDS', +}));