Skip to content

Commit 05e2acb

Browse files
jspriaddaleax
authored andcommitted
buffer: fix single digit hex string handling
Fixes single digit hex strings not raising TypeError on Buffer creation. Fixes: #6770 PR-URL: #6775 Reviewed-By: Anna Henningsen <[email protected]>
1 parent b49df88 commit 05e2acb

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

lib/buffer.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,11 +225,11 @@ function fromString(string, encoding) {
225225
if (!Buffer.isEncoding(encoding))
226226
throw new TypeError('"encoding" must be a valid string encoding');
227227

228-
var length = byteLength(string, encoding);
229-
230-
if (length === 0)
228+
if (string.length === 0)
231229
return Buffer.alloc(0);
232230

231+
var length = byteLength(string, encoding);
232+
233233
if (length >= (Buffer.poolSize >>> 1))
234234
return binding.createFromString(string, encoding);
235235

test/parallel/test-buffer.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,15 @@ for (let i = 0; i < 256; i++) {
749749
assert.equal(hexb2[i], hexb[i]);
750750
}
751751

752+
// Test single hex character throws TypeError
753+
// - https://github.com/nodejs/node/issues/6770
754+
assert.throws(function() {
755+
Buffer.from('A', 'hex');
756+
}, TypeError);
757+
758+
// Test single base64 char encodes as 0
759+
assert.strictEqual(Buffer.from('A', 'base64').length, 0);
760+
752761
{
753762
// test an invalid slice end.
754763
console.log('Try to slice off the end of the buffer');

0 commit comments

Comments
 (0)