From 748d2b4de19ed212060fd80809bc2654a6900324 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Mon, 18 Jan 2016 15:08:12 +0800 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/4738 Reviewed-By: Ben Noordhuis Reviewed-By: Brian White Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- lib/buffer.js | 3 +++ test/parallel/test-buffer-bytelength.js | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/lib/buffer.js b/lib/buffer.js index f784e05835b225..a830f2a8e39017 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -258,6 +258,9 @@ function base64ByteLength(str, bytes) { function byteLength(string, encoding) { + if (string instanceof Buffer) + return string.length; + if (typeof string !== 'string') string = '' + string; diff --git a/test/parallel/test-buffer-bytelength.js b/test/parallel/test-buffer-bytelength.js index 91f18afcb3f5c3..d4dda5ae8b83c3 100644 --- a/test/parallel/test-buffer-bytelength.js +++ b/test/parallel/test-buffer-bytelength.js @@ -10,6 +10,12 @@ assert.equal(Buffer.byteLength(NaN, 'utf8'), 3); assert.equal(Buffer.byteLength({}, 'raws'), 15); assert.equal(Buffer.byteLength(), 9); +// buffer +var incomplete = new Buffer([0xe4, 0xb8, 0xad, 0xe6, 0x96]); +assert.equal(Buffer.byteLength(incomplete), 5); +var ascii = new Buffer('abc'); +assert.equal(Buffer.byteLength(ascii), 3); + // special case: zero length string assert.equal(Buffer.byteLength('', 'ascii'), 0); assert.equal(Buffer.byteLength('', 'HeX'), 0);