buffer: make byteLength work with Buffer correctly
authorJackson Tian <shyvo1987@gmail.com>
Mon, 18 Jan 2016 07:08:12 +0000 (15:08 +0800)
committerMyles Borins <mborins@us.ibm.com>
Mon, 15 Feb 2016 19:30:23 +0000 (11:30 -0800)
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 <info@bnoordhuis.nl>
Reviewed-By: Brian White <mscdex@mscdex.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
lib/buffer.js
test/parallel/test-buffer-bytelength.js

index f784e05..a830f2a 100644 (file)
@@ -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;
 
index 91f18af..d4dda5a 100644 (file)
@@ -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);