From 05e2acb428047174fc201158ac859d20c2ece1dd Mon Sep 17 00:00:00 2001 From: Justin Sprigg Date: Mon, 16 May 2016 02:04:03 +1000 Subject: [PATCH] buffer: fix single digit hex string handling Fixes single digit hex strings not raising TypeError on Buffer creation. Fixes: https://github.com/nodejs/node/issues/6770 PR-URL: https://github.com/nodejs/node/pull/6775 Reviewed-By: Anna Henningsen --- lib/buffer.js | 6 +++--- test/parallel/test-buffer.js | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 515f841fd3..a4bd2a2f87 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -225,11 +225,11 @@ function fromString(string, encoding) { if (!Buffer.isEncoding(encoding)) throw new TypeError('"encoding" must be a valid string encoding'); - var length = byteLength(string, encoding); - - if (length === 0) + if (string.length === 0) return Buffer.alloc(0); + var length = byteLength(string, encoding); + if (length >= (Buffer.poolSize >>> 1)) return binding.createFromString(string, encoding); diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 62fd488efe..f48cfc2a32 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -749,6 +749,15 @@ for (let i = 0; i < 256; i++) { assert.equal(hexb2[i], hexb[i]); } +// Test single hex character throws TypeError +// - https://github.com/nodejs/node/issues/6770 +assert.throws(function() { + Buffer.from('A', 'hex'); +}, TypeError); + +// Test single base64 char encodes as 0 +assert.strictEqual(Buffer.from('A', 'base64').length, 0); + { // test an invalid slice end. console.log('Try to slice off the end of the buffer');