From 22f194241195f105751f88b7b981313fac24c240 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Thu, 26 Sep 2024 19:00:40 -0700 Subject: [PATCH] fix Buffer.fill with a non-null empty fill including uninitialized bytes --- src/bun.js/bindings/JSBuffer.cpp | 5 +++++ test/js/node/buffer.test.js | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/src/bun.js/bindings/JSBuffer.cpp b/src/bun.js/bindings/JSBuffer.cpp index 8a0aea2c36c00..c88626f780e05 100644 --- a/src/bun.js/bindings/JSBuffer.cpp +++ b/src/bun.js/bindings/JSBuffer.cpp @@ -601,6 +601,11 @@ static inline JSC::EncodedJSValue jsBufferConstructorFunction_allocBody(JSC::JSG } auto startPtr = uint8Array->typedVector() + start; auto str_ = value.toWTFString(lexicalGlobalObject); + if (str_.isEmpty()) { + memset(startPtr, 0, length); + RELEASE_AND_RETURN(scope, JSC::JSValue::encode(uint8Array)); + } + ZigString str = Zig::toZigString(str_); if (UNLIKELY(!Bun__Buffer_fill(&str, startPtr, end - start, encoding))) { diff --git a/test/js/node/buffer.test.js b/test/js/node/buffer.test.js index 17f25ec067a9b..9b3c6459fbad6 100644 --- a/test/js/node/buffer.test.js +++ b/test/js/node/buffer.test.js @@ -964,6 +964,10 @@ for (let withOverridenBufferWrite of [false, true]) { expect(buf[4]).toBe(128); }); + it("fill(N, empty string) should be the same as fill(N) and not include any uninitialized bytes", () => { + expect(Buffer.alloc(100, "")).toEqual(Buffer.alloc(100)); + }); + // https://github.com/joyent/node/issues/1758 it("check for fractional length args, junk length args, etc.", () => { // Call .fill() first, stops valgrind warning about uninitialized memory reads.