Skip to content

Commit

Permalink
buffer: improve fill(number) performance
Browse files Browse the repository at this point in the history
PR-URL: #31489
Reviewed-By: Ben Noordhuis <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
  • Loading branch information
mscdex authored and codebytere committed Mar 17, 2020
1 parent 48e4d45 commit 1849c2c
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ const {
ObjectCreate,
ObjectDefineProperties,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
ObjectGetPrototypeOf,
ObjectSetPrototypeOf,
SymbolSpecies,
SymbolToPrimitive,
Uint8ArrayPrototype,
} = primordials;

const {
Expand Down Expand Up @@ -101,6 +104,13 @@ const {
addBufferPrototypeMethods
} = require('internal/buffer');

const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8ArrayPrototype);

const TypedArrayProto_byteLength =
ObjectGetOwnPropertyDescriptor(TypedArrayPrototype,
'byteLength').get;
const TypedArrayFill = TypedArrayPrototype.fill;

FastBuffer.prototype.constructor = Buffer;
Buffer.prototype = FastBuffer.prototype;
addBufferPrototypeMethods(Buffer.prototype);
Expand Down Expand Up @@ -1001,11 +1011,22 @@ function _fill(buf, value, offset, end, encoding) {
return buf;
}

const res = bindingFill(buf, value, offset, end, encoding);
if (res < 0) {
if (res === -1)
throw new ERR_INVALID_ARG_VALUE('value', value);
throw new ERR_BUFFER_OUT_OF_BOUNDS();

if (typeof value === 'number') {
// OOB check
const byteLen = TypedArrayProto_byteLength.call(buf);
const fillLength = end - offset;
if (offset > end || fillLength + offset > byteLen)
throw new ERR_BUFFER_OUT_OF_BOUNDS();

TypedArrayFill.call(buf, value, offset, end);
} else {
const res = bindingFill(buf, value, offset, end, encoding);
if (res < 0) {
if (res === -1)
throw new ERR_INVALID_ARG_VALUE('value', value);
throw new ERR_BUFFER_OUT_OF_BOUNDS();
}
}

return buf;
Expand Down

0 comments on commit 1849c2c

Please sign in to comment.