diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 773b3341821f82..8c1e503a52ff00 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -642,6 +642,12 @@ void Fill(const FunctionCallbackInfo& args) { size_t in_there = str_length; char* ptr = ts_obj_data + start + str_length; + if (in_there == 0) { + // Just use zero-fill if the input was empty + memset(ts_obj_data + start, 0, fill_length); + return; + } + while (in_there < fill_length - in_there) { memcpy(ptr, ts_obj_data + start, in_there); ptr += in_there; diff --git a/test/parallel/test-buffer-alloc-is-filled.js b/test/parallel/test-buffer-alloc-is-filled.js new file mode 100644 index 00000000000000..bd6bdb6f29f30b --- /dev/null +++ b/test/parallel/test-buffer-alloc-is-filled.js @@ -0,0 +1,20 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); + +for (const fill of [ + '', + [], + Buffer.from(''), + new Uint8Array(0), + { toString: () => '' }, + { toString: () => '', length: 10 } +]) { + for (let i = 0; i < 50; i++) { + const buf = Buffer.alloc(100, fill); + assert.strictEqual(buf.length, 100); + for (let n = 0; n < buf.length; n++) + assert.strictEqual(buf[n], 0); + } +} diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 4d9c018c7f7410..ebdb49d8e85e02 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -349,6 +349,22 @@ Buffer.alloc(8, ''); assert.strictEqual(buf.toString(), 'էէէէէ'); } +{ + for (const fill of [ + '', + [], + Buffer.from(''), + new Uint8Array(0), + { toString: () => '' }, + { toString: () => '', length: 10 } + ]) { + assert.deepStrictEqual( + Buffer.alloc(10, 'abc').fill(fill), + Buffer.alloc(10) + ); + } +} + // Testing public API. Make sure "start" is properly checked, even if it's // magically mangled using Symbol.toPrimitive. {