Skip to content

Commit

Permalink
buffer: make byteLength work with Buffer correctly
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
JacksonTian authored and jasnell committed Jan 18, 2016
1 parent 5f57005 commit 8d0ca10
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ function base64ByteLength(str, bytes) {


function byteLength(string, encoding) {
if (string instanceof Buffer)
return string.length;

if (typeof string !== 'string')
string = '' + string;

Expand Down
6 changes: 6 additions & 0 deletions test/parallel/test-buffer-bytelength.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ assert.equal(Buffer.byteLength(NaN, 'utf8'), 3);
assert.equal(Buffer.byteLength({}, 'binary'), 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);
Expand Down

0 comments on commit 8d0ca10

Please sign in to comment.