Skip to content

Commit aa1140e

Browse files
targosrvagg
authored andcommitted
buffer: SlowBuffer only accept valid numeric values
Fixes a regression that appeared with the new Buffer implementation in v3. Without this change, calling the SlowBuffer constructor with something else than a number would abort on the C++ side. This makes sure that the length argument is coerced to number or is 0. Fixes: #2634 PR-URL: #2635 Reviewed-By: trevnorris - Trevor Norris <[email protected]> Reviewed-By: cjihrig - Colin Ihrig <[email protected]>
1 parent 2ffb21b commit aa1140e

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

lib/buffer.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@ createPool();
5858

5959

6060
function SlowBuffer(length) {
61-
if (length < 0)
61+
if (+length != length)
6262
length = 0;
63-
return binding.create(length);
63+
return binding.create(+length);
6464
};
6565

6666
SlowBuffer.prototype.__proto__ = Buffer.prototype;

test/parallel/test-buffer-slow.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const buffer = require('buffer');
6+
const Buffer = buffer.Buffer;
7+
const SlowBuffer = buffer.SlowBuffer;
8+
9+
const ones = [1, 1, 1, 1];
10+
11+
// should create a Buffer
12+
let sb = new SlowBuffer(4);
13+
assert(sb instanceof Buffer);
14+
assert.strictEqual(sb.length, 4);
15+
sb.fill(1);
16+
assert.deepEqual(sb, ones);
17+
18+
// underlying ArrayBuffer should have the same length
19+
assert.strictEqual(sb.buffer.byteLength, 4);
20+
21+
// should work without new
22+
sb = SlowBuffer(4);
23+
assert(sb instanceof Buffer);
24+
assert.strictEqual(sb.length, 4);
25+
sb.fill(1);
26+
assert.deepEqual(sb, ones);
27+
28+
// should work with edge cases
29+
assert.strictEqual(SlowBuffer(0).length, 0);
30+
try {
31+
assert.strictEqual(SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength);
32+
} catch (e) {
33+
assert.equal(e.message, 'Buffer allocation failed - process out of memory');
34+
}
35+
36+
// should work with number-coercible values
37+
assert.strictEqual(SlowBuffer('6').length, 6);
38+
assert.strictEqual(SlowBuffer(true).length, 1);
39+
40+
// should create zero-length buffer if parameter is not a number
41+
assert.strictEqual(SlowBuffer().length, 0);
42+
assert.strictEqual(SlowBuffer(NaN).length, 0);
43+
assert.strictEqual(SlowBuffer({}).length, 0);
44+
assert.strictEqual(SlowBuffer('string').length, 0);
45+
46+
// should throw with invalid length
47+
assert.throws(function() {
48+
new SlowBuffer(Infinity);
49+
}, 'invalid Buffer length');
50+
assert.throws(function() {
51+
new SlowBuffer(-1);
52+
}, 'invalid Buffer length');
53+
assert.throws(function() {
54+
new SlowBuffer(buffer.kMaxLength + 1);
55+
}, 'invalid Buffer length');

0 commit comments

Comments
 (0)