From 6772308883f3025f94db208186224b887ff9bc69 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Fri, 30 Nov 2012 13:02:39 -0800 Subject: [PATCH] buffer: Don't double-negate numeric buffer arg Fix #4331 Using double negate forces values into 32bit space. Because of this Math.ceil needs to be used. Since NaN comparisons are always false, use that to our advantage to return 0 if it is. Also added two tests to verify the changes. --- lib/buffer.js | 8 ++++---- test/simple/test-buffer.js | 8 ++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 53f484c56dc..91a6326b9ab 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -192,10 +192,10 @@ SlowBuffer.prototype.slice = function(start, end) { function coerce(length) { // Coerce length to a number (possibly NaN), round up - // in case it's fractional (e.g. 123.456) then do a - // double negate to coerce a NaN to 0. Easy, right? - length = ~~Math.ceil(+length); - return length < 0 ? 0 : length; + // in case it's fractional (e.g. 123.456). Since NaN + // comparisons are always false, use to return zero. + length = Math.ceil(+length); + return length > 0 ? length : 0; } diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index e423c76e00a..25688182b1e 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -737,3 +737,11 @@ assert.equal(b.toString(), 'xxx'); // issue GH-3416 Buffer(Buffer(0), 0, 0); + +// issue GH-4331 +assert.throws(function() { + new Buffer(0xFFFFFFFF); +}, RangeError); +assert.throws(function() { + new Buffer(0xFFFFFFFFF); +}, TypeError);