buffer: throw on failed fill attempts by cjihrig · Pull Request #17427 · nodejs/node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions doc/api/buffer.md
6 changes: 5 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -892,8 +892,12 @@ function fill_(buf, val, start, end, encoding) {

start = start >>> 0;
end = end === undefined ? buf.length : end >>> 0;
const fillLength = bindingFill(buf, val, start, end, encoding);

return bindingFill(buf, val, start, end, encoding);
if (fillLength === -1)
throw new errors.TypeError('ERR_INVALID_ARG_VALUE', 'value', val);

return fillLength;
}


Expand Down
9 changes: 5 additions & 4 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -643,11 +643,12 @@ void Fill(const FunctionCallbackInfo<Value>& args) {
enc,
nullptr);
// This check is also needed in case Write() returns that no bytes could
// be written.
// TODO(trevnorris): Should this throw? Because of the string length was
// greater than 0 but couldn't be written then the string was invalid.
// be written. If no bytes could be written, then return -1 because the
// string is invalid. This will trigger a throw in JavaScript. Silently
// failing should be avoided because it can lead to buffers with unexpected
// contents.
if (str_length == 0)
return args.GetReturnValue().Set(0);
return args.GetReturnValue().Set(-1);
}

start_fill:
Expand Down
21 changes: 12 additions & 9 deletions test/parallel/test-buffer-alloc.js
Original file line number Diff line number Diff line change
Expand Up @@ -1006,13 +1006,16 @@ assert.strictEqual(Buffer.prototype.toLocaleString, Buffer.prototype.toString);
assert.strictEqual(buf.toLocaleString(), buf.toString());
}

{
// Ref: https://github.com/nodejs/node/issues/17423
const buf = Buffer.alloc(0x1000, 'This is not correctly encoded', 'hex');
assert(buf.every((byte) => byte === 0), `Buffer was not zeroed out: ${buf}`);
}
common.expectsError(() => {
Buffer.alloc(0x1000, 'This is not correctly encoded', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
});

{
const buf = Buffer.alloc(0x1000, 'c', 'hex');
assert(buf.every((byte) => byte === 0), `Buffer was not zeroed out: ${buf}`);
}
common.expectsError(() => {
Buffer.alloc(0x1000, 'c', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
});
34 changes: 20 additions & 14 deletions test/parallel/test-buffer-fill.js