Truly independent web browser
LibWeb: Implement TextEncoder in Rust
Aliaksandr Kalenik45d6d1874f7a
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rsnew file mode 100644index 00000000000..2dde28b8241--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs@@ -0,0 +1,11 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Encoding Standard, https://encoding.spec.whatwg.org/++#[cfg(not(test))]+pub(crate) mod text_encoder;+pub(crate) mod utf8;diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rsnew file mode 100644index 00000000000..0be31c2d685--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rs@@ -0,0 +1,176 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! TextEncoder, https://encoding.spec.whatwg.org/#interface-textencoder++use core::mem::MaybeUninit;++use ak::Utf16String;+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, ErrorType, Gc, Trace, TypedArrayBase, TypedArrayKind,+ create_typed_array_on_buffer, is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record,+ typed_array_byte_length,+};++use crate::bindings::conversions::UsvString;+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::encoding::utf8::{self, EncodeIntoProgress};++/// A TextEncoder has no state: it always encodes UTF-8.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TextEncoder;++/// The dictionary TextEncoderEncodeIntoResult of Encoding/TextEncoder.idl, whose members the bindings convert.+pub(crate) struct TextEncoderEncodeIntoResult {+ pub(crate) read: Option<u64>,+ pub(crate) written: Option<u64>,+}++fn encode_into_result(progress: EncodeIntoProgress) -> TextEncoderEncodeIntoResult {+ TextEncoderEncodeIntoResult {+ read: Some(progress.read as u64),+ written: Some(progress.written as u64),+ }+}++/// Every code unit encodes to at most three bytes, so a source of that many bytes fits a destination without the+/// encoding being measured first.+const MAX_UTF8_BYTES_PER_CODE_UNIT: usize = 3;++#[expect(+ clippy::unnecessary_wraps,+ reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"+)]+impl TextEncoder {+ // https://encoding.spec.whatwg.org/#dom-textencoder+ pub(crate) fn construct(_: &mut CallContext) -> WebIdlResult<Self> {+ // The new TextEncoder() constructor steps are to do nothing.+ Ok(Self)+ }++ // https://encoding.spec.whatwg.org/#dom-textencoder-encoding+ pub(crate) fn encoding(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ // The encoding getter steps are to return "utf-8".+ Ok(Utf16String::from_ascii(b"utf-8"))+ }++ // https://encoding.spec.whatwg.org/#dom-textencoder-encode+ pub(crate) fn encode(&self, cx: &mut CallContext, input: UsvString) -> WebIdlResult<Gc<TypedArrayBase>> {+ // 1. Convert input to an I/O queue of scalar values.+ // 2. Let output be the I/O queue of bytes « end-of-queue ».+ // 3. While true:+ // 1. Let item be the result of reading from input.+ // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder,+ // input, output, and "fatal".+ // 3. Assert: result is not an error.+ // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object+ // wrapping an ArrayBuffer containing output.+ let length = input.utf8_length();+ let array_length = u32::try_from(length)+ .map_err(|_| Exception::RangeError(ErrorType::InvalidLength.message(&[&"typed array"])))?;+ let buffer =+ ArrayBuffer::try_create_written_by(cx.vm(), cx.realm(), length, ArrayBufferShared::No, |output| {+ // SAFETY: The buffer has the length of the encoding.+ unsafe { input.encode_utf8(output) }+ })?;+ Ok(create_typed_array_on_buffer(+ cx.vm(),+ cx.realm(),+ TypedArrayKind::Uint8Array,+ array_length,+ buffer,+ ))+ }++ // https://encoding.spec.whatwg.org/#dom-textencoder-encodeinto+ pub(crate) fn encode_into(+ &self,+ _: &mut CallContext,+ source: UsvString,+ destination: Gc<TypedArrayBase>,+ ) -> WebIdlResult<TextEncoderEncodeIntoResult> {+ // AD-HOC: Return early if destination is detached. This is not explicitly handled in the spec, however no+ // bytes are copied as the destination's size is always zero in this case.+ // See: https://github.com/whatwg/encoding/issues/324+ let buffer = destination.viewed_array_buffer();+ if buffer.is_detached() {+ return Ok(encode_into_result(EncodeIntoProgress { read: 0, written: 0 }));+ }+ let destination_record = make_typed_array_with_buffer_witness_record(&destination, ArrayBufferOrder::SeqCst);+ if is_typed_array_out_of_bounds(&destination_record) {+ return Ok(encode_into_result(EncodeIntoProgress { read: 0, written: 0 }));+ }+ let destination_byte_length = typed_array_byte_length(&destination_record) as usize;+ if destination_byte_length == 0 {+ return Ok(encode_into_result(EncodeIntoProgress { read: 0, written: 0 }));+ }+ let destination_bytes =+ buffer.with_data_block(|data_block| data_block.data_at(destination.byte_offset() as usize));+ assert!(!destination_bytes.is_null());++ // OPTIMIZATION: Encode the whole source at once into a destination that is not shared when it fits.+ // Shared destinations stay on the incremental path, which keeps their writes the same.+ if !buffer.is_shared_array_buffer() {+ let fits = source.length_in_code_units() * MAX_UTF8_BYTES_PER_CODE_UNIT <= destination_byte_length+ || source.utf8_length() <= destination_byte_length;+ if fits {+ // SAFETY: The destination views `destination_byte_length` bytes of the buffer from its byte offset,+ // which nothing else accesses while this runs, as the buffer is not shared, and which the+ // encoding fits.+ let written = unsafe {+ let output = core::slice::from_raw_parts_mut(+ destination_bytes.cast::<MaybeUninit<u8>>(),+ destination_byte_length,+ );+ source.encode_utf8(output)+ };+ return Ok(encode_into_result(EncodeIntoProgress {+ read: source.length_in_code_units(),+ written,+ }));+ }+ }++ // 1. Let read be 0.+ // 2. Let written be 0.+ // 3. Let encoder be an instance of the UTF-8 encoder.+ // 4. Let unused be the I/O queue of scalar values « end-of-queue ».+ // 5. Convert source to an I/O queue of scalar values.+ // 6. While true:+ // 1. Let item be the result of reading from source.+ // 2. Let result be the result of running encoder's handler on unused and item.+ // 3. If result is finished, then break.+ // 4. Otherwise:+ // 1. If destination's byte length − written is greater than or equal to the number of bytes in+ // result, then:+ // 1. If item is greater than U+FFFF, then increment read by 2.+ // 2. Otherwise, increment read by 1.+ // 3. Write the bytes in result into destination, with startingOffset set to written.+ // 4. Increment written by the number of bytes in result.+ // 2. Otherwise, break.+ // 7. Return «[ "read" → read, "written" → written ]».+ let units = source.units();+ let progress = if buffer.is_shared_array_buffer() {+ // WARNING: See the warning for SharedArrayBuffer objects at+ // https://encoding.spec.whatwg.org/#sharedarraybuffer-warning. Another thread can access the+ // bytes at any time, so they are only written through raw copies.+ utf8::encode_into(&units, destination_byte_length, |offset, bytes| {+ // SAFETY: The encoder writes within the destination's byte length.+ unsafe {+ core::ptr::copy_nonoverlapping(bytes.as_ptr(), destination_bytes.add(offset), bytes.len());+ }+ })+ } else {+ // SAFETY: Nothing else accesses the bytes of a buffer that is not shared while this runs.+ let output = unsafe { core::slice::from_raw_parts_mut(destination_bytes, destination_byte_length) };+ utf8::encode_into(&units, destination_byte_length, |offset, bytes| {+ output[offset..offset + bytes.len()].copy_from_slice(bytes);+ })+ };+ Ok(encode_into_result(progress))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/utf8.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/utf8.rsnew file mode 100644index 00000000000..1e68b9bbaca--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/utf8.rs@@ -0,0 +1,109 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The UTF-8 encoder, https://encoding.spec.whatwg.org/#utf-8-encoder, encoding a string in AK's representation one+//! scalar value at a time.++use ak::Utf16StringUnits;++/// The scalar values of a string with UTF-16 storage, each with the number of code units it takes. A lone surrogate+/// reads as U+FFFD, which takes as many code units.+fn scalar_values(code_units: &[u16]) -> impl Iterator<Item = (char, usize)> + '_ {+ char::decode_utf16(code_units.iter().copied()).map(|scalar_value| match scalar_value {+ Ok(scalar_value) => (scalar_value, scalar_value.len_utf16()),+ Err(_) => (char::REPLACEMENT_CHARACTER, 1),+ })+}++/// The number of code units read and of bytes written by the encodeInto() algorithm,+/// https://encoding.spec.whatwg.org/#dom-textencoder-encodeinto+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct EncodeIntoProgress {+ pub(crate) read: usize,+ pub(crate) written: usize,+}++/// Encodes the scalar values of the string that fit in `capacity` bytes, in order, and stops at the first one that+/// does not. `write` stores bytes at the offset it is given.+pub(crate) fn encode_into(+ units: &Utf16StringUnits<'_>,+ capacity: usize,+ mut write: impl FnMut(usize, &[u8]),+) -> EncodeIntoProgress {+ match units {+ Utf16StringUnits::Ascii(bytes) => {+ // Every scalar value of ASCII storage is one code unit and one byte.+ let length = bytes.len().min(capacity);+ write(0, &bytes[..length]);+ EncodeIntoProgress {+ read: length,+ written: length,+ }+ }+ Utf16StringUnits::Utf16(code_units) => {+ let mut progress = EncodeIntoProgress { read: 0, written: 0 };+ let mut bytes = [0; 4];+ for (scalar_value, code_unit_count) in scalar_values(code_units) {+ let encoded = scalar_value.encode_utf8(&mut bytes);+ if capacity - progress.written < encoded.len() {+ break;+ }+ write(progress.written, encoded.as_bytes());+ progress.read += code_unit_count;+ progress.written += encoded.len();+ }+ progress+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn utf16(string: &str) -> Vec<u16> {+ string.encode_utf16().collect()+ }++ fn encoded_into(units: &Utf16StringUnits<'_>, capacity: usize) -> (EncodeIntoProgress, Vec<u8>) {+ let mut output = vec![0; capacity];+ let progress = encode_into(units, capacity, |offset, bytes| {+ output[offset..offset + bytes.len()].copy_from_slice(bytes);+ });+ (progress, output)+ }++ #[test]+ fn encode_into_encodes_lone_surrogates_as_replacement_characters() {+ let string = [0x61, 0xD800, 0x62, 0xDC00];+ let (progress, output) = encoded_into(&Utf16StringUnits::Utf16(&string), 8);+ assert_eq!(progress, EncodeIntoProgress { read: 4, written: 8 });+ assert_eq!(output, [0x61, 0xEF, 0xBF, 0xBD, 0x62, 0xEF, 0xBF, 0xBD]);+ }++ #[test]+ fn encode_into_stops_before_a_scalar_value_that_does_not_fit() {+ let string = utf16("ab\u{1F600}c");+ let (progress, output) = encoded_into(&Utf16StringUnits::Utf16(&string), 5);+ assert_eq!(progress, EncodeIntoProgress { read: 2, written: 2 });+ assert_eq!(output, [0x61, 0x62, 0, 0, 0]);++ let (progress, output) = encoded_into(&Utf16StringUnits::Utf16(&string), 6);+ assert_eq!(progress, EncodeIntoProgress { read: 4, written: 6 });+ assert_eq!(output, [0x61, 0x62, 0xF0, 0x9F, 0x98, 0x80]);+ }++ #[test]+ fn encode_into_counts_code_units_read() {+ let string = utf16("\u{E9}\u{1F600}");+ let (progress, _) = encoded_into(&Utf16StringUnits::Utf16(&string), 16);+ assert_eq!(progress, EncodeIntoProgress { read: 3, written: 6 });++ let (progress, output) = encoded_into(&Utf16StringUnits::Ascii(b"xyz"), 2);+ assert_eq!(progress, EncodeIntoProgress { read: 2, written: 2 });+ assert_eq!(output, b"xy");+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 0c3a4274fca..3c6e6545fd7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -28,6 +28,11 @@ mod rust_panic;reason = "the generated bindings use only the conversions their interfaces need")]pub(crate) mod bindings;+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+pub(crate) mod encoding;// NB: Only C++ calls into libweb_rust, so nothing in this crate names it. Linking it keeps its extern "C" functions in// the static library.diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex ef45793dd16..a98413f02d7 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -356,7 +356,6 @@ set(SOURCESEncoding/TextDecoder.cppEncoding/TextDecoderCommon.cppEncoding/TextDecoderStream.cpp- Encoding/TextEncoder.cppEncoding/TextEncoderCommon.cppEncoding/TextEncoderStream.cppEncryptedMediaExtensions/Algorithms.cppdiff --git a/Libraries/LibWeb/Encoding/TextEncoder.cpp b/Libraries/LibWeb/Encoding/TextEncoder.cppdeleted file mode 100644index 30ea5d6cc30..00000000000--- a/Libraries/LibWeb/Encoding/TextEncoder.cpp+++ /dev/null@@ -1,138 +0,0 @@-/*- * Copyright (c) 2021-2022, Linus Groh <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Bindings/TextEncoder.h>-#include <LibWeb/Encoding/TextEncoder.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Encoding {--GC_DEFINE_ALLOCATOR(TextEncoder);--GC::Ref<TextEncoder> TextEncoder::create()-{- return GC::Heap::the().allocate<TextEncoder>();-}--TextEncoder::TextEncoder()-{-}--TextEncoder::~TextEncoder() = default;--// https://encoding.spec.whatwg.org/#dom-textencoder-encode-ErrorOr<ByteBuffer> TextEncoder::encode_to_byte_buffer(Utf16String const& input) const-{- // 1. Convert input to an I/O queue of scalar values.- // 2. Let output be the I/O queue of bytes « end-of-queue ».- // 3. While true:- // 1. Let item be the result of reading from input.- // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder, input, output, and "fatal".- // 3. Assert: result is not an error.- // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.-- auto utf8_input = input.to_utf8();- return ByteBuffer::copy(utf8_input.bytes());-}--WebIDL::ExceptionOr<GC::Ref<JS::Uint8Array>> TextEncoder::encode(JS::Object const& relevant_global_object, Utf16String const& input) const-{- auto& target = HTML::relevant_realm(relevant_global_object);- auto byte_buffer = TRY_OR_THROW_OOM(target.vm(), encode_to_byte_buffer(input));- auto array_length = byte_buffer.size();- auto array_buffer = JS::ArrayBuffer::create(target, move(byte_buffer));- return JS::Uint8Array::create(target, array_length, *array_buffer);-}--// https://encoding.spec.whatwg.org/#dom-textencoder-encodeinto-EncodeIntoResult TextEncoder::encode_into_result(Utf16String const& source, GC::Root<JS::Uint8Array> const& destination) const-{- // AD-HOC: Return early if destination is detached. This is not explicitly handled in the spec,- // however no bytes are copied as destinations size is always zero in this case.- // See: https://github.com/whatwg/encoding/issues/324- if (destination->viewed_array_buffer()->is_detached())- return { 0, 0 };-- auto destination_record = JS::make_typed_array_with_buffer_witness_record(*destination, JS::ArrayBuffer::Order::SeqCst);- if (JS::is_typed_array_out_of_bounds(destination_record))- return { 0, 0 };- auto destination_byte_length = JS::typed_array_byte_length(destination_record);-- // OPTIMIZATION: Encode directly into a non-shared destination when the input fits.- // Keep shared destinations on the existing path to avoid changing shared-memory write semantics.- auto& destination_buffer = *destination->viewed_array_buffer();- if (!destination_buffer.is_shared_array_buffer()) {- auto destination_bytes = Bytes { destination_buffer.data_at(destination->byte_offset()), destination_byte_length };- if (auto bytes_written = source.utf16_view().to_utf8_with_replacement_into(destination_bytes); bytes_written.has_value())- return { source.length_in_code_units(), *bytes_written };- }-- // 1. Let read be 0.- WebIDL::UnsignedLongLong read = 0;- // 2. Let written be 0.- WebIDL::UnsignedLongLong written = 0;-- // 3. Let encoder be an instance of the UTF-8 encoder.- // 4. Let unused be the I/O queue of scalar values « end-of-queue ».- // 5. Convert source to an I/O queue of scalar values.- auto it = source.utf16_view().begin();- auto end = source.utf16_view().end();-- // 6. While true:- while (true) {- // 6.1. Let item be the result of reading from source.- // 6.2. Let result be the result of running encoder’s handler on unused and item.- // 6.3. If result is finished, then break.- if (it == end)- break;- auto item = *it;- auto code_unit_length = it.length_in_code_units();-- Array<u8, 4> result;- size_t result_size = 0;- (void)AK::UnicodeUtils::code_point_to_utf8(item, [&](char byte) {- result[result_size++] = static_cast<u8>(byte);- });-- // 6.4. Otherwise:- // 6.4.1. If destination’s byte length − written is greater than or equal to the number of bytes in result, then:- if (destination_byte_length - written >= result_size) {- // 6.4.1.1. If item is greater than U+FFFF, then increment read by 2.- // 6.4.1.2. Otherwise, increment read by 1.- read += code_unit_length;-- // 6.4.1.3. Write the bytes in result into destination, with startingOffset set to written.- // 6.4.1.4. Increment written by the number of bytes in result.- // WARNING: See the warning for SharedArrayBuffer objects at https://encoding.spec.whatwg.org/#sharedarraybuffer-warning.- destination->viewed_array_buffer()->overwrite(destination->byte_offset() + written, result.data(), result_size);- written += result_size;- }- // 6.4.2. Otherwise, break.- else {- break;- }-- ++it;- }-- // 7. Return «[ "read" → read, "written" → written ]».- return { read, written };-}--Bindings::TextEncoderEncodeIntoResult TextEncoder::encode_into(Utf16String const& source, GC::Root<JS::Uint8Array> const& destination) const-{- auto result = encode_into_result(source, destination);- return {- .read = result.read,- .written = result.written,- };-}--}diff --git a/Libraries/LibWeb/Encoding/TextEncoder.h b/Libraries/LibWeb/Encoding/TextEncoder.hdeleted file mode 100644index cf9ef282ef3..00000000000--- a/Libraries/LibWeb/Encoding/TextEncoder.h+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright (c) 2021, Linus Groh <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/NonnullRefPtr.h>-#include <AK/RefCounted.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Encoding/TextEncoderCommon.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::Bindings {--struct TextEncoderEncodeIntoResult;--}--namespace Web::Encoding {--struct EncodeIntoResult {- WebIDL::UnsignedLongLong read { 0 };- WebIDL::UnsignedLongLong written { 0 };-};--// https://encoding.spec.whatwg.org/#textencoder-class TextEncoder final- : public Bindings::GCAllocatedWrappable- , public TextEncoderCommonMixin {- WEB_WRAPPABLE(TextEncoder, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(TextEncoder);--public:- [[nodiscard]] static GC::Ref<TextEncoder> create();-- virtual ~TextEncoder() override;-- ErrorOr<ByteBuffer> encode_to_byte_buffer(Utf16String const& input) const;- WebIDL::ExceptionOr<GC::Ref<JS::Uint8Array>> encode(JS::Object const& relevant_global_object, Utf16String const& input) const;- EncodeIntoResult encode_into_result(Utf16String const& source, GC::Root<JS::Uint8Array> const& destination) const;- Bindings::TextEncoderEncodeIntoResult encode_into(Utf16String const& source, GC::Root<JS::Uint8Array> const& destination) const;--protected:- // https://encoding.spec.whatwg.org/#dom-textencoder- explicit TextEncoder();-};--}diff --git a/Libraries/LibWeb/Encoding/TextEncoder.idl b/Libraries/LibWeb/Encoding/TextEncoder.idlindex bc17de21dfb..695428271d7 100644--- a/Libraries/LibWeb/Encoding/TextEncoder.idl+++ b/Libraries/LibWeb/Encoding/TextEncoder.idl@@ -5,7 +5,7 @@ dictionary TextEncoderEncodeIntoResult {};// https://encoding.spec.whatwg.org/#textencoder-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface TextEncoder {constructor();diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 5ae4b2562b8..367d109267e 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -555,7 +555,6 @@ enum class HistoryAction : u8;namespace Web::Encoding {class TextDecoder;-class TextEncoder;class TextEncoderStream;}