Skip to content

Commit 8d0ca10

Browse files
JacksonTianjasnell
authored andcommitted
buffer: make byteLength work with Buffer correctly
Make the byteLength work correctly when input is Buffer. e.g: ```js // The incomplete unicode string Buffer.byteLength(new Buffer([0xe4, 0xb8, 0xad, 0xe6, 0x96])) ``` The old output: 9 The new output: 5 PR-URL: #4738 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Brian White <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent 5f57005 commit 8d0ca10

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

lib/buffer.js

+3
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,9 @@ function base64ByteLength(str, bytes) {
262262

263263

264264
function byteLength(string, encoding) {
265+
if (string instanceof Buffer)
266+
return string.length;
267+
265268
if (typeof string !== 'string')
266269
string = '' + string;
267270

test/parallel/test-buffer-bytelength.js

+6
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ assert.equal(Buffer.byteLength(NaN, 'utf8'), 3);
1010
assert.equal(Buffer.byteLength({}, 'binary'), 15);
1111
assert.equal(Buffer.byteLength(), 9);
1212

13+
// buffer
14+
var incomplete = new Buffer([0xe4, 0xb8, 0xad, 0xe6, 0x96]);
15+
assert.equal(Buffer.byteLength(incomplete), 5);
16+
var ascii = new Buffer('abc');
17+
assert.equal(Buffer.byteLength(ascii), 3);
18+
1319
// special case: zero length string
1420
assert.equal(Buffer.byteLength('', 'ascii'), 0);
1521
assert.equal(Buffer.byteLength('', 'HeX'), 0);

0 commit comments

Comments
 (0)