Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 34 additions & 96 deletions src/jsc/modules/NodeBufferModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,113 +14,51 @@ namespace Zig {
using namespace WebCore;
using namespace JSC;

// TODO: Add DOMJIT fast path
JSC_DEFINE_HOST_FUNCTION(jsBufferConstructorFunction_isUtf8,
(JSC::JSGlobalObject * lexicalGlobalObject,
JSC::CallFrame* callframe))
// Port of Node's buffer.isUtf8() / buffer.isAscii() argument handling:
// https://github.com/nodejs/node/blob/v26.3.0/lib/buffer.js#L1415-L1429
// https://github.com/nodejs/node/blob/v26.3.0/src/node_buffer.cc#L1305-L1333
Comment thread
robobun marked this conversation as resolved.
Resolved
template<typename Validate>
static JSC::EncodedJSValue validateBytesOf(JSC::JSGlobalObject* globalObject, JSC::JSValue input, Validate validate)
{
auto throwScope = DECLARE_THROW_SCOPE(lexicalGlobalObject->vm());

auto buffer = callframe->argument(0);
auto* bufferView = dynamicDowncast<JSC::JSArrayBufferView>(buffer);
const char* ptr = nullptr;
size_t byteLength = 0;
if (bufferView) {
if (bufferView->isDetached()) [[unlikely]] {
throwTypeError(lexicalGlobalObject, throwScope,
"ArrayBufferView is detached"_s);
return {};
}

byteLength = bufferView->byteLength();

if (byteLength == 0) {
return JSValue::encode(jsBoolean(true));
}

ptr = reinterpret_cast<const char*>(bufferView->vector());
} else if (auto* arrayBuffer = dynamicDowncast<JSC::JSArrayBuffer>(buffer)) {
auto* impl = arrayBuffer->impl();

if (!impl) {
return JSValue::encode(jsBoolean(true));
}

if (impl->isDetached()) [[unlikely]] {
return Bun::ERR::INVALID_STATE(throwScope, lexicalGlobalObject,
"Cannot validate on a detached buffer"_s);
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());

std::span<const uint8_t> bytes;
// isTypedArrayType() excludes DataView, which Node rejects. A view whose buffer was detached
// has a byteLength of 0 and validates as empty; Node only throws for the ArrayBuffer itself.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (auto* view = dynamicDowncast<JSC::JSArrayBufferView>(input); view && isTypedArrayType(view->type())) {
bytes = view->span();
} else if (auto* arrayBuffer = dynamicDowncast<JSC::JSArrayBuffer>(input)) {
if (arrayBuffer->impl()->isDetached()) [[unlikely]] {
// Thrown from C++ in Node too, so without the "Invalid state: " prefix Bun::ERR::INVALID_STATE adds.
return Bun::throwError(globalObject, scope, Bun::ErrorCode::ERR_INVALID_STATE, "Cannot validate on a detached buffer"_s);
}

byteLength = impl->byteLength();

if (byteLength == 0) {
return JSValue::encode(jsBoolean(true));
}

ptr = reinterpret_cast<const char*>(impl->data());
bytes = arrayBuffer->impl()->span();
} else {
Bun::throwError(lexicalGlobalObject, throwScope,
Bun::ErrorCode::ERR_INVALID_ARG_TYPE,
"First argument must be an ArrayBufferView"_s);
return {};
return Bun::ERR::INVALID_ARG_INSTANCE(scope, globalObject, "input"_s, "ArrayBuffer, Buffer, or TypedArray"_s, input);
}

RELEASE_AND_RETURN(throwScope, JSValue::encode(jsBoolean(simdutf::validate_utf8(ptr, byteLength))));
if (bytes.empty())
return JSValue::encode(jsBoolean(true));

return JSValue::encode(jsBoolean(validate(reinterpret_cast<const char*>(bytes.data()), bytes.size())));
}

// TODO: Add DOMJIT fast path
JSC_DEFINE_HOST_FUNCTION(jsBufferConstructorFunction_isAscii,
JSC_DEFINE_HOST_FUNCTION(jsBufferConstructorFunction_isUtf8,
(JSC::JSGlobalObject * lexicalGlobalObject,
JSC::CallFrame* callframe))
{
auto throwScope = DECLARE_THROW_SCOPE(lexicalGlobalObject->vm());

auto buffer = callframe->argument(0);
auto* bufferView = dynamicDowncast<JSC::JSArrayBufferView>(buffer);
const char* ptr = nullptr;
size_t byteLength = 0;
if (bufferView) {

if (bufferView->isDetached()) [[unlikely]] {
return Bun::ERR::INVALID_STATE(throwScope, lexicalGlobalObject,
"Cannot validate on a detached buffer"_s);
}

byteLength = bufferView->byteLength();

if (byteLength == 0) {
return JSValue::encode(jsBoolean(true));
}

ptr = reinterpret_cast<const char*>(bufferView->vector());
} else if (auto* arrayBuffer = dynamicDowncast<JSC::JSArrayBuffer>(buffer)) {
auto* impl = arrayBuffer->impl();
if (impl->isDetached()) [[unlikely]] {
return Bun::ERR::INVALID_STATE(throwScope, lexicalGlobalObject,
"Cannot validate on a detached buffer"_s);
}

if (!impl) {
return JSValue::encode(jsBoolean(true));
}

byteLength = impl->byteLength();

if (byteLength == 0) {
return JSValue::encode(jsBoolean(true));
}

ptr = reinterpret_cast<const char*>(impl->data());
} else {
Bun::throwError(lexicalGlobalObject, throwScope,
Bun::ErrorCode::ERR_INVALID_ARG_TYPE,
"First argument must be an ArrayBufferView"_s);
return {};
}
return validateBytesOf(lexicalGlobalObject, callframe->argument(0), [](const char* data, size_t length) {
return simdutf::validate_utf8(data, length);
});
}

RELEASE_AND_RETURN(
throwScope,
JSValue::encode(jsBoolean(simdutf::validate_ascii(ptr, byteLength))));
JSC_DEFINE_HOST_FUNCTION(jsBufferConstructorFunction_isAscii,
(JSC::JSGlobalObject * lexicalGlobalObject,
JSC::CallFrame* callframe))
{
return validateBytesOf(lexicalGlobalObject, callframe->argument(0), [](const char* data, size_t length) {
return simdutf::validate_ascii(data, length);
});
}

BUN_DECLARE_HOST_FUNCTION(jsFunctionResolveObjectURL);
Expand Down
86 changes: 86 additions & 0 deletions test/js/node/buffer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4746,3 +4746,89 @@ it.skipIf(os.totalmem() < 10 * 1024 ** 3)(
expect(exitCode).toBe(0);
},
);

describe.each([
["isUtf8", isUtf8],
["isAscii", isAscii],
])("buffer.%s() input handling", (name, validate) => {
// "ab" followed by "é" in UTF-8: valid UTF-8, not ASCII. 8 bytes so every TypedArray kind can view it.
const bytes = [0x61, 0x62, 0x20, 0x20, 0x20, 0x20, 0xc3, 0xa9];
const expected = name === "isUtf8";
const invalidInput = received =>
expect.objectContaining({
name: "TypeError",
code: "ERR_INVALID_ARG_TYPE",
message: `The "input" argument must be an instance of ArrayBuffer, Buffer, or TypedArray. Received ${received}`,
});

// Node types the parameter as TypedArray | ArrayBuffer | Buffer. A DataView is an ArrayBufferView
// in JSC as well, but it is not a TypedArray, so it is rejected like any other object.
it.each([
["the whole buffer", ab => new DataView(ab)],
["a sub-range", ab => new DataView(ab, 2, 4)],
["zero bytes", () => new DataView(new ArrayBuffer(0))],
])("rejects a DataView over %s", (_, makeView) => {
expect(() => validate(makeView(new Uint8Array(bytes).buffer))).toThrow(invalidInput("an instance of DataView"));
});

it.each([
["undefined", undefined, "undefined"],
["null", null, "null"],
["a string", "abc", "type string ('abc')"],
["a number", 1, "type number (1)"],
["a plain object", {}, "an instance of Object"],
["an array of bytes", [0x61], "an instance of Array"],
])("rejects %s with Node's message", (_, input, received) => {
expect(() => validate(input)).toThrow(invalidInput(received));
});

it("throws ERR_INVALID_STATE for a detached ArrayBuffer", () => {
const ab = new Uint8Array(bytes).buffer;
structuredClone(ab, { transfer: [ab] });
expect(() => validate(ab)).toThrow(
expect.objectContaining({
name: "Error",
code: "ERR_INVALID_STATE",
message: "Cannot validate on a detached buffer",
}),
);
});

// Node only checks the ArrayBuffer form for detachment; a detached view reports byteLength 0
// and validates like any other empty input.
it("validates a view whose buffer was detached as empty input", () => {
const view = new Uint8Array([0xff, 0xfe]);
structuredClone(view.buffer, { transfer: [view.buffer] });
expect(view.byteLength).toBe(0);
expect(validate(view)).toBe(true);
});

it("accepts every TypedArray kind, Buffer, ArrayBuffer and SharedArrayBuffer", () => {
const ab = new Uint8Array(bytes).buffer;
const sab = new SharedArrayBuffer(bytes.length);
new Uint8Array(sab).set(bytes);
const inputs = [
new Int8Array(ab),
new Uint8Array(ab),
new Uint8ClampedArray(ab),
new Int16Array(ab),
new Uint16Array(ab),
new Int32Array(ab),
new Uint32Array(ab),
new Float16Array(ab),
new Float32Array(ab),
new Float64Array(ab),
new BigInt64Array(ab),
new BigUint64Array(ab),
Buffer.from(ab),
ab,
sab,
new Uint8Array(sab),
];
expect(inputs.map(input => validate(input))).toEqual(inputs.map(() => expected));
// The view decides which bytes are looked at: the non-ASCII tail is outside this one.
expect(validate(new Uint8Array(ab, 0, 6))).toBe(true);
expect(validate(new Uint8Array(0))).toBe(true);
expect(validate(new ArrayBuffer(0))).toBe(true);
});
});
Loading