Skip to content

Commit 748d2b4

Browse files
JacksonTianMyles Borins
authored and
Myles Borins
committed
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 0178001 commit 748d2b4

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
@@ -258,6 +258,9 @@ function base64ByteLength(str, bytes) {
258258

259259

260260
function byteLength(string, encoding) {
261+
if (string instanceof Buffer)
262+
return string.length;
263+
261264
if (typeof string !== 'string')
262265
string = '' + string;
263266

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({}, 'raws'), 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)