diff options
author | Ben Noordhuis <info@bnoordhuis.nl> | 2011-09-24 05:07:35 +0200 |
---|---|---|
committer | Ben Noordhuis <info@bnoordhuis.nl> | 2011-09-24 18:27:03 +0200 |
commit | d1571314390d9a0f8d697d8e70987f7a9e1ef98d (patch) | |
tree | 930615934d7259a9ebc159f0ff244028a20b6316 /lib/buffer.js | |
parent | fcba1459f2400b59927411578c99a022d41bbbe7 (diff) | |
download | nodejs-d1571314390d9a0f8d697d8e70987f7a9e1ef98d.tar.gz nodejs-d1571314390d9a0f8d697d8e70987f7a9e1ef98d.tar.bz2 nodejs-d1571314390d9a0f8d697d8e70987f7a9e1ef98d.zip |
buffers: handle bad length argument in constructor
Coerce fractional, negative and non-numeric length arguments to numbers.
Fractional numbers are rounded up, negative numbers and non-numeric values
are set to zero.
Diffstat (limited to 'lib/buffer.js')
-rw-r--r-- | lib/buffer.js | 15 |
1 files changed, 12 insertions, 3 deletions
diff --git a/lib/buffer.js b/lib/buffer.js index 91fd67706..25dfaab04 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -196,6 +196,15 @@ 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; +} + + // Buffer function Buffer(subject, encoding, offset) { @@ -207,14 +216,14 @@ function Buffer(subject, encoding, offset) { // Are we slicing? if (typeof offset === 'number') { - this.length = encoding; + this.length = coerce(encoding); this.parent = subject; this.offset = offset; } else { // Find the length switch (type = typeof subject) { case 'number': - this.length = subject; + this.length = coerce(subject); break; case 'string': @@ -222,7 +231,7 @@ function Buffer(subject, encoding, offset) { break; case 'object': // Assume object is an array - this.length = subject.length; + this.length = coerce(subject.length); break; default: |