Skip to content

Commit 96b501d

Browse files
mscdexjasnell
authored andcommitted
buffer: make byteLength throw on invalid input
PR-URL: #8946 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Roman Reiss <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Teddy Katz <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent a349bc1 commit 96b501d

File tree

3 files changed

+9
-7
lines changed

3 files changed

+9
-7
lines changed

doc/api/buffer.md

-2
Original file line numberDiff line numberDiff line change
@@ -631,8 +631,6 @@ console.log(`${str}: ${str.length} characters, ` +
631631
When `string` is a `Buffer`/[`DataView`]/[`TypedArray`]/[`ArrayBuffer`], the
632632
actual byte length is returned.
633633

634-
Otherwise, converts to `String` and returns the byte length of string.
635-
636634
### Class Method: Buffer.compare(buf1, buf2)
637635
<!-- YAML
638636
added: v0.11.13

lib/buffer.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ function byteLength(string, encoding) {
369369
return string.byteLength;
370370
}
371371

372-
string = '' + string;
372+
throw new TypeError('"string" must be a string, Buffer, or ArrayBuffer');
373373
}
374374

375375
var len = string.length;

test/parallel/test-buffer-bytelength.js

+8-4
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@ const SlowBuffer = require('buffer').SlowBuffer;
77
const vm = require('vm');
88

99
// coerce values to string
10-
assert.strictEqual(Buffer.byteLength(32, 'latin1'), 2);
11-
assert.strictEqual(Buffer.byteLength(NaN, 'utf8'), 3);
12-
assert.strictEqual(Buffer.byteLength({}, 'latin1'), 15);
13-
assert.strictEqual(Buffer.byteLength(), 9);
10+
assert.throws(() => { Buffer.byteLength(32, 'latin1'); },
11+
'"string" must be a string, Buffer, or ArrayBuffer');
12+
assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); },
13+
'"string" must be a string, Buffer, or ArrayBuffer');
14+
assert.throws(() => { Buffer.byteLength({}, 'latin1'); },
15+
'"string" must be a string, Buffer, or ArrayBuffer');
16+
assert.throws(() => { Buffer.byteLength(); },
17+
'"string" must be a string, Buffer, or ArrayBuffer');
1418

1519
assert(ArrayBuffer.isView(new Buffer(10)));
1620
assert(ArrayBuffer.isView(new SlowBuffer(10)));

0 commit comments

Comments
 (0)