Skip to content

Commit 1849c2c

Browse files
mscdexcodebytere
authored andcommittedMar 17, 2020
buffer: improve fill(number) performance
PR-URL: #31489 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
1 parent 48e4d45 commit 1849c2c

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed
 

‎lib/buffer.js

+26-5
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,12 @@ const {
3434
ObjectCreate,
3535
ObjectDefineProperties,
3636
ObjectDefineProperty,
37+
ObjectGetOwnPropertyDescriptor,
38+
ObjectGetPrototypeOf,
3739
ObjectSetPrototypeOf,
3840
SymbolSpecies,
3941
SymbolToPrimitive,
42+
Uint8ArrayPrototype,
4043
} = primordials;
4144

4245
const {
@@ -101,6 +104,13 @@ const {
101104
addBufferPrototypeMethods
102105
} = require('internal/buffer');
103106

107+
const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8ArrayPrototype);
108+
109+
const TypedArrayProto_byteLength =
110+
ObjectGetOwnPropertyDescriptor(TypedArrayPrototype,
111+
'byteLength').get;
112+
const TypedArrayFill = TypedArrayPrototype.fill;
113+
104114
FastBuffer.prototype.constructor = Buffer;
105115
Buffer.prototype = FastBuffer.prototype;
106116
addBufferPrototypeMethods(Buffer.prototype);
@@ -1001,11 +1011,22 @@ function _fill(buf, value, offset, end, encoding) {
10011011
return buf;
10021012
}
10031013

1004-
const res = bindingFill(buf, value, offset, end, encoding);
1005-
if (res < 0) {
1006-
if (res === -1)
1007-
throw new ERR_INVALID_ARG_VALUE('value', value);
1008-
throw new ERR_BUFFER_OUT_OF_BOUNDS();
1014+
1015+
if (typeof value === 'number') {
1016+
// OOB check
1017+
const byteLen = TypedArrayProto_byteLength.call(buf);
1018+
const fillLength = end - offset;
1019+
if (offset > end || fillLength + offset > byteLen)
1020+
throw new ERR_BUFFER_OUT_OF_BOUNDS();
1021+
1022+
TypedArrayFill.call(buf, value, offset, end);
1023+
} else {
1024+
const res = bindingFill(buf, value, offset, end, encoding);
1025+
if (res < 0) {
1026+
if (res === -1)
1027+
throw new ERR_INVALID_ARG_VALUE('value', value);
1028+
throw new ERR_BUFFER_OUT_OF_BOUNDS();
1029+
}
10091030
}
10101031

10111032
return buf;

0 commit comments

Comments
 (0)
Please sign in to comment.