diff --git a/lib/buffer.js b/lib/buffer.js index 8efb4cd789492b..7bad03939f5e5e 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -91,6 +91,14 @@ Object.setPrototypeOf(Buffer, Uint8Array); /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) + * + * Only pay attention to encoding if it's a string. This + * prevents accidentally sending in a number that would + * be interpreted as a start offset. + * Also, don't apply encoding if fill is a number. + * + * These comments are placed before the function to keep the text length + * down, to ensure that it remains inlineable by V8. **/ Buffer.alloc = function(size, fill, encoding) { if (typeof size !== 'number') @@ -98,14 +106,14 @@ Buffer.alloc = function(size, fill, encoding) { if (size <= 0) return createBuffer(size); if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - // Also, don't apply encoding if fill is a number. if (typeof fill !== 'number' && typeof encoding === 'string') fill = Buffer.from(fill, encoding); - return createBuffer(size, true).fill(fill); + const buf = createBuffer(size, true); + // Buffer.prototype.fill does not support filling with other buffers in v4. + // Instead, call binding.fill directly. + binding.fill(buf, fill, 0, buf.length); + return buf; } return createBuffer(size); }; diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index a90625e163c5cc..b2ca5b96e661ad 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1060,6 +1060,19 @@ assert.throws(function() { Buffer.allocUnsafe(0xFFFFFFFFF); }, RangeError); +assert(Buffer.alloc.toString().length < 600, 'Buffer.alloc is not inlineable'); + +// https://github.com/nodejs/node/issues/9226 +{ + const buf = Buffer.alloc(4, 'YQ==', 'base64'); + const expectedBuf = Buffer.from([97, 97, 97, 97]); + assert(buf.equals(expectedBuf)); +} +{ + const buf = Buffer.alloc(4, 'ab', 'ascii'); + const expectedBuf = Buffer.from([97, 98, 97, 98]); + assert(buf.equals(expectedBuf)); +} // attempt to overflow buffers, similar to previous bug in array buffers assert.throws(function() {