Truly independent web browser
LibTextCodec+LibWeb: Share one streaming decoder with TextDecoder
Shannon Bootha8aa4c85cf0e
diff --git a/Cargo.lock b/Cargo.lockindex 3ee9b8d67cb..b29d6ea2be4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -865,6 +865,7 @@ dependencies = ["libcompositing_rust","libgfx_rust","libjs_rust",+ "libtextcodec_rust","liburl_rust","libweb_rust","rustc-demangle",diff --git a/Libraries/LibTextCodec/Decoder.cpp b/Libraries/LibTextCodec/Decoder.cppindex 82885e40566..ec663561bba 100644--- a/Libraries/LibTextCodec/Decoder.cpp+++ b/Libraries/LibTextCodec/Decoder.cpp@@ -147,7 +147,7 @@ ErrorOr<String> rust_decode_to_utf8(StringView encoding, StringView input, Ignorreturn context.builder.to_string_without_validation();}-ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last, ErrorMode error_mode)+ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last){Utf16DecodeContext context { .builder = Utf16StringBuilder(input.size()) };auto succeeded = FFI::textcodec_rust_streaming_decoder_decode_to_utf16(@@ -155,7 +155,6 @@ ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingDinput.data(),input.size(),last,- error_mode == ErrorMode::Fatal,&context,append_decoded_utf16);if (!succeeded)@@ -194,7 +193,7 @@ Optional<StringView> get_static_encoding_name_from_rust(StringView label)return StringView { encoding_name, encoding_name_length };}-ErrorOr<String> rust_streaming_decode_to_utf8(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last, ErrorMode error_mode)+ErrorOr<String> rust_streaming_decode_to_utf8(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last){DecodeContext context { .builder = StringBuilder(input.size()) };auto succeeded = FFI::textcodec_rust_streaming_decoder_decode_to_utf8(@@ -202,7 +201,6 @@ ErrorOr<String> rust_streaming_decode_to_utf8(FFI::TextCodecRustStreamingDecoderinput.data(),input.size(),last,- error_mode == ErrorMode::Fatal,&context,append_decoded_bytes);if (!succeeded)@@ -503,12 +501,12 @@ ErrorOr<size_t> Latin1Decoder::length_in_utf16_code_units(StringView input)}StreamingDecoder::StreamingDecoder(StringView encoding, IgnoreBOM ignore_bom, ErrorMode error_mode)- : m_error_mode(error_mode){m_decoder = FFI::textcodec_rust_streaming_decoder_new(reinterpret_cast<u8 const*>(encoding.characters_without_null_termination()),encoding.length(),- ignore_bom == IgnoreBOM::No);+ error_mode == ErrorMode::Fatal,+ ignore_bom == IgnoreBOM::Yes);VERIFY(m_decoder);}@@ -519,22 +517,22 @@ StreamingDecoder::~StreamingDecoder()ErrorOr<String> StreamingDecoder::to_utf8(ReadonlyBytes input){- return rust_streaming_decode_to_utf8(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), input, false, m_error_mode);+ return rust_streaming_decode_to_utf8(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), input, false);}ErrorOr<Utf16String> StreamingDecoder::to_utf16(ReadonlyBytes input, Flush flush){- return rust_streaming_decode_to_utf16(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), input, flush == Flush::Yes, m_error_mode);+ return rust_streaming_decode_to_utf16(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), input, flush == Flush::Yes);}ErrorOr<String> StreamingDecoder::finish(){- return rust_streaming_decode_to_utf8(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), {}, true, m_error_mode);+ return rust_streaming_decode_to_utf8(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), {}, true);}ErrorOr<Utf16String> StreamingDecoder::finish_to_utf16(){- return rust_streaming_decode_to_utf16(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), {}, true, m_error_mode);+ return rust_streaming_decode_to_utf16(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), {}, true);}ErrorOr<void> UTF8Decoder::process(StringView input, Function<ErrorOr<void>(u32)> on_code_point)diff --git a/Libraries/LibTextCodec/Decoder.h b/Libraries/LibTextCodec/Decoder.hindex 0ed02d8e235..5794786a503 100644--- a/Libraries/LibTextCodec/Decoder.h+++ b/Libraries/LibTextCodec/Decoder.h@@ -62,7 +62,6 @@ public:ErrorOr<Utf16String> finish_to_utf16();private:- ErrorMode m_error_mode { ErrorMode::Replacement };void* m_decoder { nullptr };};diff --git a/Libraries/LibTextCodec/Rust/Cargo.toml b/Libraries/LibTextCodec/Rust/Cargo.tomlindex 3154c3dde5a..54dc170fd67 100644--- a/Libraries/LibTextCodec/Rust/Cargo.toml+++ b/Libraries/LibTextCodec/Rust/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2024"[lib]-crate-type = ["staticlib"]+crate-type = ["staticlib", "rlib"][features]allocator = ["dep:ladybird_allocator"]diff --git a/Libraries/LibTextCodec/Rust/src/lib.rs b/Libraries/LibTextCodec/Rust/src/lib.rsindex fba288b8a1f..b9af551a650 100644--- a/Libraries/LibTextCodec/Rust/src/lib.rs+++ b/Libraries/LibTextCodec/Rust/src/lib.rs@@ -13,9 +13,12 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;+pub mod streaming_decoder;++pub use streaming_decoder::{DecodingFailed, StreamingDecoder};+use crate::rust_panic::abort_on_panic;-use encoding_rs::CoderResult;-use encoding_rs::DecoderResult;+use ak::Utf16StringUnits;use encoding_rs::EncoderResult;use encoding_rs::Encoding;use std::ffi::c_void;@@ -25,7 +28,19 @@ type FfiUtf16Fn = unsafe extern "C" fn(ctx: *mut c_void, data: *const u16, len:type FfiCodePointFn = unsafe extern "C" fn(ctx: *mut c_void, code_point: u32);pub struct TextCodecRustStreamingDecoder {- decoder: encoding_rs::Decoder,+ decoder: StreamingDecoder,+}++/// Getting an encoding from a label, https://encoding.spec.whatwg.org/#concept-encoding-get+pub fn encoding_for_label(label: Utf16StringUnits<'_>) -> Option<&'static Encoding> {+ match label {+ Utf16StringUnits::Ascii(label) => Encoding::for_label(label),+ Utf16StringUnits::Utf16(label) => {+ // NB: Every label is ASCII, so a label with any other code unit is not one.+ let label: Option<Vec<u8>> = label.iter().map(|&unit| u8::try_from(unit).ok()).collect();+ Encoding::for_label(&label.filter(|label| label.is_ascii())?)+ }+ }}unsafe fn bytes_from_raw<'a>(bytes: *const u8, len: usize) -> Option<&'a [u8]> {@@ -123,7 +138,8 @@ pub unsafe extern "C" fn textcodec_rust_decode_to_utf8(pub unsafe extern "C" fn textcodec_rust_streaming_decoder_new(encoding_label: *const u8,encoding_label_len: usize,- remove_bom: bool,+ fatal: bool,+ ignore_bom: bool,) -> *mut TextCodecRustStreamingDecoder {unsafe {abort_on_panic(|| {@@ -133,11 +149,7 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_new(let Some(encoding) = Encoding::for_label(label) else {return std::ptr::null_mut();};- let decoder = if remove_bom {- encoding.new_decoder_with_bom_removal()- } else {- encoding.new_decoder_without_bom_handling()- };+ let decoder = StreamingDecoder::new(encoding, fatal, ignore_bom);Box::into_raw(Box::new(TextCodecRustStreamingDecoder { decoder }))})}@@ -166,7 +178,6 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_decode_to_utf8(input: *const u8,input_len: usize,last: bool,- fatal: bool,ctx: *mut c_void,on_bytes: FfiBytesFn,) -> bool {@@ -179,36 +190,13 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_decode_to_utf8(let Some(input) = bytes_from_raw(input, input_len) else {return false;};- let decoder = &mut *decoder;- let mut output = String::with_capacity(if fatal {- let Some(output_capacity) = decoder.decoder.max_utf8_buffer_length_without_replacement(input.len())- else {- return false;- };- output_capacity- } else {- let Some(output_capacity) = decoder.decoder.max_utf8_buffer_length(input.len()) else {- return false;- };- output_capacity- });-- if fatal {- let (result, _) = decoder- .decoder- .decode_to_string_without_replacement(input, &mut output, last);- if !output.is_empty() {- on_bytes(ctx, output.as_ptr(), output.len());- }- return matches!(result, DecoderResult::InputEmpty);- }-- let (result, _, _) = decoder.decoder.decode_to_string(input, &mut output, last);+ let Ok(output) = (*decoder).decoder.decode_to_utf8(input, !last) else {+ return false;+ };if !output.is_empty() {on_bytes(ctx, output.as_ptr(), output.len());}-- matches!(result, CoderResult::InputEmpty)+ true})}}@@ -223,7 +211,6 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_decode_to_utf16(input: *const u8,input_len: usize,last: bool,- fatal: bool,ctx: *mut c_void,on_utf16: FfiUtf16Fn,) -> bool {@@ -236,29 +223,13 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_decode_to_utf16(let Some(input) = bytes_from_raw(input, input_len) else {return false;};- let decoder = &mut *decoder;- let Some(output_capacity) = decoder.decoder.max_utf16_buffer_length(input.len()) else {+ let Ok(output) = (*decoder).decoder.decode_to_utf16(input, !last) else {return false;};- let mut output = vec![0u16; output_capacity];-- if fatal {- let (result, _, written) =- decoder- .decoder- .decode_to_utf16_without_replacement(input, &mut output, last);- if written > 0 {- on_utf16(ctx, output.as_ptr(), written);- }- return matches!(result, DecoderResult::InputEmpty);- }-- let (result, _, written, _) = decoder.decoder.decode_to_utf16(input, &mut output, last);- if written > 0 {- on_utf16(ctx, output.as_ptr(), written);+ if !output.is_empty() {+ on_utf16(ctx, output.as_ptr(), output.len());}-- matches!(result, CoderResult::InputEmpty)+ true})}}@@ -318,3 +289,22 @@ pub unsafe extern "C" fn textcodec_rust_encode_from_utf8(})}}++#[cfg(test)]+mod tests {+ use super::*;++ fn utf16(string: &str) -> Vec<u16> {+ string.encode_utf16().collect()+ }++ #[test]+ fn labels() {+ let name = |label: Utf16StringUnits<'_>| encoding_for_label(label).map(Encoding::name);+ assert_eq!(name(Utf16StringUnits::Ascii(b" Latin1\n")), Some("windows-1252"));+ assert_eq!(name(Utf16StringUnits::Ascii(b"nonsense")), None);+ assert_eq!(name(Utf16StringUnits::Utf16(&utf16("utf-8"))), Some("UTF-8"));+ assert_eq!(name(Utf16StringUnits::Utf16(&utf16("\u{FC}tf-8"))), None);+ assert_eq!(name(Utf16StringUnits::Utf16(&utf16("\u{175}tf-8"))), None);+ }+}diff --git a/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs b/Libraries/LibTextCodec/Rust/src/streaming_decoder.rsnew file mode 100644index 00000000000..70943372e4c--- /dev/null+++ b/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs@@ -0,0 +1,193 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Decoding a stream of bytes with the decoders of the Encoding Standard, https://encoding.spec.whatwg.org/#encodings,+//! which the encoding_rs crate implements.++use encoding_rs::{CoderResult, Decoder, DecoderResult, Encoding};++#[derive(Debug, PartialEq, Eq)]+pub struct DecodingFailed;++/// The decoder of an encoding together with the error mode and the BOM handling that it decodes with, which keeps+/// the bytes of a character that a chunk of a stream ended in until the next chunk.+pub struct StreamingDecoder {+ encoding: &'static Encoding,+ fatal: bool,+ ignore_bom: bool,+ decoder: Decoder,+}++impl StreamingDecoder {+ pub fn new(encoding: &'static Encoding, fatal: bool, ignore_bom: bool) -> Self {+ Self {+ encoding,+ fatal,+ ignore_bom,+ decoder: Self::new_decoder(encoding, ignore_bom),+ }+ }++ fn new_decoder(encoding: &'static Encoding, ignore_bom: bool) -> Decoder {+ if ignore_bom {+ encoding.new_decoder_without_bom_handling()+ } else {+ encoding.new_decoder_with_bom_removal()+ }+ }++ pub fn encoding(&self) -> &'static Encoding {+ self.encoding+ }++ pub fn fatal(&self) -> bool {+ self.fatal+ }++ pub fn ignore_bom(&self) -> bool {+ self.ignore_bom+ }++ /// Decodes the next bytes of the input to UTF-16. Unless more of the input follows, the bytes are its end: the+ /// decoder then flushes what it kept, and starts over for the next input, whether or not decoding succeeded.+ pub fn decode_to_utf16(&mut self, input: &[u8], more_input_follows: bool) -> Result<Vec<u16>, DecodingFailed> {+ let decoded = self.decode_to_utf16_with_current_decoder(input, !more_input_follows);+ self.start_over_unless_more_input_follows(more_input_follows);+ decoded+ }++ /// Decodes the next bytes of the input to UTF-8, like decode_to_utf16().+ pub fn decode_to_utf8(&mut self, input: &[u8], more_input_follows: bool) -> Result<String, DecodingFailed> {+ let decoded = self.decode_to_utf8_with_current_decoder(input, !more_input_follows);+ self.start_over_unless_more_input_follows(more_input_follows);+ decoded+ }++ fn start_over_unless_more_input_follows(&mut self, more_input_follows: bool) {+ if !more_input_follows {+ // NB: encoding_rs finishes a decoder for good once it has seen the end of its input.+ self.decoder = Self::new_decoder(self.encoding, self.ignore_bom);+ }+ }++ fn decode_to_utf16_with_current_decoder(&mut self, input: &[u8], last: bool) -> Result<Vec<u16>, DecodingFailed> {+ let output_capacity = self+ .decoder+ .max_utf16_buffer_length(input.len())+ .ok_or(DecodingFailed)?;+ let mut output = vec![0; output_capacity];++ let (input_was_consumed, written) = if self.fatal {+ let (result, _, written) = self+ .decoder+ .decode_to_utf16_without_replacement(input, &mut output, last);+ (matches!(result, DecoderResult::InputEmpty), written)+ } else {+ let (result, _, written, _) = self.decoder.decode_to_utf16(input, &mut output, last);+ (matches!(result, CoderResult::InputEmpty), written)+ };+ if !input_was_consumed {+ return Err(DecodingFailed);+ }+ output.truncate(written);+ Ok(output)+ }++ fn decode_to_utf8_with_current_decoder(&mut self, input: &[u8], last: bool) -> Result<String, DecodingFailed> {+ let output_capacity = if self.fatal {+ self.decoder.max_utf8_buffer_length_without_replacement(input.len())+ } else {+ self.decoder.max_utf8_buffer_length(input.len())+ };+ let mut output = String::with_capacity(output_capacity.ok_or(DecodingFailed)?);++ let input_was_consumed = if self.fatal {+ let (result, _) = self+ .decoder+ .decode_to_string_without_replacement(input, &mut output, last);+ matches!(result, DecoderResult::InputEmpty)+ } else {+ let (result, _, _) = self.decoder.decode_to_string(input, &mut output, last);+ matches!(result, CoderResult::InputEmpty)+ };+ if !input_was_consumed {+ return Err(DecodingFailed);+ }+ Ok(output)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn utf8_decoder(fatal: bool, ignore_bom: bool) -> StreamingDecoder {+ StreamingDecoder::new(encoding_rs::UTF_8, fatal, ignore_bom)+ }++ fn utf16(string: &str) -> Vec<u16> {+ string.encode_utf16().collect()+ }++ #[test]+ fn a_character_split_over_chunks() {+ let mut decoder = utf8_decoder(false, false);+ assert_eq!(decoder.decode_to_utf16(&[0x61, 0xE2, 0x82], true), Ok(utf16("a")));+ assert_eq!(decoder.decode_to_utf16(&[0xAC], false), Ok(utf16("\u{20AC}")));++ let mut decoder = utf8_decoder(false, false);+ assert_eq!(decoder.decode_to_utf8(&[0x61, 0xE2, 0x82], true), Ok("a".to_string()));+ assert_eq!(decoder.decode_to_utf8(&[0xAC], false), Ok("\u{20AC}".to_string()));+ }++ #[test]+ fn the_end_of_the_input_flushes_and_starts_over() {+ let mut decoder = utf8_decoder(false, false);+ assert_eq!(+ decoder.decode_to_utf16(&[0x61, 0xE2, 0x82], false),+ Ok(utf16("a\u{FFFD}"))+ );+ assert_eq!(decoder.decode_to_utf16(&[0xAC], false), Ok(utf16("\u{FFFD}")));+ assert_eq!(decoder.decode_to_utf16(&[], false), Ok(Vec::new()));+ }++ #[test]+ fn a_byte_order_mark_is_removed_once_for_every_input() {+ let mut decoder = utf8_decoder(false, false);+ assert_eq!(decoder.decode_to_utf16(&[0xEF, 0xBB, 0xBF, 0x61], true), Ok(utf16("a")));+ assert_eq!(+ decoder.decode_to_utf16(&[0xEF, 0xBB, 0xBF, 0x62], false),+ Ok(utf16("\u{FEFF}b"))+ );+ assert_eq!(+ decoder.decode_to_utf16(&[0xEF, 0xBB, 0xBF, 0x63], false),+ Ok(utf16("c"))+ );++ let mut keeping = utf8_decoder(false, true);+ assert_eq!(+ keeping.decode_to_utf16(&[0xEF, 0xBB, 0xBF, 0x61], false),+ Ok(utf16("\u{FEFF}a"))+ );+ }++ #[test]+ fn fatal_decoding_fails_on_invalid_bytes() {+ let mut decoder = utf8_decoder(true, false);+ assert_eq!(decoder.decode_to_utf16(&[0x61, 0xFF], false), Err(DecodingFailed));+ assert_eq!(decoder.decode_to_utf16(&[0x62], false), Ok(utf16("b")));+ assert_eq!(decoder.decode_to_utf16(&[0xE2, 0x82], false), Err(DecodingFailed));+ assert_eq!(decoder.decode_to_utf8(&[0x61, 0xFF], false), Err(DecodingFailed));+ }++ #[test]+ fn a_failure_in_the_middle_of_the_input_keeps_the_decoder() {+ let mut decoder = utf8_decoder(true, false);+ assert_eq!(decoder.decode_to_utf16(&[0x61, 0xFF, 0x62], true), Err(DecodingFailed));+ assert_eq!(decoder.decode_to_utf16(&[0x63], true), Ok(utf16("c")));+ assert_eq!(decoder.decode_to_utf16(&[0x64], false), Ok(utf16("d")));+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.tomlindex acf01d5bcdb..31fa7040383 100644--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml@@ -24,6 +24,7 @@ ladybird_allocator = { path = "../../../RustAllocator", optional = true }libcompositing_rust = { path = "../../../LibCompositing/Rust" }libgfx_rust = { path = "../../../LibGfx/Rust", default-features = false }libjs_rust = { path = "../../../LibJS/Rust", default-features = false }+libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }liburl_rust = { path = "../../../LibURL/Rust", default-features = false }libweb_rust = { path = "../../Rust" }rustc-demangle = "0.1"diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/decoding.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/decoding.rsdeleted file mode 100644index fbb1293b295..00000000000--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/decoding.rs+++ /dev/null@@ -1,165 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Decoding with the decoders of the Encoding Standard, https://encoding.spec.whatwg.org/#encodings, which the-//! encoding_rs crate implements.--use ak::Utf16StringUnits;-use encoding_rs::{CoderResult, Decoder, DecoderResult, Encoding};--/// Getting an encoding from a label, https://encoding.spec.whatwg.org/#concept-encoding-get-pub(crate) fn encoding_for_label(label: Utf16StringUnits<'_>) -> Option<&'static Encoding> {- match label {- Utf16StringUnits::Ascii(label) => Encoding::for_label(label),- Utf16StringUnits::Utf16(label) => {- // NB: Every label is ASCII, so a label with any other code unit is not one.- let label: Option<Vec<u8>> = label.iter().map(|&unit| u8::try_from(unit).ok()).collect();- Encoding::for_label(&label.filter(|label| label.is_ascii())?)- }- }-}--#[derive(Debug, PartialEq, Eq)]-pub(crate) struct DecodingFailed;--/// The decoder of an encoding together with the error mode and the BOM handling that it decodes with, which keeps-/// the bytes of a character that a chunk of a stream ended in until the next chunk.-pub(crate) struct StreamingDecoder {- encoding: &'static Encoding,- fatal: bool,- ignore_bom: bool,- decoder: Decoder,-}--impl StreamingDecoder {- pub(crate) fn new(encoding: &'static Encoding, fatal: bool, ignore_bom: bool) -> Self {- Self {- encoding,- fatal,- ignore_bom,- decoder: Self::new_decoder(encoding, ignore_bom),- }- }-- fn new_decoder(encoding: &'static Encoding, ignore_bom: bool) -> Decoder {- if ignore_bom {- encoding.new_decoder_without_bom_handling()- } else {- encoding.new_decoder_with_bom_removal()- }- }-- pub(crate) fn encoding(&self) -> &'static Encoding {- self.encoding- }-- pub(crate) fn fatal(&self) -> bool {- self.fatal- }-- pub(crate) fn ignore_bom(&self) -> bool {- self.ignore_bom- }-- /// Decodes the next bytes of the input to UTF-16. Unless more of the input follows, the bytes are its end: the- /// decoder then flushes what it kept, and starts over for the next input, whether or not decoding succeeded.- pub(crate) fn decode(&mut self, input: &[u8], more_input_follows: bool) -> Result<Vec<u16>, DecodingFailed> {- let decoded = self.decode_with_current_decoder(input, !more_input_follows);- if !more_input_follows {- // NB: encoding_rs finishes a decoder for good once it has seen the end of its input.- self.decoder = Self::new_decoder(self.encoding, self.ignore_bom);- }- decoded- }-- fn decode_with_current_decoder(&mut self, input: &[u8], last: bool) -> Result<Vec<u16>, DecodingFailed> {- let output_capacity = self- .decoder- .max_utf16_buffer_length(input.len())- .ok_or(DecodingFailed)?;- let mut output = vec![0; output_capacity];-- let (input_was_consumed, written) = if self.fatal {- let (result, _, written) = self- .decoder- .decode_to_utf16_without_replacement(input, &mut output, last);- (matches!(result, DecoderResult::InputEmpty), written)- } else {- let (result, _, written, _) = self.decoder.decode_to_utf16(input, &mut output, last);- (matches!(result, CoderResult::InputEmpty), written)- };- if !input_was_consumed {- return Err(DecodingFailed);- }- output.truncate(written);- Ok(output)- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn utf8_decoder(fatal: bool, ignore_bom: bool) -> StreamingDecoder {- StreamingDecoder::new(encoding_rs::UTF_8, fatal, ignore_bom)- }-- fn utf16(string: &str) -> Vec<u16> {- string.encode_utf16().collect()- }-- #[test]- fn labels() {- let name = |label: Utf16StringUnits<'_>| encoding_for_label(label).map(Encoding::name);- assert_eq!(name(Utf16StringUnits::Ascii(b" Latin1\n")), Some("windows-1252"));- assert_eq!(name(Utf16StringUnits::Ascii(b"nonsense")), None);- assert_eq!(name(Utf16StringUnits::Utf16(&utf16("utf-8"))), Some("UTF-8"));- assert_eq!(name(Utf16StringUnits::Utf16(&utf16("\u{FC}tf-8"))), None);- assert_eq!(name(Utf16StringUnits::Utf16(&utf16("\u{175}tf-8"))), None);- }-- #[test]- fn a_character_split_over_chunks() {- let mut decoder = utf8_decoder(false, false);- assert_eq!(decoder.decode(&[0x61, 0xE2, 0x82], true), Ok(utf16("a")));- assert_eq!(decoder.decode(&[0xAC], false), Ok(utf16("\u{20AC}")));- }-- #[test]- fn the_end_of_the_input_flushes_and_starts_over() {- let mut decoder = utf8_decoder(false, false);- assert_eq!(decoder.decode(&[0x61, 0xE2, 0x82], false), Ok(utf16("a\u{FFFD}")));- assert_eq!(decoder.decode(&[0xAC], false), Ok(utf16("\u{FFFD}")));- assert_eq!(decoder.decode(&[], false), Ok(Vec::new()));- }-- #[test]- fn a_byte_order_mark_is_removed_once_for_every_input() {- let mut decoder = utf8_decoder(false, false);- assert_eq!(decoder.decode(&[0xEF, 0xBB, 0xBF, 0x61], true), Ok(utf16("a")));- assert_eq!(decoder.decode(&[0xEF, 0xBB, 0xBF, 0x62], false), Ok(utf16("\u{FEFF}b")));- assert_eq!(decoder.decode(&[0xEF, 0xBB, 0xBF, 0x63], false), Ok(utf16("c")));-- let mut keeping = utf8_decoder(false, true);- assert_eq!(keeping.decode(&[0xEF, 0xBB, 0xBF, 0x61], false), Ok(utf16("\u{FEFF}a")));- }-- #[test]- fn fatal_decoding_fails_on_invalid_bytes() {- let mut decoder = utf8_decoder(true, false);- assert_eq!(decoder.decode(&[0x61, 0xFF], false), Err(DecodingFailed));- assert_eq!(decoder.decode(&[0x62], false), Ok(utf16("b")));- assert_eq!(decoder.decode(&[0xE2, 0x82], false), Err(DecodingFailed));- }-- #[test]- fn a_failure_in_the_middle_of_the_input_keeps_the_decoder() {- let mut decoder = utf8_decoder(true, false);- assert_eq!(decoder.decode(&[0x61, 0xFF, 0x62], true), Err(DecodingFailed));- assert_eq!(decoder.decode(&[0x63], true), Ok(utf16("c")));- assert_eq!(decoder.decode(&[0x64], false), Ok(utf16("d")));- }-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rsindex 087bc997916..0c8bb9fd0bc 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs@@ -6,7 +6,6 @@//! The Encoding Standard, https://encoding.spec.whatwg.org/-pub(crate) mod decoding;#[cfg(not(test))]pub(crate) mod text_decoder;#[cfg(not(test))]diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rsindex db3e618306b..939de1d6751 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs@@ -10,11 +10,11 @@ use core::cell::RefCell;use ak::Utf16String;use libjs_rust::api::Trace;+use libtextcodec_rust::{DecodingFailed, StreamingDecoder, encoding_for_label};use crate::bindings::conversions::{BufferSource, UsvString};use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, Exception, WebIdlResult};-use crate::encoding::decoding::{DecodingFailed, StreamingDecoder, encoding_for_label};/// The dictionary TextDecoderOptions of Encoding/TextDecoder.idl, whose members the bindings convert.pub(crate) struct TextDecoderOptions {@@ -110,8 +110,8 @@ impl TextDecoder {let decoded = match &input {// SAFETY: Decoding runs no script and allocates no cell, so nothing detaches, resizes or frees the// buffer of the input while its bytes are read.- Some(input) => unsafe { input.with_bytes(|bytes| decoder.decode(bytes, options.stream)) },- None => decoder.decode(&[], options.stream),+ Some(input) => unsafe { input.with_bytes(|bytes| decoder.decode_to_utf16(bytes, options.stream)) },+ None => decoder.decode_to_utf16(&[], options.stream),};let decoded =decoded.map_err(|DecodingFailed| Exception::TypeError(Utf16String::from_ascii(b"Decoding failed")))?;