Skip to content

Commit d804efc

Browse files
committed
Use jsg::JsUint8Array for TextEncoder::encodeInto
jsg::BufferSource adds additional overhead and complexity that is unnecessary for this specific API. Switching to jsg::JsUint8Array yields a significant performance boost.
1 parent 54f9d9e commit d804efc

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

src/workerd/api/encoding.c++

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -486,10 +486,13 @@ jsg::BufferSource TextEncoder::encode(jsg::Lock& js, jsg::Optional<jsg::JsString
486486
}
487487

488488
TextEncoder::EncodeIntoResult TextEncoder::encodeInto(
489-
jsg::Lock& js, jsg::JsString input, jsg::BufferSource buffer) {
490-
auto handle = buffer.getHandle(js);
491-
JSG_REQUIRE(handle->IsUint8Array(), TypeError, "buffer must be a Uint8Array");
492-
return encodeIntoImpl(js, input, buffer);
489+
jsg::Lock& js, jsg::JsString input, jsg::JsUint8Array buffer) {
490+
auto result = input.writeInto(
491+
js, buffer.asArrayPtr<char>(), jsg::JsString::WriteFlags::REPLACE_INVALID_UTF8);
492+
return TextEncoder::EncodeIntoResult{
493+
.read = static_cast<int>(result.read),
494+
.written = static_cast<int>(result.written),
495+
};
493496
}
494497

495498
} // namespace workerd::api

src/workerd/api/encoding.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ class TextEncoder final: public jsg::Object {
218218

219219
jsg::BufferSource encode(jsg::Lock& js, jsg::Optional<jsg::JsString> input);
220220

221-
EncodeIntoResult encodeInto(jsg::Lock& js, jsg::JsString input, jsg::BufferSource buffer);
221+
EncodeIntoResult encodeInto(jsg::Lock& js, jsg::JsString input, jsg::JsUint8Array buffer);
222222

223223
// UTF-8 is the only encoding type supported by the WHATWG spec.
224224
kj::StringPtr getEncoding() {
@@ -239,6 +239,7 @@ class TextEncoder final: public jsg::Object {
239239
// `Uint8Array`. The spec defines that this function returns a `Uint8Array` too.
240240
JSG_TS_OVERRIDE({
241241
encode(input?: string): Uint8Array;
242+
encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;
242243
});
243244
}
244245
};

0 commit comments

Comments
 (0)