Skip to content

Commit

Permalink
buffer: optimize write checks
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Aug 11, 2024
1 parent 298ff4f commit 40b9b26
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
4 changes: 2 additions & 2 deletions benchmark/buffers/buffer-write-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
const common = require('../common.js');
const bench = common.createBenchmark(main, {
encoding: [
'', 'utf8', 'ascii', 'hex', 'utf16le', 'latin1',
'', 'utf8', 'ascii', 'latin1',
],
args: [ '', 'offset', 'offset+length' ],
len: [2048],
len: [0],
n: [1e6],
});

Expand Down
21 changes: 16 additions & 5 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1092,23 +1092,34 @@ Buffer.prototype.write = function write(string, offset, length, encoding) {

// Buffer#write(string, offset[, length][, encoding])
} else {
validateOffset(offset, 'offset', 0, this.length);
if (NumberIsInteger(offset)) {
if (offset < 0 || offset > this.length) {
throw new ERR_OUT_OF_RANGE('offset', `>= ${0} && <= ${this.length}`, value);

Check failure on line 1097 in lib/buffer.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

'value' is not defined
}
} else {
throw new ERR_INVALID_ARG_TYPE('offset', 'integer', offset);
}

const remaining = this.length - offset;

if (length === undefined) {
length = remaining;
} else if (NumberIsInteger(length)) {
if (length < 0 || length > this.length) {
throw new ERR_OUT_OF_RANGE('length', `>= ${0} && <= ${this.length}`, value);

Check failure on line 1109 in lib/buffer.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

'value' is not defined
}
if (length > remaining) {
length = remaining;
}
} else if (typeof length === 'string') {
encoding = length;
length = remaining;
} else {
validateOffset(length, 'length', 0, this.length);
if (length > remaining)
length = remaining;
throw new ERR_INVALID_ARG_TYPE('length', 'integer', length);
}
}

if (!encoding)
if (!encoding || encoding === 'utf8' || encoding === 'ascii')
return this.utf8Write(string, offset, length);

const ops = getEncodingOps(encoding);
Expand Down

0 comments on commit 40b9b26

Please sign in to comment.