Permalink
Browse files

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.
  • Loading branch information...
1 parent acad8d9 commit 6772308883f3025f94db208186224b887ff9bc69 @trevnorris trevnorris committed with isaacs Nov 30, 2012
Showing with 12 additions and 4 deletions.
  1. +4 −4 lib/buffer.js
  2. +8 −0 test/simple/test-buffer.js
View
@@ -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;
}
@@ -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);

0 comments on commit 6772308

Please sign in to comment.