From 513ffb32e5a8065de368ccab22ee71986d3946e0 Mon Sep 17 00:00:00 2001 From: Nikolai Vavilov Date: Sun, 5 Feb 2017 14:14:53 +0200 Subject: [PATCH] buffer: stricter argument checking in toString This prevents the confusing behavior of `buf.toString(0, 5)` by disallowing passing `0` as the encoding. PR-URL: https://github.com/nodejs/node/pull/11120 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Joyee Cheung Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Luigi Pinca --- lib/buffer.js | 2 +- test/parallel/test-buffer-tostring-range.js | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index 0a8724bda48e48..cb93d7e2488f3b 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -463,7 +463,7 @@ function slowToString(encoding, start, end) { if (end <= start) return ''; - if (!encoding) encoding = 'utf8'; + if (encoding === undefined) encoding = 'utf8'; while (true) { switch (encoding) { diff --git a/test/parallel/test-buffer-tostring-range.js b/test/parallel/test-buffer-tostring-range.js index c7ab356e4661ff..a550906912a480 100644 --- a/test/parallel/test-buffer-tostring-range.js +++ b/test/parallel/test-buffer-tostring-range.js @@ -82,3 +82,11 @@ assert.strictEqual(rangeBuffer.toString('ascii', 0, true), 'a'); assert.strictEqual(rangeBuffer.toString({toString: function() { return 'ascii'; }}), 'abc'); + +// try toString() with 0 and null as the encoding +assert.throws(() => { + rangeBuffer.toString(0, 1, 2); +}, /^TypeError: Unknown encoding: 0$/); +assert.throws(() => { + rangeBuffer.toString(null, 1, 2); +}, /^TypeError: Unknown encoding: null$/);