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.
v0.8.16-release
Trevor Norris 2012-11-30 13:02:39 -08:00 committed by isaacs
parent acad8d9a77
commit 6772308883
2 changed files with 12 additions and 4 deletions

View File

@ -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;
}

View File

@ -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);